diff --git a/.gitattributes b/.gitattributes index c6c7f33f023..1521fd1b08f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -182,6 +182,7 @@ Tools/Unity.BugInfo.Coverage/bin/* filter=lfs diff=lfs merge=lfs -text # search test cases /Modules/QuickSearch/Tests/QuickSearch/Assets/Cases/UUM-113048/uum-113048.index filter=lfs diff=lfs merge=lfs -text +/Editor/Modules/QuickSearch/Tests/QuickSearch/Assets/Cases/UUM-113048/uum-113048.index filter=lfs diff=lfs merge=lfs -text # SRP Templates /Templates/**/LightingData.asset filter=lfs diff=lfs merge=lfs -text diff --git a/Packages/com.unity.render-pipelines.core/Editor-PrivateShared/Tools/Converter/AssetsConverter.cs b/Packages/com.unity.render-pipelines.core/Editor-PrivateShared/Tools/Converter/AssetsConverter.cs index c53bf7d89fa..f7574aed4ec 100644 --- a/Packages/com.unity.render-pipelines.core/Editor-PrivateShared/Tools/Converter/AssetsConverter.cs +++ b/Packages/com.unity.render-pipelines.core/Editor-PrivateShared/Tools/Converter/AssetsConverter.cs @@ -146,14 +146,14 @@ internal static RenderPipelineConverterAssetItem CreateAssetItem(SearchItem item // Named with the path in the hierarchy, the only name Search has for objects in closed scenes. GameObject // names can contain '/', so the object's own name can't be taken from it. - static string GetSceneObjectName(string transformPath) + internal static string GetSceneObjectName(string transformPath) { var path = transformPath.StartsWith('/') ? transformPath.Substring(1) : transformPath; return $"{path} (SceneObject)"; } // Returns null unless the id is of an object in a scene that is not loaded - static string GetUnloadedScenePath(string globalObjectId) + internal static string GetUnloadedScenePath(string globalObjectId) { if (!GlobalObjectId.TryParse(globalObjectId, out var gid) || gid.identifierType != GlobalObjectIdentifierType.SceneObject) return null; @@ -234,7 +234,11 @@ public Status Convert(IRenderPipelineConverterItem item, out string message) var scenePath = GetUnloadedScenePath(assetItem.GlobalObjectId); if (scenePath != null) + { + // Opening the scene unloads converted assets that are not saved, such as prefabs + AssetDatabase.SaveAssets(); (m_ScenesOpenedForConversion ??= new HashSet()).Add(scenePath); + } var obj = assetItem.LoadObject(); @@ -273,6 +277,8 @@ void SaveSceneOpenedForConversion(UnityEngine.Object obj) public virtual void AfterConvert() { + // A later converter can open scenes too + AssetDatabase.SaveAssets(); m_ScenesOpenedForConversion?.Clear(); } } diff --git a/Packages/com.unity.render-pipelines.core/Editor-PrivateShared/Tools/Converter/ReadonlyMaterialConverter/ReadonlyMaterialConverter.MaterialReferenceBuilder.cs b/Packages/com.unity.render-pipelines.core/Editor-PrivateShared/Tools/Converter/ReadonlyMaterialConverter/ReadonlyMaterialConverter.MaterialReferenceBuilder.cs index 5026ecc9a56..750c2fbe1d0 100644 --- a/Packages/com.unity.render-pipelines.core/Editor-PrivateShared/Tools/Converter/ReadonlyMaterialConverter/ReadonlyMaterialConverter.MaterialReferenceBuilder.cs +++ b/Packages/com.unity.render-pipelines.core/Editor-PrivateShared/Tools/Converter/ReadonlyMaterialConverter/ReadonlyMaterialConverter.MaterialReferenceBuilder.cs @@ -141,7 +141,7 @@ public static bool TryGetReferenceInfoFromType(Type type, out MaterialReferenceI foreach (var prop in type.GetProperties(flags)) { - if (!prop.CanRead) continue; + if (!prop.CanRead || prop.GetSetMethod(true) == null) continue; // skip read-only properties, e.g. Terrain.splatBaseMaterial if (prop.GetIndexParameters().Length > 0) continue; // skip indexers if (prop.PropertyType == typeof(Material) || prop.PropertyType == typeof(Material[])) diff --git a/Packages/com.unity.render-pipelines.core/Editor-PrivateShared/Tools/Converter/SearchServiceUtils.cs b/Packages/com.unity.render-pipelines.core/Editor-PrivateShared/Tools/Converter/SearchServiceUtils.cs index 462c266c5fd..ea291143de8 100644 --- a/Packages/com.unity.render-pipelines.core/Editor-PrivateShared/Tools/Converter/SearchServiceUtils.cs +++ b/Packages/com.unity.render-pipelines.core/Editor-PrivateShared/Tools/Converter/SearchServiceUtils.cs @@ -17,6 +17,28 @@ public enum IndexingOptions // Set while a caller blocks the Editor, so searches have to finish before RunQueuedSearch returns public static bool synchronous { get; set; } + // Asset changes reach the index after a delay and are then applied in the background, and searches do not wait for them + static void WaitForIndexUpToDate(Action onIndexUpToDate) + { + if (IsIndexUpdatePending()) + EditorApplication.delayCall += () => WaitForIndexUpToDate(onIndexUpToDate); + else + onIndexUpToDate(); + } + + static bool IsIndexUpdatePending() + { + // The index defers its updates until play mode is exited + if (EditorApplication.isPlaying) + return false; + + var db = SearchDatabase.GetDefaultSearchDatabase(); + if (db.LoadingState == SearchDatabase.LoadState.Error || db.LoadingState == SearchDatabase.LoadState.Canceled) + return false; + + return SearchMonitor.pending || !db.ready || db.updating || db.needsUpdate; + } + public static void RunQueuedSearch( IndexingOptions neededOptions, List<(string query, string description)> contextSearchQueriesAndIds, @@ -111,7 +133,7 @@ void ProcessNextSearch() void OnSearchIndexReady() { - ProcessNextSearch(); + WaitForIndexUpToDate(ProcessNextSearch); } if (isDeepSearchEnabled != needsDeepSearch || isPackageIndexingEnabled != needsPackageIndexing) diff --git a/Packages/com.unity.render-pipelines.core/Editor-PrivateShared/Tools/Converter/Window/RenderPipelineConvertersEditor.cs b/Packages/com.unity.render-pipelines.core/Editor-PrivateShared/Tools/Converter/Window/RenderPipelineConvertersEditor.cs index a0c5c599536..312c7b336ea 100644 --- a/Packages/com.unity.render-pipelines.core/Editor-PrivateShared/Tools/Converter/Window/RenderPipelineConvertersEditor.cs +++ b/Packages/com.unity.render-pipelines.core/Editor-PrivateShared/Tools/Converter/Window/RenderPipelineConvertersEditor.cs @@ -525,14 +525,15 @@ void Convert() EditorUtility.ClearProgressBar(); } + // Save before reloading the scene we started from, which unloads converted assets that are not saved + AssetDatabase.SaveAssets(); + // Checking if we have changed current scene. If we have we reload the old scene we started from if (!string.IsNullOrEmpty(currentScenePath) && currentScenePath != SceneManager.GetActiveScene().path) { EditorSceneManager.OpenScene(currentScenePath); } - AssetDatabase.SaveAssets(); - RefreshUI(); GraphicsToolUsageAnalytic.ActionPerformed(nameof(Convert), contextInfo.ToNestedColumn()); diff --git a/Packages/com.unity.render-pipelines.core/Editor/CommandBuffers/CommandBufferGenerator/CommandBufferGenerator.cs b/Packages/com.unity.render-pipelines.core/Editor/CommandBuffers/CommandBufferGenerator/CommandBufferGenerator.cs index d02abea4145..206a6636764 100644 --- a/Packages/com.unity.render-pipelines.core/Editor/CommandBuffers/CommandBufferGenerator/CommandBufferGenerator.cs +++ b/Packages/com.unity.render-pipelines.core/Editor/CommandBuffers/CommandBufferGenerator/CommandBufferGenerator.cs @@ -196,7 +196,7 @@ public interface @type_name@ @base_type@ @" /// Wraps [{0}](https://docs.unity3d.com/ScriptReference/Rendering.CommandBuffer.{0}.html) on a CommandBuffer. {1} - public void {0}{5}({2}) {6} {{ {4} m_WrappedCommandBuffer.{0}({3}); }} +{7} public void {0}{5}({2}) {6} {{ {4} m_WrappedCommandBuffer.{0}({3}); }} "; // Generated individual function template @@ -204,7 +204,7 @@ public interface @type_name@ @base_type@ @" /// Wraps [{0}](https://docs.unity3d.com/ScriptReference/Rendering.CommandBuffer.{0}.html) on a CommandBuffer. {1} - public void {0}{5}({2}) {6}; +{7} public void {0}{5}({2}) {6}; "; static string paramDocTemplate = @@ -346,7 +346,12 @@ static void GenerateCommandBufferType(string className, string docString, string argDocList.AppendFormat(typeParamDocTemplate, "T", method.Name); } - result.AppendFormat((isInterface) ? interfaceFunctionTemplate : functionTemplate, method.Name, argDocList.ToString(), typedArgList.ToString(), argList.ToString(), validationCode.ToString(), genericArgList.ToString(), genericConstraints.ToString()); + var obsoleteAttribute = (ObsoleteAttribute)Attribute.GetCustomAttribute(method, typeof(ObsoleteAttribute), false); + var obsoleteCode = obsoleteAttribute == null + ? "" + : string.Format(" [Obsolete(\"{0}\", {1})]\n", obsoleteAttribute.Message?.Replace("\"", "\\\""), obsoleteAttribute.IsError ? "true" : "false"); + + result.AppendFormat((isInterface) ? interfaceFunctionTemplate : functionTemplate, method.Name, argDocList.ToString(), typedArgList.ToString(), argList.ToString(), validationCode.ToString(), genericArgList.ToString(), genericConstraints.ToString(), obsoleteCode); } result.Append(postamble); diff --git a/Packages/com.unity.render-pipelines.core/Editor/CoreEditorUtils.cs b/Packages/com.unity.render-pipelines.core/Editor/CoreEditorUtils.cs index 8d3b367cc5a..ba6638f017c 100644 --- a/Packages/com.unity.render-pipelines.core/Editor/CoreEditorUtils.cs +++ b/Packages/com.unity.render-pipelines.core/Editor/CoreEditorUtils.cs @@ -303,8 +303,11 @@ public static void DrawMultipleFields(GUIContent label, SerializedProperty[] ppt EditorGUIUtility.labelWidth = GetLongestLabelWidth(labels) + CoreEditorConstants.standardHorizontalSpacing; int oldIndentLevel = EditorGUI.indentLevel; EditorGUI.indentLevel = 0; - for (var i = 0; i < ppts.Length; ++i) - EditorGUILayout.PropertyField(ppts[i], labels[i]); + using (new EditorGUIBridge.CompositeStylingScope()) + { + for (var i = 0; i < ppts.Length; ++i) + EditorGUILayout.PropertyField(ppts[i], labels[i]); + } EditorGUI.indentLevel = oldIndentLevel; } } diff --git a/Packages/com.unity.render-pipelines.core/Editor/InternalBridge/EditorGUIBridge.cs b/Packages/com.unity.render-pipelines.core/Editor/InternalBridge/EditorGUIBridge.cs new file mode 100644 index 00000000000..a3ecfd8849d --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Editor/InternalBridge/EditorGUIBridge.cs @@ -0,0 +1,17 @@ +namespace UnityEditor.Rendering +{ + static class EditorGUIBridge + { + public readonly struct CompositeStylingScope : System.IDisposable + { + readonly EditorGUI.CompositeStylingScope m_Scope; + + public CompositeStylingScope(bool enabled = true) + { + m_Scope = new EditorGUI.CompositeStylingScope(enabled); + } + + public void Dispose() => m_Scope.Dispose(); + } + } +} diff --git a/Packages/com.unity.render-pipelines.core/Editor/InternalBridge/EditorGUIBridge.cs.meta b/Packages/com.unity.render-pipelines.core/Editor/InternalBridge/EditorGUIBridge.cs.meta new file mode 100644 index 00000000000..26e53f3b582 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Editor/InternalBridge/EditorGUIBridge.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 406c6cb06a44461c9e8f00aac1ca3347 diff --git a/Packages/com.unity.render-pipelines.core/Editor/InternalBridge/EditorWindowBridge.cs b/Packages/com.unity.render-pipelines.core/Editor/InternalBridge/EditorWindowBridge.cs new file mode 100644 index 00000000000..202d0ebf3e6 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Editor/InternalBridge/EditorWindowBridge.cs @@ -0,0 +1,8 @@ +namespace UnityEditor.Rendering +{ + static class EditorWindowBridge + { + public static void RepaintImmediately(EditorWindow window) + => window.RepaintImmediately(); + } +} diff --git a/Packages/com.unity.render-pipelines.core/Editor/InternalBridge/EditorWindowBridge.cs.meta b/Packages/com.unity.render-pipelines.core/Editor/InternalBridge/EditorWindowBridge.cs.meta new file mode 100644 index 00000000000..338fbabde45 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Editor/InternalBridge/EditorWindowBridge.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 59b06a192524a3b4da02793509fd7fb8 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.core/Editor/Lighting/LightUI.Drawers.cs b/Packages/com.unity.render-pipelines.core/Editor/Lighting/LightUI.Drawers.cs index 29b7b4a251e..8cbb0afb908 100644 --- a/Packages/com.unity.render-pipelines.core/Editor/Lighting/LightUI.Drawers.cs +++ b/Packages/com.unity.render-pipelines.core/Editor/Lighting/LightUI.Drawers.cs @@ -252,19 +252,27 @@ public static void DrawIntensityModifiers(ISerializedLight serialized, bool hide /// The light unit that has been selected by the user. public static LightUnit DrawLightIntensityUnitPopup(Rect position, LightUnit selected, LightType type) { - switch (type) +#pragma warning disable CS8524 // intentionally cover only named LightTypes; Warning flags a new one not in the switch + return type switch { - case LightType.Box: - case LightType.Directional: - return (LightUnit)EditorGUI.EnumPopup(position, (DirectionalLightUnit)selected); - - case LightType.Point: - case LightType.Spot: - case LightType.Pyramid: - return (LightUnit)EditorGUI.EnumPopup(position, (PunctualLightUnit)selected); + LightType.Directional or LightType.Box => DrawPopup(), + LightType.Point or LightType.Spot or LightType.Pyramid => DrawPopup(), + LightType.Rectangle or LightType.Disc or LightType.Tube => DrawPopup(), + }; +#pragma warning restore CS8524 + + // Draws the unit dropdown for the given per-type unit enum. If single unit, it renders as a disabled field. + LightUnit DrawPopup() where TUnit : struct, Enum + { + if (Enum.GetValues(typeof(TUnit)).Length <= 1) + { + LightUnit native = LightUnitUtils.GetNativeLightUnit(type); + using (new EditorGUI.DisabledScope(true)) + EditorGUI.EnumPopup(position, native); + return native; + } - default: - return (LightUnit)EditorGUI.EnumPopup(position, (AreaLightUnit)selected); + return (LightUnit)EditorGUI.EnumPopup(position, (TUnit)(object)selected); } } } diff --git a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.RenderingLayers.cs b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.RenderingLayers.cs index 4d4123d0ef5..95ca8d53747 100644 --- a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.RenderingLayers.cs +++ b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.RenderingLayers.cs @@ -127,8 +127,8 @@ static AccelStructAdapter BuildAccelerationStructure(out bool hasTerrains) Array.Fill(matIndices, renderer.component.renderingLayerMask); // repurpose the material id as we don't need it here var perSubMeshMask = new uint[subMeshCount]; Array.Fill(perSubMeshMask, GetInstanceMask(renderer.component.shadowCastingMode)); - Span perSubMeshOpaqueness = stackalloc bool[subMeshCount]; - perSubMeshOpaqueness.Fill(true); + var perSubMeshOpaqueness = new bool[subMeshCount]; + Array.Fill(perSubMeshOpaqueness, true); accelStruct.AddInstance(EntityId.ToULong(renderer.component.GetEntityId()), renderer.component, perSubMeshMask, matIndices, perSubMeshOpaqueness, 1); } diff --git a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.Serialization.cs b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.Serialization.cs index 988d5df5a67..aafc2290706 100644 --- a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.Serialization.cs +++ b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.Serialization.cs @@ -690,6 +690,8 @@ static void ExtractBakingCells() foreach (var data in loadedSceneDataList) { var cells = m_BakingSet.GetSceneCellIndexList(data.sceneGUID); + if (cells == null) + continue; var numberOfCells = cells.Count; diff --git a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.SkyOcclusion.cs b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.SkyOcclusion.cs index 97e4d823a94..1b742047a4a 100644 --- a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.SkyOcclusion.cs +++ b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.SkyOcclusion.cs @@ -221,8 +221,8 @@ static AccelStructAdapter BuildAccelerationStructure(out bool hasTerrains) var matIndices = GetMaterialIndices(renderer.component); var perSubMeshMask = new uint[subMeshCount]; Array.Fill(perSubMeshMask, GetInstanceMask(renderer.component.shadowCastingMode)); - Span perSubMeshOpaqueness = stackalloc bool[subMeshCount]; - perSubMeshOpaqueness.Fill(true); + var perSubMeshOpaqueness = new bool[subMeshCount]; + Array.Fill(perSubMeshOpaqueness, true); accelStruct.AddInstance(EntityId.ToULong(renderer.component.GetEntityId()), renderer.component, perSubMeshMask, matIndices, perSubMeshOpaqueness, 1); } diff --git a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.VirtualOffset.cs b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.VirtualOffset.cs index b99673082a8..7d6b3cf7f5e 100644 --- a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.VirtualOffset.cs +++ b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.VirtualOffset.cs @@ -149,8 +149,8 @@ static AccelStructAdapter BuildAccelerationStructure(int mask, out bool hasTerra int subMeshCount = mesh.subMeshCount; var maskAndMatDummy = new uint[subMeshCount]; System.Array.Fill(maskAndMatDummy, 0xFFFFFFFF); - Span perSubMeshOpaqueness = stackalloc bool[subMeshCount]; - perSubMeshOpaqueness.Fill(true); + var perSubMeshOpaqueness = new bool[subMeshCount]; + System.Array.Fill(perSubMeshOpaqueness, true); accelStruct.AddInstance(EntityId.ToULong(renderer.component.GetEntityId()), renderer.component, maskAndMatDummy, maskAndMatDummy, perSubMeshOpaqueness, 1); } diff --git a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.cs b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.cs index f6cd89c9245..b3064f0e5f0 100644 --- a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.cs +++ b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.cs @@ -903,6 +903,7 @@ static internal void Init() Lightmapping.lightingDataCleared += OnLightingDataCleared; Lightmapping.bakeStarted += OnBakeStarted; Lightmapping.bakeCancelled += OnBakeCancelled; + Lightmapping.bakeCompleted += OnBakeCompleted; Lightmapping.inputExtraction += OnInputExtraction; AssemblyReloadEvents.beforeAssemblyReload += CleanUp; // Without a domain reload on entering play mode the context can outlive every reload, so also release it before the graphics device shuts down. @@ -1118,9 +1119,19 @@ static void OnBakeStarted() { ProbeReferenceVolume.instance.checksDuringBakeAction = CheckPVChanges; Lightmapping.AddBakeDelegate(BakeDelegate); + s_FullBakeDelegateRegistered = true; } } + static bool s_FullBakeDelegateRegistered; + + // A bake that fails before its bake delegates run never calls BakeDelegate, so release the APV bake data here. + static void OnBakeCompleted() + { + if (s_FullBakeDelegateRegistered) + OnBakeCancelled(); + } + static readonly string k_APVLightBakerFolder = "APVBake"; static readonly string k_APVLightBakerOutputFolder = $"Temp/LightBakerOutput/{k_APVLightBakerFolder}"; static readonly string k_APVLightBakerPostProcessingOutputFolder = $"Temp/PostProcessingOutput/{k_APVLightBakerFolder}"; @@ -1206,17 +1217,22 @@ static bool PrepareBaking(BakeType bakeType, GetProbesFunc getProbes, GetAdditio s_BakeData.Init(m_BakingSet, positions, requests, bakeType); positions.Dispose(); - // Set delegates used for virtual offsets baking + SetVirtualOffsetBakeDelegates(true); + + return true; + } + + // Native code only clears these delegates once it has called them, which does not happen when a bake fails before probe preprocessing. + static void SetVirtualOffsetBakeDelegates(bool enabled) + { Type lightmappingType = typeof(Lightmapping); FieldInfo initField = lightmappingType.GetField("s_VirtualOffsetBakeInitializeDataDelegate", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); Debug.Assert(initField != null, "Unexpected, could not find s_VirtualOffsetBakeInitializeDataDelegate"); FieldInfo updateField = lightmappingType.GetField("s_VirtualOffsetBakeUpdateDelegate", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); Debug.Assert(updateField != null, "Unexpected, could not find s_VirtualOffsetBakeUpdateDelegate"); - initField.SetValue(null, Delegate.CreateDelegate(initField.FieldType, typeof(BakeData), nameof(BakeData.InitVirtualOffsetJob))); - updateField.SetValue(null, Delegate.CreateDelegate(updateField.FieldType, typeof(BakeData), nameof(BakeData.UpdateVirtualOffsetJob))); - - return true; + initField.SetValue(null, enabled ? Delegate.CreateDelegate(initField.FieldType, typeof(BakeData), nameof(BakeData.InitVirtualOffsetJob)) : null); + updateField.SetValue(null, enabled ? Delegate.CreateDelegate(updateField.FieldType, typeof(BakeData), nameof(BakeData.UpdateVirtualOffsetJob)) : null); } static bool PrepareAdditionalProbesBaking(BakeType bakeType, GetProbesFunc getProbes, GetAdditionalRequestsFunc getAdditionalRequests) @@ -1543,6 +1559,7 @@ static void OnBakeCancelled() static void CleanBakeData() { + SetVirtualOffsetBakeDelegates(false); s_BakeData.CleanUp(); s_BakingBatch?.Dispose(); s_BakingBatch = null; @@ -1553,6 +1570,7 @@ static void CleanBakeData() CleanUp(); Lightmapping.RemoveBakeDelegate(BakeDelegate); + s_FullBakeDelegateRegistered = false; s_PartialBakeSceneList = null; ProbeReferenceVolume.instance.checksDuringBakeAction = null; diff --git a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeVolumeEditor.cs b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeVolumeEditor.cs index 9bfc8c31f66..d1c68efe228 100644 --- a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeVolumeEditor.cs +++ b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeVolumeEditor.cs @@ -147,14 +147,6 @@ public override void OnInspectorGUI() bool drawInspector = true; -#pragma warning disable 618 - if (ProbeVolumeLightingTab.GetLightingSettings().realtimeGI) -#pragma warning restore 618 - { - EditorGUILayout.HelpBox("Adaptive Probe Volumes are not supported when using Realtime Global Illumination(Enlighten).", MessageType.Warning, wide: true); - drawInspector = false; - } - if (!ProbeVolumeGlobalSettingsStripper.ProbeVolumeSupportedForBuild()) { APVDisabledHelpBox(); diff --git a/Packages/com.unity.render-pipelines.core/Editor/PathTracing/AssemblyInfo.cs b/Packages/com.unity.render-pipelines.core/Editor/PathTracing/AssemblyInfo.cs index 23e46c1c07c..489bf620f6e 100644 --- a/Packages/com.unity.render-pipelines.core/Editor/PathTracing/AssemblyInfo.cs +++ b/Packages/com.unity.render-pipelines.core/Editor/PathTracing/AssemblyInfo.cs @@ -1,5 +1,6 @@ using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Assembly-CSharp-Editor-testable")] +[assembly: InternalsVisibleTo("Unity.Modules.GI.LightBaker.Tests.Editor")] [assembly: InternalsVisibleTo("Unity.RenderPipelines.Core.Editor")] [assembly: InternalsVisibleTo("Assembly-CSharp-testable")] diff --git a/Packages/com.unity.render-pipelines.core/Editor/PathTracing/BakeInputToWorldConversion.cs b/Packages/com.unity.render-pipelines.core/Editor/PathTracing/BakeInputToWorldConversion.cs index 86ff93b3ebd..e0772febeff 100644 --- a/Packages/com.unity.render-pipelines.core/Editor/PathTracing/BakeInputToWorldConversion.cs +++ b/Packages/com.unity.render-pipelines.core/Editor/PathTracing/BakeInputToWorldConversion.cs @@ -340,12 +340,7 @@ internal static void InjectEnvironmentLight( allocatedObjects.Add(envCubemap); // If we have no cubemap (i.e. the 1x1x1 black texture), don't set it - we don't want to waste samples directly sampling it. if (!isEmptyCubemap) - { - var envCubemapMaterial = new Material(Shader.Find("Hidden/PassthroughSkybox")); - envCubemapMaterial.SetTexture("_Tex", envCubemap); - world.SetEnvironmentMaterial(envCubemapMaterial); - allocatedObjects.Add(envCubemapMaterial); - } + world.SetEnvironmentCubemap(envCubemap); } internal static void InjectMaterials( @@ -492,6 +487,15 @@ internal static void InjectMaterials( perInstanceSubMeshVisibility[instanceIdx][subMeshIdx] = subMeshMaterialIdx != -1; } } + int rejectedMaterialCount = 0; + foreach (var handle in materialCache.Values) + { + if (handle == MaterialHandle.Invalid) + rejectedMaterialCount++; + } + if (rejectedMaterialCount > 0) + Debug.LogError($"Light baking: {rejectedMaterialCount} materials could not be added because the material texture atlas is full ({SystemInfo.maxTextureArraySlices} slices). Geometry using them is left out of the bake."); + Debug.Assert(allocatedObjects.Count == allocationCount + bakeInput.albedoData.Length * 2 + bakeInput.transmissionData.Length, "InjectMaterials allocated objects incorrectly"); } diff --git a/Packages/com.unity.render-pipelines.core/Editor/PathTracing/LightBakerStrangler.cs b/Packages/com.unity.render-pipelines.core/Editor/PathTracing/LightBakerStrangler.cs index 0f524e66257..4f793a0dbb7 100644 --- a/Packages/com.unity.render-pipelines.core/Editor/PathTracing/LightBakerStrangler.cs +++ b/Packages/com.unity.render-pipelines.core/Editor/PathTracing/LightBakerStrangler.cs @@ -699,7 +699,7 @@ internal static InstanceHandle[] AddLODInstances(World world, CommandBuffer cmd, if ((lodBuildData.LodMask & currentLodLevel) == 0) continue; - Span currentLodMasks = stackalloc uint[lodBuildData.Masks.Length]; + var currentLodMasks = new uint[lodBuildData.Masks.Length]; GetCurrentLodInstanceMasks(pathtracingShader, lodBuildData.Masks, currentLodMasks); instanceHandles[i++] = world.AddInstance(lodBuildData.Mesh, lodBuildData.Materials, currentLodMasks, UnityComputeWorld.RenderingObjectLayer, lodBuildData.LocalToWorldMatrix, lodBuildData.Bounds, lodBuildData.IsStatic, lodBuildData.Filter, true); @@ -715,7 +715,7 @@ internal static InstanceHandle[] AddLODInstances(World world, CommandBuffer cmd, if ((lodZeroInstance.LodMask & currentLodLevel) != 0) continue; - Span lodZeroMasks = stackalloc uint[lodZeroInstance.Masks.Length]; + var lodZeroMasks = new uint[lodZeroInstance.Masks.Length]; GetLodZeroInstanceMasks(pathtracingShader, lodZeroInstance.Masks, lodZeroMasks); world.UpdateInstanceMask(lodZeroInstance.InstanceHandle, lodZeroMasks); diff --git a/Packages/com.unity.render-pipelines.core/Editor/RenderGraph/RenderGraphTestsCore.cs b/Packages/com.unity.render-pipelines.core/Editor/RenderGraph/RenderGraphTestsCore.cs index 7e95b06e194..b13fedacad3 100644 --- a/Packages/com.unity.render-pipelines.core/Editor/RenderGraph/RenderGraphTestsCore.cs +++ b/Packages/com.unity.render-pipelines.core/Editor/RenderGraph/RenderGraphTestsCore.cs @@ -193,6 +193,9 @@ public void CleanupRenderGraph() // Cleaning all Render Graph resources and data structures // Nothing remains, Render Graph in next test will start from scratch m_RenderGraph.CleanupResourcesAndGraph(); + + // Disposing a builder outside of recording leaves the graph in RecordingGraph, which would leak into the next test + m_RenderGraph.RenderGraphState = RenderGraphState.Idle; } } } diff --git a/Packages/com.unity.render-pipelines.core/Editor/Unity.RenderPipelines.Core.Editor.asmdef b/Packages/com.unity.render-pipelines.core/Editor/Unity.RenderPipelines.Core.Editor.asmdef index 81085d49a8d..ac3af49e803 100644 --- a/Packages/com.unity.render-pipelines.core/Editor/Unity.RenderPipelines.Core.Editor.asmdef +++ b/Packages/com.unity.render-pipelines.core/Editor/Unity.RenderPipelines.Core.Editor.asmdef @@ -57,6 +57,11 @@ "expression": "1.0.0", "define": "ENABLE_METALFX_MODULE" }, + { + "name": "com.unity.modules.intelxess", + "expression": "1.0.0", + "define": "ENABLE_INTELXESS_MODULE" + }, { "name": "com.unity.modules.terrain", "expression": "1.0.0", diff --git a/Packages/com.unity.render-pipelines.core/Editor/Upscaling/XeSSOptionsEditor.cs b/Packages/com.unity.render-pipelines.core/Editor/Upscaling/XeSSOptionsEditor.cs new file mode 100644 index 00000000000..4c123eaa3a1 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Editor/Upscaling/XeSSOptionsEditor.cs @@ -0,0 +1,26 @@ +#if ENABLE_XESS && ENABLE_INTELXESS_MODULE +using UnityEditor; +using UnityEngine; +using UnityEngine.Intel; + +[CustomEditor(typeof(XeSSOptions))] +internal class XeSSOptionsEditor : UpscalerOptionsEditor +{ + protected override bool showsReactiveMaskGeneration => true; + + // Declare variables to hold each property + private SerializedProperty m_QualityMode; + + protected override void OnEnable() + { + base.OnEnable(); + // Find each property by its exact field name in XeSSOptions.cs + m_QualityMode = serializedObject.FindProperty("m_XeSSQualityMode"); + } + + protected override void DrawOptions() + { + EditorGUILayout.PropertyField(m_QualityMode); + } +} +#endif diff --git a/Packages/com.unity.render-pipelines.core/Editor/Upscaling/XeSSOptionsEditor.cs.meta b/Packages/com.unity.render-pipelines.core/Editor/Upscaling/XeSSOptionsEditor.cs.meta new file mode 100644 index 00000000000..dfde52c8a43 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Editor/Upscaling/XeSSOptionsEditor.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 5cfa8206b8b30384d8d917dc1b01e446 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.core/Editor/Volume/VolumeProfileUtils.cs b/Packages/com.unity.render-pipelines.core/Editor/Volume/VolumeProfileUtils.cs index 8d3b9f867ae..3e8187fd400 100644 --- a/Packages/com.unity.render-pipelines.core/Editor/Volume/VolumeProfileUtils.cs +++ b/Packages/com.unity.render-pipelines.core/Editor/Volume/VolumeProfileUtils.cs @@ -155,7 +155,7 @@ static VolumeComponent GetVolumeComponentOfTypeOrDefault(this VolumeProfile prof return profile.GetVolumeComponentOfType(type) ?? (VolumeComponent) ScriptableObject.CreateInstance(type); } - static List GetTypesMissingFromDefaultProfile(VolumeProfile profile, Type pipelineAssetType) + internal static List GetTypesMissingFromDefaultProfile(VolumeProfile profile, Type pipelineAssetType) { List missingTypes = new List(); var volumeComponentTypes = VolumeManager.GetBaseComponentTypesForPipeline(pipelineAssetType); diff --git a/Packages/com.unity.render-pipelines.core/Runtime-PrivateShared/AssemblyInfo.cs b/Packages/com.unity.render-pipelines.core/Runtime-PrivateShared/AssemblyInfo.cs index 46893054850..95945e31856 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime-PrivateShared/AssemblyInfo.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime-PrivateShared/AssemblyInfo.cs @@ -35,4 +35,16 @@ internal static class RenderingDebuggerBridge public static void SetSupportsHidingDebugOverlays(bool value) => UnityEngine.Rendering.DebugManager.instance.supportsHidingDebugOverlays = value; } + + internal static class ConstantBufferBackedPropertiesBridge + { + public static void SetBackedByConstantBuffer(int nameID, string warning) + => UnityEngine.Rendering.ConstantBufferBackedPropertiesBridge.SetBackedByConstantBuffer(nameID, warning); + + public static void ClearWarnings() + => UnityEngine.Rendering.ConstantBufferBackedPropertiesBridge.ClearWarnings(); + + public static void EnableWarnings(bool enable) + => UnityEngine.Rendering.ConstantBufferBackedPropertiesBridge.EnableWarnings(enable); + } } diff --git a/Packages/com.unity.render-pipelines.core/Runtime-PrivateShared/AssetLinkUtils.cs b/Packages/com.unity.render-pipelines.core/Runtime-PrivateShared/AssetLinkUtils.cs new file mode 100644 index 00000000000..267c6779e5d --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime-PrivateShared/AssetLinkUtils.cs @@ -0,0 +1,44 @@ +#if UNITY_EDITOR +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; + +namespace Unity.RenderPipelines.Core.Runtime.Shared +{ + internal static class AssetLinkUtils + { + const string k_LinkKey = "srpasset"; + + internal static string AssetLink(Object asset) + { + string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(asset)); + + string color = EditorGUIUtility.isProSkin ? "#40a0ff" : "#0000FF"; + + return $"{asset.name}"; + } + + [InitializeOnLoadMethod] + static void RegisterLinkHandler() + { + EditorGUI.hyperLinkClicked -= OnLinkClicked; + EditorGUI.hyperLinkClicked += OnLinkClicked; + } + + static void OnLinkClicked(EditorWindow window, HyperLinkClickedEventArgs args) => SelectLinkedAsset(args.hyperLinkData); + + internal static void SelectLinkedAsset(Dictionary hyperLinkData) + { + if (!hyperLinkData.TryGetValue(k_LinkKey, out string guid)) + return; + + var asset = AssetDatabase.LoadMainAssetAtPath(AssetDatabase.GUIDToAssetPath(guid)); + if (asset == null) + return; + + Selection.activeObject = asset; + EditorGUIUtility.PingObject(asset); + } + } +} +#endif diff --git a/Packages/com.unity.render-pipelines.core/Runtime-PrivateShared/AssetLinkUtils.cs.meta b/Packages/com.unity.render-pipelines.core/Runtime-PrivateShared/AssetLinkUtils.cs.meta new file mode 100644 index 00000000000..36f440e7264 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime-PrivateShared/AssetLinkUtils.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: a26d24c303b44420a2cfc43c397f5f74 diff --git a/Packages/com.unity.render-pipelines.core/Runtime-PrivateShared/DebugUIUtilities.cs b/Packages/com.unity.render-pipelines.core/Runtime-PrivateShared/DebugUIUtilities.cs index a2192e96922..81780f36434 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime-PrivateShared/DebugUIUtilities.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime-PrivateShared/DebugUIUtilities.cs @@ -15,5 +15,7 @@ internal static DebugUI.Foldout GetFoldoutByName(string name, IEnumerable CoreUtils.FormatMemorySize(bytes); } } diff --git a/Packages/com.unity.render-pipelines.core/Runtime/AssemblyInfo.cs b/Packages/com.unity.render-pipelines.core/Runtime/AssemblyInfo.cs index 0e770b06597..d4551e1176a 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/AssemblyInfo.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/AssemblyInfo.cs @@ -16,6 +16,9 @@ [assembly: InternalsVisibleTo("Unity.PathTracing.Runtime")] [assembly: InternalsVisibleTo("Unity.PathTracing.Editor")] +// Access to HashFNV1A32 for the Unified Ray Tracing GeometryPool +[assembly: InternalsVisibleTo("Unity.UnifiedRayTracing.Runtime")] + // Access to RenderGraph internals (e.g. RenderGraphParameters.invalidContextForTesting) for SurfaceCache core tests [assembly: InternalsVisibleTo("Unity.SurfaceCache.Tests")] @@ -24,6 +27,7 @@ [assembly: InternalsVisibleTo("SRPSmoke.Runtime.Tests")] [assembly: InternalsVisibleTo("SRPSmoke.Editor.Tests")] [assembly: InternalsVisibleTo("Assembly-CSharp-Editor-testable")] +[assembly: InternalsVisibleTo("Unity.Modules.GI.LightBaker.Tests.Editor")] // Access for URP Tests so they use internals from Core Runtime [assembly: InternalsVisibleTo("Unity.RenderPipelines.Universal.Runtime.Tests")] diff --git a/Packages/com.unity.render-pipelines.core/Runtime/CommandBuffers/ComputeCommandBuffer.cs b/Packages/com.unity.render-pipelines.core/Runtime/CommandBuffers/ComputeCommandBuffer.cs index 38ce2d210da..b1433399cff 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/CommandBuffers/ComputeCommandBuffer.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/CommandBuffers/ComputeCommandBuffer.cs @@ -223,10 +223,12 @@ internal ComputeCommandBuffer(CommandBuffer wrapped, RenderGraphPass executingPa /// Wraps [BeginSample](https://docs.unity3d.com/ScriptReference/Rendering.CommandBuffer.BeginSample.html) on a CommandBuffer. /// [See CommandBuffer documentation](https://docs.unity3d.com/ScriptReference/Rendering.CommandBuffer.BeginSample.html) + [Obsolete("Use BeginSample(ProfilerMarker) instead.", false)] public void BeginSample(CustomSampler sampler) { m_WrappedCommandBuffer.BeginSample(sampler); } /// Wraps [EndSample](https://docs.unity3d.com/ScriptReference/Rendering.CommandBuffer.EndSample.html) on a CommandBuffer. /// [See CommandBuffer documentation](https://docs.unity3d.com/ScriptReference/Rendering.CommandBuffer.EndSample.html) + [Obsolete("Use EndSample(ProfilerMarker) instead.", false)] public void EndSample(CustomSampler sampler) { m_WrappedCommandBuffer.EndSample(sampler); } /// Wraps [BeginSample](https://docs.unity3d.com/ScriptReference/Rendering.CommandBuffer.BeginSample.html) on a CommandBuffer. diff --git a/Packages/com.unity.render-pipelines.core/Runtime/CommandBuffers/IBaseCommandBuffer.cs b/Packages/com.unity.render-pipelines.core/Runtime/CommandBuffers/IBaseCommandBuffer.cs index 7dc756abd36..5ba37659c8b 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/CommandBuffers/IBaseCommandBuffer.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/CommandBuffers/IBaseCommandBuffer.cs @@ -179,10 +179,12 @@ public interface IBaseCommandBuffer /// Wraps [BeginSample](https://docs.unity3d.com/ScriptReference/Rendering.CommandBuffer.BeginSample.html) on a CommandBuffer. /// [See CommandBuffer documentation](https://docs.unity3d.com/ScriptReference/Rendering.CommandBuffer.BeginSample.html) + [Obsolete("Use BeginSample(ProfilerMarker) instead.", false)] public void BeginSample(CustomSampler sampler) ; /// Wraps [EndSample](https://docs.unity3d.com/ScriptReference/Rendering.CommandBuffer.EndSample.html) on a CommandBuffer. /// [See CommandBuffer documentation](https://docs.unity3d.com/ScriptReference/Rendering.CommandBuffer.EndSample.html) + [Obsolete("Use EndSample(ProfilerMarker) instead.", false)] public void EndSample(CustomSampler sampler) ; /// Wraps [BeginSample](https://docs.unity3d.com/ScriptReference/Rendering.CommandBuffer.BeginSample.html) on a CommandBuffer. diff --git a/Packages/com.unity.render-pipelines.core/Runtime/CommandBuffers/RasterCommandBuffer.cs b/Packages/com.unity.render-pipelines.core/Runtime/CommandBuffers/RasterCommandBuffer.cs index 65cb985d26b..c2b3d2ef56e 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/CommandBuffers/RasterCommandBuffer.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/CommandBuffers/RasterCommandBuffer.cs @@ -217,10 +217,12 @@ internal RasterCommandBuffer(CommandBuffer wrapped, RenderGraphPass executingPas /// Wraps [BeginSample](https://docs.unity3d.com/ScriptReference/Rendering.CommandBuffer.BeginSample.html) on a CommandBuffer. /// [See CommandBuffer documentation](https://docs.unity3d.com/ScriptReference/Rendering.CommandBuffer.BeginSample.html) + [Obsolete("Use BeginSample(ProfilerMarker) instead.", false)] public void BeginSample(CustomSampler sampler) { m_WrappedCommandBuffer.BeginSample(sampler); } /// Wraps [EndSample](https://docs.unity3d.com/ScriptReference/Rendering.CommandBuffer.EndSample.html) on a CommandBuffer. /// [See CommandBuffer documentation](https://docs.unity3d.com/ScriptReference/Rendering.CommandBuffer.EndSample.html) + [Obsolete("Use EndSample(ProfilerMarker) instead.", false)] public void EndSample(CustomSampler sampler) { m_WrappedCommandBuffer.EndSample(sampler); } /// Wraps [BeginSample](https://docs.unity3d.com/ScriptReference/Rendering.CommandBuffer.BeginSample.html) on a CommandBuffer. diff --git a/Packages/com.unity.render-pipelines.core/Runtime/CommandBuffers/UnsafeCommandBuffer.cs b/Packages/com.unity.render-pipelines.core/Runtime/CommandBuffers/UnsafeCommandBuffer.cs index 1a39c778ef7..9a407abdc07 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/CommandBuffers/UnsafeCommandBuffer.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/CommandBuffers/UnsafeCommandBuffer.cs @@ -461,10 +461,12 @@ internal UnsafeCommandBuffer(CommandBuffer wrapped, RenderGraphPass executingPas /// Wraps [BeginSample](https://docs.unity3d.com/ScriptReference/Rendering.CommandBuffer.BeginSample.html) on a CommandBuffer. /// [See CommandBuffer documentation](https://docs.unity3d.com/ScriptReference/Rendering.CommandBuffer.BeginSample.html) + [Obsolete("Use BeginSample(ProfilerMarker) instead.", false)] public void BeginSample(CustomSampler sampler) { m_WrappedCommandBuffer.BeginSample(sampler); } /// Wraps [EndSample](https://docs.unity3d.com/ScriptReference/Rendering.CommandBuffer.EndSample.html) on a CommandBuffer. /// [See CommandBuffer documentation](https://docs.unity3d.com/ScriptReference/Rendering.CommandBuffer.EndSample.html) + [Obsolete("Use EndSample(ProfilerMarker) instead.", false)] public void EndSample(CustomSampler sampler) { m_WrappedCommandBuffer.EndSample(sampler); } /// Wraps [BeginSample](https://docs.unity3d.com/ScriptReference/Rendering.CommandBuffer.BeginSample.html) on a CommandBuffer. diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs b/Packages/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs index 8a80f7ff82d..982af3401be 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs @@ -41,6 +41,8 @@ public static void PushGlobal(CommandBuffer cmd, in CBType data, int sha /// Command Buffer used to execute the graphic commands. /// Input data of the constant buffer. /// Shader porperty id to bind the constant buffer to. + /// Thrown when the executing render graph pass does not allow + /// global state modification, like the SetGlobal* methods of the render graph command buffers. public static void PushGlobal(BaseCommandBuffer cmd, in CBType data, int shaderId) where CBType : unmanaged { var cb = ConstantBufferSingleton.instance; @@ -214,6 +216,8 @@ public static void SetGlobal(CommandBuffer cmd, int shaderId) where CBTy /// The type of structure representing the constant buffer data. /// Command Buffer used to execute the graphic commands. /// Shader porperty id to bind the constant buffer to. + /// Thrown when the executing render graph pass does not allow + /// global state modification, like the SetGlobal* methods of the render graph command buffers. public static void SetGlobal(BaseCommandBuffer cmd, int shaderId) where CBType : unmanaged { var cb = ConstantBufferSingleton.instance; @@ -413,8 +417,11 @@ public void SetGlobal(CommandBuffer cmd, int shaderId) /// /// Command Buffer used to execute the graphic commands. /// Shader porperty id to bind the constant buffer to. + /// Thrown when the executing render graph pass does not allow + /// global state modification, like the SetGlobal* methods of the render graph command buffers. public void SetGlobal(BaseCommandBuffer cmd, int shaderId) { + cmd.ThrowIfGlobalStateNotAllowed(); SetGlobal(cmd.m_WrappedCommandBuffer, shaderId); } @@ -501,6 +508,8 @@ public void PushGlobal(CommandBuffer cmd, in CBType data, int shaderId) /// Command Buffer used to execute the graphic commands. /// Input data of the constant buffer. /// Shader porperty id to bind the constant buffer to. + /// Thrown when the executing render graph pass does not allow + /// global state modification, like the SetGlobal* methods of the render graph command buffers. public void PushGlobal(BaseCommandBuffer cmd, in CBType data, int shaderId) { UpdateData(cmd, data); diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Common/ConstantBufferBackedPropertiesBridge.cs b/Packages/com.unity.render-pipelines.core/Runtime/Common/ConstantBufferBackedPropertiesBridge.cs new file mode 100644 index 00000000000..4048af961c2 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Common/ConstantBufferBackedPropertiesBridge.cs @@ -0,0 +1,22 @@ +namespace UnityEngine.Rendering +{ + // These Shader methods are internal, and the engine's InternalsVisibleTo list includes SRP Core's runtime assembly + // but not URP's: URP calls them through this class, via Unity.RenderPipelines.Core.Runtime.Shared. + internal static class ConstantBufferBackedPropertiesBridge + { + public static void SetBackedByConstantBuffer(int nameID, string warning) + { + Shader.SetGlobalShaderPropertyBackedByConstantBuffer(nameID, warning); + } + + public static void ClearWarnings() + { + Shader.ClearConstantBufferBackedPropertyWarnings(); + } + + public static void EnableWarnings(bool enable) + { + Shader.EnableConstantBufferBackedPropertyWarnings(enable); + } + } +} diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Common/ConstantBufferBackedPropertiesBridge.cs.meta b/Packages/com.unity.render-pipelines.core/Runtime/Common/ConstantBufferBackedPropertiesBridge.cs.meta new file mode 100644 index 00000000000..b215a7c9c97 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Common/ConstantBufferBackedPropertiesBridge.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 030a3d19bbea44f8bd89f58b3c5cc3ae +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Common/DynamicArray.cs b/Packages/com.unity.render-pipelines.core/Runtime/Common/DynamicArray.cs index 65535208d79..128b68707b9 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Common/DynamicArray.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/Common/DynamicArray.cs @@ -158,8 +158,9 @@ public void Insert(int index, T item) Add(item); else { - Resize(size + 1, true); - Array.Copy(m_Array, index, m_Array, index + 1, size - index); + int oldSize = size; + Resize(oldSize + 1, true); + Array.Copy(m_Array, index, m_Array, index + 1, oldSize - index); m_Array[index] = item; } } diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Debug/ProbeVolumeDebugBase.hlsl b/Packages/com.unity.render-pipelines.core/Runtime/Debug/ProbeVolumeDebugBase.hlsl index 9e124643602..18449ea901f 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Debug/ProbeVolumeDebugBase.hlsl +++ b/Packages/com.unity.render-pipelines.core/Runtime/Debug/ProbeVolumeDebugBase.hlsl @@ -14,7 +14,7 @@ float4x4 unity_MatrixVP; // Sent by builtin float4x4 unity_MatrixInvV; // Sent by builtin float4x4 unity_ObjectToWorld; // Sent by builtin float4x4 unity_MatrixV; // Sent by builtin -float4 _ScreenSize; +float4 _ProbeVolumeDebugScreenSize; float3 _WorldSpaceCameraPos; // Sent by builtin CBUFFER_END @@ -112,7 +112,7 @@ void FindSamplingData(float3 posWS, float3 normalWS, uint renderingLayer, out fl if (_DebugSamplingNoise) { float2 posNDC = ComputeNormalizedDeviceCoordinates(posWS, UNITY_MATRIX_VP); - float2 posSS = floor(posNDC.xy * _ScreenSize.xy); + float2 posSS = floor(posNDC.xy * _ProbeVolumeDebugScreenSize.xy); posWS = AddNoiseToSamplingPosition(posWS, posSS, viewDir_WS); } diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Debug/ProbeVolumeDebugFunctions.hlsl b/Packages/com.unity.render-pipelines.core/Runtime/Debug/ProbeVolumeDebugFunctions.hlsl index c5c60e38c77..28d7fc270e9 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Debug/ProbeVolumeDebugFunctions.hlsl +++ b/Packages/com.unity.render-pipelines.core/Runtime/Debug/ProbeVolumeDebugFunctions.hlsl @@ -63,7 +63,7 @@ float4 TransformPosition(float3 posOS) if (_ShadingMode == DEBUGPROBESHADINGMODE_RENDERING_LAYER_MASKS) { - o.centerCoordSS = _ScreenSize.xy * ComputeNormalizedDeviceCoordinatesWithZ(probePosition_WS, UNITY_MATRIX_VP).xy; + o.centerCoordSS = _ProbeVolumeDebugScreenSize.xy * ComputeNormalizedDeviceCoordinatesWithZ(probePosition_WS, UNITY_MATRIX_VP).xy; if (_APVLayerCount != 1 & (asuint(UNITY_ACCESS_INSTANCED_PROP(Props, _RenderingLayer)) & _RenderingLayerMask) == 0) DoCull(o); } diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DebugDisplaySerializer.cs b/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DebugDisplaySerializer.cs index 1ac665c4ffa..6538b354985 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DebugDisplaySerializer.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DebugDisplaySerializer.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; #if UNITY_EDITOR using UnityEditor; @@ -44,7 +45,14 @@ internal static bool areDebugOverlaysHidden set => instance.m_AreDebugOverlaysHidden = value; } - ISerializedDebugDisplaySettings GetOrCreate(Type type) + // TODO https://jira.unity3d.com/browse/VM-3582 Remove Pragma warning disable once Engine modules are built under net10 + // Uses this assembly's DynamicallyAccessedMembers polyfill over the engine's and the BCL's copies. + // See DynamicallyAccessedMembersAttribute.cs. +#pragma warning disable CS0436 + const DynamicallyAccessedMemberTypes k_CreatedMembers = + DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.NonPublicConstructors; + + ISerializedDebugDisplaySettings GetOrCreate([DynamicallyAccessedMembers(k_CreatedMembers)] Type type) { var setting = Get(type); if (setting != null) @@ -79,10 +87,11 @@ ISerializedDebugDisplaySettings Get(Type type) /// /// The debug display settings type to retrieve. /// The serialized instance for the given debug display settings type. - public static T GetOrCreate() where T : class, ISerializedDebugDisplaySettings + public static T GetOrCreate<[DynamicallyAccessedMembers(k_CreatedMembers)] T>() where T : class, ISerializedDebugDisplaySettings { return instance.GetOrCreate(typeof(T)) as T; } +#pragma warning restore CS0436 /// /// Returns the serialized instance for the given debug display settings type. diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DebugDisplaySettingsVolumes.cs b/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DebugDisplaySettingsVolumes.cs index 816e050ec78..706d50aa6be 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DebugDisplaySettingsVolumes.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DebugDisplaySettingsVolumes.cs @@ -78,7 +78,6 @@ private void OnSelectionChanged() } VolumeComponent m_VolumeInterpolatedResults; - private bool m_StoreStackInterpolatedValues; private ObservableList m_InfluenceVolumes = new (); private List<(Volume volume, float weight)> m_VolumesWeights = new (); @@ -104,45 +103,41 @@ static bool AreVolumesChanged(ObservableList influenceVolumes, List<(Vol return false; } - private void OnBeginVolumeStackUpdate(VolumeStack stack, Camera camera) - { - if (camera == selectedCamera) - { - ClearInterpolationData(); - m_StoreStackInterpolatedValues = selectedCamera != null && selectedComponentType != null; - } - } - - private void OnEndVolumeStackUpdate(VolumeStack stack, Camera camera) +#if UNITY_ENABLE_CHECKS + // Render pipelines set VolumeManager.instance.stack to the stack a camera renders with, so read it while + // that camera is still the current one. The stack can be shared between cameras, so copy its contents. + private void OnEndCameraRendering(ScriptableRenderContext context, Camera camera) { - if (m_StoreStackInterpolatedValues) - { - if (AreVolumesChanged(m_InfluenceVolumes, m_VolumesWeights)) - { - m_InfluenceVolumes.Clear(); - foreach (var pair in m_VolumesWeights) - m_InfluenceVolumes.Add(pair.volume); - } - - // Copy the results of the interpolation into our resulVolumeComponent - var componentInStack = stack.GetComponent(selectedComponentType); + if (camera != selectedCamera || selectedComponentType == null) + return; - for (int i = 0; i < componentInStack.parameters.Count; ++i) - { - resultVolumeComponent.parameters[i].SetValue(componentInStack.parameters[i]); - } + var stack = VolumeManager.instance.stack; + if (stack == null || !stack.isValid) + return; - m_StoreStackInterpolatedValues = false; + ClearInterpolationData(); + var contributions = stack.contributions; + for (int i = 0; i < contributions.Count; ++i) + { + if (contributions[i].volume != null) + m_VolumesWeights.Add(contributions[i]); } - } - private void OnVolumeStackInterpolated(VolumeStack stack, Volume volume, float interpolationFactor) - { - if (m_StoreStackInterpolatedValues) + if (AreVolumesChanged(m_InfluenceVolumes, m_VolumesWeights)) { - m_VolumesWeights.Add((volume, interpolationFactor)); + m_InfluenceVolumes.Clear(); + foreach (var pair in m_VolumesWeights) + m_InfluenceVolumes.Add(pair.volume); } + + var componentInStack = stack.GetComponent(selectedComponentType); + if (componentInStack == null) + return; + + for (int i = 0; i < componentInStack.parameters.Count; ++i) + resultVolumeComponent.parameters[i].SetValue(componentInStack.parameters[i]); } +#endif /// /// Obtains the volume weight @@ -178,10 +173,8 @@ public ObservableList GetVolumesList() void IDebugDisplaySettingsData.Reset() { #if UNITY_ENABLE_CHECKS - VolumeManager.instance.overrideVolumeStackData -= OnVolumeStackInterpolated; - VolumeManager.instance.beginVolumeStackUpdate -= OnBeginVolumeStackUpdate; - VolumeManager.instance.endVolumeStackUpdate -= OnEndVolumeStackUpdate; - VolumeManager.instance.renderingDebuggerAttached = false; + RenderPipelineManager.endCameraRendering -= OnEndCameraRendering; + VolumeManager.instance.recordVolumeContributions = false; #endif ClearInterpolationData(); @@ -205,9 +198,7 @@ public DebugDisplaySettingsVolume(IVolumeDebugSettings volumeDebugSettings) public DebugDisplaySettingsVolume() { #if UNITY_ENABLE_CHECKS - VolumeManager.instance.overrideVolumeStackData += OnVolumeStackInterpolated; - VolumeManager.instance.beginVolumeStackUpdate += OnBeginVolumeStackUpdate; - VolumeManager.instance.endVolumeStackUpdate += OnEndVolumeStackUpdate; + RenderPipelineManager.endCameraRendering += OnEndCameraRendering; #endif } @@ -572,8 +563,8 @@ public static DebugUI.Table CreateVolumeTable(DebugDisplaySettingsVolume data) Func hiddenCallback = () => { #if UNITY_ENABLE_CHECKS - VolumeManager.instance.renderingDebuggerAttached = data.selectedComponent > 0 && data.selectedCamera != null; - return !VolumeManager.instance.renderingDebuggerAttached; + VolumeManager.instance.recordVolumeContributions = data.selectedComponent > 0 && data.selectedCamera != null; + return !VolumeManager.instance.recordVolumeContributions; #else return true; #endif diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DebugUI.Fields.cs b/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DebugUI.Fields.cs index 4aa7d3559f6..38f4056ddee 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DebugUI.Fields.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DebugUI.Fields.cs @@ -289,8 +289,8 @@ public class IntField : Field /// Validated value. public override int ValidateValue(int value) { - if (min != null) value = Mathf.Max(value, min()); - if (max != null) value = Mathf.Min(value, max()); + if (min != null) value = Math.Max(value, min()); + if (max != null) value = Math.Min(value, max()); return value; } @@ -386,8 +386,8 @@ public class UIntField : Field /// Validated value. public override uint ValidateValue(uint value) { - if (min != null) value = (uint)Mathf.Max(value, min()); - if (max != null) value = (uint)Mathf.Min(value, max()); + if (min != null) value = Math.Max(value, min()); + if (max != null) value = Math.Min(value, max()); return value; } diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DynamicallyAccessedMembersAttribute.cs b/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DynamicallyAccessedMembersAttribute.cs new file mode 100644 index 00000000000..921d3121f4d --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DynamicallyAccessedMembersAttribute.cs @@ -0,0 +1,27 @@ +// TODO https://jira.unity3d.com/browse/VM-3582 Remove this file once Engine modules are built under net10 +namespace System.Diagnostics.CodeAnalysis +{ + // Polyfill: netstandard2.1 lacks DynamicallyAccessedMembersAttribute (net5+); the linker matches it by name. + // The engine modules also carry an internal copy, and net10 has the BCL one. + // This assembly can see both, so it keeps its own copy, which takes precedence over imported ones (CS0436). + // Without it, a net10 compile has two imported copies and fails with CS0433. +#pragma warning disable CS0436 + [AttributeUsage(AttributeTargets.GenericParameter | AttributeTargets.Parameter, Inherited = false)] + sealed class DynamicallyAccessedMembersAttribute : Attribute + { + public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes) + { + } + } +#pragma warning restore CS0436 + + // Values must match the BCL enum. + [Flags] + enum DynamicallyAccessedMemberTypes + { + None = 0, + PublicParameterlessConstructor = 1 << 0, + PublicConstructors = (1 << 1) | PublicParameterlessConstructor, + NonPublicConstructors = 1 << 2, + } +} diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DynamicallyAccessedMembersAttribute.cs.meta b/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DynamicallyAccessedMembersAttribute.cs.meta new file mode 100644 index 00000000000..f6ff77a873b --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DynamicallyAccessedMembersAttribute.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b4c11986120047fcabd204b45a5d6862 +timeCreated: 1793185418 diff --git a/Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/Utilities/ParallelBitArray.cs b/Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/Utilities/ParallelBitArray.cs index b2968bc6324..889063716ad 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/Utilities/ParallelBitArray.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/Utilities/ParallelBitArray.cs @@ -53,16 +53,15 @@ public void Resize(int newLength) var newBits = new NativeArray(newBitsLength, m_Allocator, NativeArrayOptions.UninitializedMemory); if (m_Bits.IsCreated) { - NativeArray.Copy(m_Bits, newBits, m_Bits.Length); + NativeArray.Copy(m_Bits, newBits, Math.Min(oldBitsLength, newBitsLength)); m_Bits.Dispose(); } m_Bits = newBits; } - // mask off bits past the length + // mask off bits past the length, including stale bits in the last valid chunk int validLength = Math.Min(oldLength, newLength); - int validBitsLength = Math.Min(oldBitsLength, newBitsLength); - for (int chunkIndex = validBitsLength; chunkIndex < m_Bits.Length; ++chunkIndex) + for (int chunkIndex = validLength / 64; chunkIndex < m_Bits.Length; ++chunkIndex) { int validBitCount = Math.Max(validLength - 64 * chunkIndex, 0); if (validBitCount < 64) diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/AGENTS.md b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/AGENTS.md new file mode 100644 index 00000000000..05cad8d9ac7 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/AGENTS.md @@ -0,0 +1,35 @@ +# Lighting code + +These rules are the standard for new lighting code in this folder and in the folders that point to this file: `../PathTracing`, `../UnifiedRayTracing` and the URP Surface Cache GI renderer feature. Surface Cache (`SurfaceCache/`) follows them and is the code to copy. Older lighting code may not follow them. + +Shader inputs and state: + +- Only kernel, vertex and fragment entry points read shader globals. Library `.hlsl` files declare no globals. Their functions take inputs as parameters, grouped into a parameter struct when there are many (`PatchUtil::VolumeParamSet` in `SurfaceCache/PatchUtil.hlsl`). +- Do not pass a result to other code by writing a shader global. +- A pass that enables a keyword on a shared compute shader or material disables it again after its dispatch or draw, as the passes in `SurfaceCache/SurfaceCache.cs` do. A mode is always one keyword out of a complete set, never "no keyword". +- Restore a global flag such as `ShaderUtil.allowAsyncCompilation` before the function that changed it returns. + +Shader structure: + +- Each `.compute` file holds one kernel. Variants of that kernel for a ray tracing backend or for stereo rendering are acceptable (`SurfaceCache/Estimation.compute` has a compute and a hardware variant). Code that kernels share goes in an included `.hlsl` file. +- In `.hlsl` files, constants are `static const`, not `#define`. A `.compute` file uses `#define` only for values that `[numthreads]` needs. +- A macro that an including file defines before the `#include` is named after the file that reads it: `PATCH_UTIL_USE_RW_*` for `SurfaceCache/PatchUtil.hlsl`, `RING_BUFFER_USE_RW_RING_CONFIG_BUFFER` for `SurfaceCache/RingBuffer.hlsl`, `UNIFIED_RT_*` for Unified Ray Tracing. + +Layering: + +- Library code knows nothing about its callers: no camera, depth buffer, editor, play mode, URP, renderer feature or test concepts. It reads no `RenderSettings`, `SystemInfo`, `Time.frameCount` or render-pipeline state. The calling feature reads those and passes the values in. +- Work that needs a camera or screen pixels lives in the render pipeline feature. The Surface Cache screen resolve, denoising and upsampling passes are in the URP feature, not in `SurfaceCache/`. +- Callers pass every input explicitly. Do not add optional parameters with default values. A caller that wants the default configuration names it. + +Failures: + +- Return failures to the caller and let the calling feature log them. Do not add `Debug.Log`, `Debug.LogWarning` or `Debug.LogError` for a resource or capacity failure. +- Use `Debug.Assert` for states that cannot happen, and do not handle them gracefully. Use control flow only for states a caller can reach. +- A fallible function that produces an index or slot returns `bool` and gives the value through an `out` parameter, as `MaterialPool.TryAddCookieTexture` in `../PathTracing` does. Do not encode failure in a magic index such as `-1` or `int.MaxValue`. A typed handle with an `Invalid` value is acceptable. +- Report each failure one way only. Do not return a failure value and also throw or catch an exception for the same failure. +- Callers check a fallible result before they index or look up with it. + +Naming: + +- Give a type that groups inputs a `ParameterSet` suffix in C# (`SurfaceCacheVolumeParameterSet`) and a `ParamSet` suffix in HLSL (`VolumeParamSet`). Do not use a `Data` suffix, except for RenderGraph `PassData`. +- Call the material that renders an environment cubemap the "cubemap material" (`_cubemapMaterial` in `../PathTracing/Environment/CubemapRender.cs`), not the "sky box". Its shader may not render a sky. Unity API names such as `RenderSettings.skybox` keep their spelling. diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/AGENTS.md.meta b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/AGENTS.md.meta new file mode 100644 index 00000000000..15250bc5a30 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/AGENTS.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 9549c2cb3445f4e4dad6fc2fca39a809 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/CLAUDE.md b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/CLAUDE.md new file mode 100644 index 00000000000..43c994c2d36 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/CLAUDE.md.meta b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/CLAUDE.md.meta new file mode 100644 index 00000000000..a773b56a0f1 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/CLAUDE.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: ca1998d636d744714a9529cfdc9b2c93 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeReferenceVolume.Debug.cs b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeReferenceVolume.Debug.cs index 2969026cd29..767fd5e2665 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeReferenceVolume.Debug.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeReferenceVolume.Debug.cs @@ -247,6 +247,11 @@ Mesh debugMesh Material m_DebugFragmentationMaterial; readonly Plane[] m_DebugFrustumPlanes = new Plane[6]; + static Vector4 DebugScreenSize(Camera camera) + { + return new Vector4(camera.pixelWidth, camera.pixelHeight, 1.0f / camera.pixelWidth, 1.0f / camera.pixelHeight); + } + // Scenario blending debug data GUIContent[] m_DebugScenarioNames = new GUIContent[0]; int[] m_DebugScenarioValues = new int[0]; @@ -1033,6 +1038,7 @@ void DrawProbeDebug(Camera camera, Texture exposureTexture) m_ProbeSamplingDebugMaterial.SetFloat("_ProbeSize", probeVolumeDebug.probeSamplingDebugSize); m_ProbeSamplingDebugMaterial.SetTexture("_NumbersTex", m_DisplayNumbersTexture); m_ProbeSamplingDebugMaterial.SetInt("_DebugSamplingNoise", Convert.ToInt32(probeVolumeDebug.debugWithSamplingNoise)); + m_ProbeSamplingDebugMaterial.SetVector("_ProbeVolumeDebugScreenSize", DebugScreenSize(camera)); m_ProbeSamplingDebugMaterial.SetInt("_ForceDebugNormalViewBias", 0); // Add a secondary locator to show intermediate position (with no Anti-Leak) when Anti-Leak is active m_ProbeSamplingDebugMaterial.SetBuffer("_positionNormalBuffer", s_ProbeSamplingDebugData.positionNormalBuffer); @@ -1084,7 +1090,7 @@ void DrawProbeDebug(Camera camera, Texture exposureTexture) { m_DebugMaterial.SetVectorArray("_TouchupVolumeBounds", adjustmentVolumeBounds); m_DebugMaterial.SetInt("_AdjustmentVolumeCount", probeVolumeDebug.isolationProbeDebug ? adjustmentVolumeCount : 0); - m_DebugMaterial.SetVector("_ScreenSize", new Vector4(camera.pixelWidth, camera.pixelHeight, 1.0f/camera.pixelWidth, 1.0f/camera.pixelHeight)); + m_DebugMaterial.SetVector("_ProbeVolumeDebugScreenSize", DebugScreenSize(camera)); var probeBuffer = debug.probeBuffers[i]; m_DebugMaterial.SetInt("_DebugProbeVolumeSampling", 0); @@ -1096,6 +1102,7 @@ void DrawProbeDebug(Camera camera, Texture exposureTexture) { var probeBuffer = debug.probeBuffers[i]; m_ProbeSamplingDebugMaterial02.SetInt("_DebugProbeVolumeSampling", 1); + m_ProbeSamplingDebugMaterial02.SetVector("_ProbeVolumeDebugScreenSize", DebugScreenSize(camera)); props.SetInt("_ShadingMode", (int)DebugProbeShadingMode.SH); props.SetFloat("_ProbeSize", probeVolumeDebug.probeSamplingDebugSize); props.SetInt("_DebugSamplingNoise", Convert.ToInt32(probeVolumeDebug.debugWithSamplingNoise)); diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeReferenceVolume.cs b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeReferenceVolume.cs index a80270ad315..94fe7e545eb 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeReferenceVolume.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeReferenceVolume.cs @@ -979,7 +979,19 @@ internal void RegisterBakingSet(ProbeVolumePerSceneData data) internal void UnloadBakingSet() { // Need to make sure everything is unloaded before killing the baking set ref (we need it to unload cell CPU data). +#if UNITY_EDITOR + m_IsUnloadingBakingSet = true; + try + { + PerformPendingOperations(); + } + finally + { + m_IsUnloadingBakingSet = false; + } +#else PerformPendingOperations(); +#endif if (m_CurrentBakingSet != null) m_CurrentBakingSet.Cleanup(); @@ -1643,13 +1655,14 @@ public void PerformPendingOperations() #if UNITY_EDITOR Scene m_TrackedActiveScene; + bool m_IsUnloadingBakingSet; // Keeps the current baking set in sync with the active scene. Skipped while a bake is running, since the // current set is owned by EnsureCurrentBakingSet for its duration; the mismatch is picked up again once the // bake ends, on whichever call to PerformPendingOperations comes first. internal void TrackActiveScene() { - if (Application.isPlaying || UnityEditor.Lightmapping.isRunning || isBakingAdaptiveProbeVolumes) + if (m_IsUnloadingBakingSet || Application.isPlaying || UnityEditor.Lightmapping.isRunning || isBakingAdaptiveProbeVolumes) return; var activeScene = SceneManager.GetActiveScene(); diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolume.hlsl b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolume.hlsl index f5ec966672a..63c92be230d 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolume.hlsl +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolume.hlsl @@ -210,7 +210,7 @@ TEXTURE3D_APV(_APVProbeOcclusion); TEXTURE3D_APV(_APVResValidity); TEXTURE3D_APV(_SkyOcclusionTexL0L1); -TEXTURE3D(_SkyShadingDirectionIndicesTex); +TEXTURE3D_FLOAT(_SkyShadingDirectionIndicesTex); // ------------------------------------------------------------- diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeBakingSet.Editor.cs b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeBakingSet.Editor.cs index 40866241689..2524546398e 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeBakingSet.Editor.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeBakingSet.Editor.cs @@ -639,8 +639,10 @@ internal void EnsurePerSceneData(Scene scene, GUID sceneGuid) { var go = new GameObject("ProbeVolumePerSceneData"); go.hideFlags |= HideFlags.HideInHierarchy; - var perSceneData = go.AddComponent(); + + // Move before adding the component so OnEnable picks up the GUID of the target scene SceneManager.MoveGameObjectToScene(go, scene); + go.AddComponent(); } } } diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeGlobalSettings.cs b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeGlobalSettings.cs index 708fb9f4f83..86847542d30 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeGlobalSettings.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeGlobalSettings.cs @@ -87,7 +87,7 @@ class ProbeVolumeGlobalSettings : IRenderPipelineGraphicsSettings { [SerializeField, HideInInspector] int m_Version = 1; - [SerializeField, Tooltip("Enabling this will make APV baked data assets compatible with Addressables and Asset Bundles. This will also make Disk Streaming unavailable. After changing this setting, a clean rebuild may be required for data assets to be included in Adressables and Asset Bundles.")] + [SerializeField, Tooltip("Enabling this will make APV baked data assets compatible with Addressables and Asset Bundles. This will also make Disk Streaming unavailable. After changing this setting, a clean rebuild may be required for data assets to be included in Addressables and Asset Bundles.")] bool m_ProbeVolumeDisableStreamingAssets; public int version { get => m_Version; } diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/AGENTS.md b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/AGENTS.md new file mode 100644 index 00000000000..500c6ac10ca --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/AGENTS.md @@ -0,0 +1,5 @@ +# Surface Cache + +- The lighting rules in `../AGENTS.md` apply here. Surface Cache is the reference for them. Its `.hlsl` files declare no globals, and every pass in `SurfaceCache.cs` disables the keywords it enabled. +- Transparency mode is always one of two keywords, `OpaquesOnly` or `Cutouts`. +- Runtime tests live in `Tests/SRPTests/Packages/com.unity.testing.surface-cache.core/` and `Tests/SRPTests/Packages/com.unity.testing.surface-cache.urp/`. The URP_GI jobs run them through `Tests/SRPTests/Projects/UniversalGraphicsTest_Lighting`. Do not add runtime tests under `Packages/com.unity.render-pipelines.core/Tests/`. diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/AGENTS.md.meta b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/AGENTS.md.meta new file mode 100644 index 00000000000..91354ee870e --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/AGENTS.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 0168e6e119f2c456982e1e2ea45c79ce +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/CLAUDE.md b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/CLAUDE.md new file mode 100644 index 00000000000..43c994c2d36 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/CLAUDE.md.meta b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/CLAUDE.md.meta new file mode 100644 index 00000000000..4aeac4b4b46 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/CLAUDE.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 1afa42958ffa64f17b31a7bb6e6ba592 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/Defrag.compute b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/Defrag.compute index 2956e6241f9..96dade3013c 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/Defrag.compute +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/Defrag.compute @@ -45,9 +45,7 @@ RWStructuredBuffer _PatchIrradiances1; RWStructuredBuffer _PatchGeometries; RWStructuredBuffer _PatchStatistics; -uint _RingConfigReadOffset; -uint _RingConfigWriteOffset; -uint _PatchOffset; +#include "DefragConstants.cs.hlsl" [numthreads(GROUP_SIZE, 1, 1)] void Defrag(Threading::Group group) diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/DefragConstants.cs b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/DefragConstants.cs new file mode 100644 index 00000000000..1d553f0848b --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/DefragConstants.cs @@ -0,0 +1,11 @@ +namespace UnityEngine.Rendering +{ + [GenerateHLSL(needAccessors = false, generateCBuffer = true)] + internal struct SurfaceCacheDefragConstants + { + public uint _RingConfigReadOffset; + public uint _RingConfigWriteOffset; + public uint _PatchOffset; + public uint _DefragPad0; + } +} diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/DefragConstants.cs.hlsl b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/DefragConstants.cs.hlsl new file mode 100644 index 00000000000..fa3572336e5 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/DefragConstants.cs.hlsl @@ -0,0 +1,17 @@ +// +// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead +// + +#ifndef SURFACECACHEDEFRAGCONSTANTS_CS_HLSL +#define SURFACECACHEDEFRAGCONSTANTS_CS_HLSL +// Generated from UnityEngine.Rendering.SurfaceCacheDefragConstants +// PackingRules = Exact +CBUFFER_START(SurfaceCacheDefragConstants) + uint _RingConfigReadOffset; + uint _RingConfigWriteOffset; + uint _PatchOffset; + uint _DefragPad0; +CBUFFER_END + + +#endif diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/DefragConstants.cs.hlsl.meta b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/DefragConstants.cs.hlsl.meta new file mode 100644 index 00000000000..9ca520d720b --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/DefragConstants.cs.hlsl.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: c18c26488093f4460bba9e42bccac7b0 +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/DefragConstants.cs.meta b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/DefragConstants.cs.meta new file mode 100644 index 00000000000..0fa9b108788 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/DefragConstants.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: a7b33f6eaa1144634acf514d89eac39f \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleAddition.compute b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleAddition.compute index fed9dbebd74..e6f8a0f9646 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleAddition.compute +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleAddition.compute @@ -1,13 +1,13 @@ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal ps5 switch2 #pragma kernel Add +#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" #include "EmissiveTriangles.hlsl" RWStructuredBuffer _EmissiveTriangles; RWStructuredBuffer _EmissiveTriangleCounter; -uint _SubmeshInstanceId; -uint _SubmeshTriangleCount; +#include "EmissiveTriangleAdditionConstants.cs.hlsl" groupshared uint _GroupAddCount; groupshared uint _GroupAddBaseOffset; diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleAdditionConstants.cs b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleAdditionConstants.cs new file mode 100644 index 00000000000..f62d84690fa --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleAdditionConstants.cs @@ -0,0 +1,11 @@ +namespace UnityEngine.Rendering +{ + [GenerateHLSL(needAccessors = false, generateCBuffer = true)] + internal struct SurfaceCacheEmissiveTriangleAdditionConstants + { + public uint _SubmeshInstanceId; + public uint _SubmeshTriangleCount; + public uint _EmissiveTriangleAdditionPad0; + public uint _EmissiveTriangleAdditionPad1; + } +} diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleAdditionConstants.cs.hlsl b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleAdditionConstants.cs.hlsl new file mode 100644 index 00000000000..9ab4444c0d3 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleAdditionConstants.cs.hlsl @@ -0,0 +1,17 @@ +// +// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead +// + +#ifndef SURFACECACHEEMISSIVETRIANGLEADDITIONCONSTANTS_CS_HLSL +#define SURFACECACHEEMISSIVETRIANGLEADDITIONCONSTANTS_CS_HLSL +// Generated from UnityEngine.Rendering.SurfaceCacheEmissiveTriangleAdditionConstants +// PackingRules = Exact +CBUFFER_START(SurfaceCacheEmissiveTriangleAdditionConstants) + uint _SubmeshInstanceId; + uint _SubmeshTriangleCount; + uint _EmissiveTriangleAdditionPad0; + uint _EmissiveTriangleAdditionPad1; +CBUFFER_END + + +#endif diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleAdditionConstants.cs.hlsl.meta b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleAdditionConstants.cs.hlsl.meta new file mode 100644 index 00000000000..b90156acb40 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleAdditionConstants.cs.hlsl.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 71c87dd689a164ab0934b72db1479353 +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleAdditionConstants.cs.meta b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleAdditionConstants.cs.meta new file mode 100644 index 00000000000..140837b3e54 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleAdditionConstants.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f269a59d5e3df4d25833911769442887 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleRemoval.compute b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleRemoval.compute index 1873dc5a66d..9ce4f803ac8 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleRemoval.compute +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleRemoval.compute @@ -1,6 +1,7 @@ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal ps5 switch2 #pragma kernel Remove +#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" #include "EmissiveTriangles.hlsl" StructuredBuffer _SrcTriangles; @@ -8,7 +9,7 @@ StructuredBuffer _SrcTriangleCount; RWStructuredBuffer _DstTriangles; RWStructuredBuffer _DstTriangleCount; StructuredBuffer _RemovedInstanceIds; -uint _RemovedInstanceIdCount; +#include "EmissiveTriangleRemovalConstants.cs.hlsl" groupshared EmissiveTriangle _GroupSurvivors[256]; groupshared uint _GroupSurvivorCount; diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleRemovalConstants.cs b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleRemovalConstants.cs new file mode 100644 index 00000000000..a3b41f15788 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleRemovalConstants.cs @@ -0,0 +1,11 @@ +namespace UnityEngine.Rendering +{ + [GenerateHLSL(needAccessors = false, generateCBuffer = true)] + internal struct SurfaceCacheEmissiveTriangleRemovalConstants + { + public uint _RemovedInstanceIdCount; + public uint _EmissiveTriangleRemovalPad0; + public uint _EmissiveTriangleRemovalPad1; + public uint _EmissiveTriangleRemovalPad2; + } +} diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleRemovalConstants.cs.hlsl b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleRemovalConstants.cs.hlsl new file mode 100644 index 00000000000..8fae204492d --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleRemovalConstants.cs.hlsl @@ -0,0 +1,17 @@ +// +// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead +// + +#ifndef SURFACECACHEEMISSIVETRIANGLEREMOVALCONSTANTS_CS_HLSL +#define SURFACECACHEEMISSIVETRIANGLEREMOVALCONSTANTS_CS_HLSL +// Generated from UnityEngine.Rendering.SurfaceCacheEmissiveTriangleRemovalConstants +// PackingRules = Exact +CBUFFER_START(SurfaceCacheEmissiveTriangleRemovalConstants) + uint _RemovedInstanceIdCount; + uint _EmissiveTriangleRemovalPad0; + uint _EmissiveTriangleRemovalPad1; + uint _EmissiveTriangleRemovalPad2; +CBUFFER_END + + +#endif diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleRemovalConstants.cs.hlsl.meta b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleRemovalConstants.cs.hlsl.meta new file mode 100644 index 00000000000..e74a9d4997d --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleRemovalConstants.cs.hlsl.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 628b3c52f9e5144c4b68b0a3ac755bce +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleRemovalConstants.cs.meta b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleRemovalConstants.cs.meta new file mode 100644 index 00000000000..f23c7e92f9b --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EmissiveTriangleRemovalConstants.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: d4373a4e387a14d48b7e83d605ef8a2d \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/Estimation.compute b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/Estimation.compute index 6a9c750b5fc..0b5a55d819d 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/Estimation.compute +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/Estimation.compute @@ -14,6 +14,7 @@ #pragma kernel EstimateCompute Estimate=EstimateCompute UNIFIED_RT_BACKEND_COMPUTE #pragma kernel EstimateHardware Estimate=EstimateHardware UNIFIED_RT_BACKEND_HARDWARE #pragma require inlineraytracing : UNIFIED_RT_BACKEND_HARDWARE +#pragma multi_compile_local SURFACE_CACHE_PATH_TRACING_TRANSPARENCY_MODE_OPAQUES_ONLY SURFACE_CACHE_PATH_TRACING_TRANSPARENCY_MODE_CUTOUTS // Shader variant 'EstimateHardware' fails to compile on Metal with inlineraytracing // enabled due to inlineraytracing requiring DXC over FXC compilation path. @@ -62,27 +63,7 @@ TextureCube _EnvironmentCubemap; SamplerState sampler_EnvironmentCubemap; UNIFIED_RT_DECLARE_ACCEL_STRUCT(_RayTracingAccelerationStructure); -uint _PunctualLightCount; -uint _FrameIdx; -uint _VolumeSpatialResolution; -uint _VolumeCascadeCount; -float _VolumeVoxelMinSize; -uint _MultiBounce; -uint _SampleCount; -uint _WarmUpSampleMultiplier; -uint _PunctualLightCandidateCount; -float _ShortHysteresis; -uint _RingConfigOffset; -float3 _VolumeTargetPos; -int _PatchWarping; -float _MaterialAtlasTexelSize; // The size of 1 texel in the atlases above -float _AlbedoBoost; -float _EnvironmentIntensityMultiplier; -float _EmissiveTriangleIntensityMultiplier; -uint _PunctualLightSampleCount; -float3 _DirectionalLightDirection; -float3 _DirectionalLightIntensity; -uint _BouncePatchAllocation; +#include "EstimationConstants.cs.hlsl" SphericalHarmonics::RGBL1 FilterTemporallyVarianceGuided( float shortHysteresis, @@ -160,14 +141,14 @@ void ProjectAndAccumulate(inout SphericalHarmonics::RGBL1 accumulator, float3 sa accumulator.l1s[2] += sampleRadiance * SphericalHarmonics::y1Constant * sampleDirection.x; } -float GetAdditionalRayOffset(float volumeVoxelMinSize) +float GetAdditionalRayOffset(float volumeVoxelMinSize, float rayTracingNormalBias) { // We currently use the OffsetRayOrigin() heuristic to offset ray origins to avoid self-intersections. While this // helps for Surface Cache it is not enough since the ray origins are relatively imprecise because they are derived // from output of the rasterizer (as opposed to being reconstructed via barycentrics). // We fix this by adding an additional offset. This offset is a percentage of the min voxel size to keep it // somewhat proportional to the scene scale. - return volumeVoxelMinSize * 0.001; + return volumeVoxelMinSize * 0.001 + rayTracingNormalBias; } void SamplePunctualLightBounceRadianceUniform( @@ -181,12 +162,13 @@ void SamplePunctualLightBounceRadianceUniform( StructuredBuffer lightSamples, uint lightSamplesLength, float volumeVoxelMinSize, + float rayTracingNormalBias, PatchUtil::PatchGeometry patchGeo, inout SphericalHarmonics::RGBL1 accumulator, inout bool gotValidSamples) { SphericalHarmonics::RGBL1 radianceAccumulator = (SphericalHarmonics::RGBL1)0; - const float3 reconnectionRayOrigin = OffsetRayOrigin(patchGeo.position, patchGeo.normal, GetAdditionalRayOffset(volumeVoxelMinSize)); + const float3 reconnectionRayOrigin = OffsetRayOrigin(patchGeo.position, patchGeo.normal, GetAdditionalRayOffset(volumeVoxelMinSize, rayTracingNormalBias)); uint validSampleCount = 0; for(uint sampleIdx = 0; sampleIdx < sampleCount; ++sampleIdx) @@ -209,7 +191,6 @@ void SamplePunctualLightBounceRadianceUniform( lightSample.hitPos, lightSample.hitInstanceId, lightSample.hitPrimitiveIndex, - patchGeo.position, reconnectionRayOrigin, discardSample)) { @@ -223,8 +204,7 @@ void SamplePunctualLightBounceRadianceUniform( lights, lightSample, patchGeo.position, - patchGeo.normal, - reconnectionRayOrigin); + patchGeo.normal); validSampleCount++; ProjectAndAccumulate(radianceAccumulator, radianceSample.radianceOverDensity, radianceSample.direction); @@ -271,12 +251,13 @@ void SamplePunctualLightBounceRadianceRIS( uint lightSamplesLength, uint candidateCount, float volumeVoxelMinSize, + float rayTracingNormalBias, PatchUtil::PatchGeometry patchGeo, inout SphericalHarmonics::RGBL1 accumulator, inout bool gotValidSamples) { SphericalHarmonics::RGBL1 radianceAccumulator = (SphericalHarmonics::RGBL1)0; - const float3 reconnectionRayOrigin = OffsetRayOrigin(patchGeo.position, patchGeo.normal, GetAdditionalRayOffset(volumeVoxelMinSize)); + const float3 reconnectionRayOrigin = OffsetRayOrigin(patchGeo.position, patchGeo.normal, GetAdditionalRayOffset(volumeVoxelMinSize, rayTracingNormalBias)); uint validSampleCount = 0; for(uint sampleIdx = 0; sampleIdx < sampleCount; ++sampleIdx) @@ -298,8 +279,7 @@ void SamplePunctualLightBounceRadianceRIS( lights, punctualLightSample, patchGeo.position, - patchGeo.normal, - reconnectionRayOrigin); + patchGeo.normal); // weight = targetVal / sourceDensity, and targetVal = Luminance(radiance), so // weight = Luminance(radiance / sourceDensity) = Luminance(radiance) / sourceDensity. @@ -325,7 +305,6 @@ void SamplePunctualLightBounceRadianceRIS( reservoir.lightSample.hitPos, reservoir.lightSample.hitInstanceId, reservoir.lightSample.hitPrimitiveIndex, - patchGeo.position, reconnectionRayOrigin, discardSample)) { @@ -366,6 +345,7 @@ void SampleEmissiveTriangleRadiance( MaterialPoolParamSet matPoolParams, float emissiveTriangleIntensityMultiplier, float volumeVoxelMinSize, + float rayTracingNormalBias, PatchUtil::PatchGeometry patchGeo, inout SphericalHarmonics::RGBL1 accumulator, inout bool gotValidSamples) @@ -385,7 +365,7 @@ void SampleEmissiveTriangleRadiance( emissiveTriangleIntensityMultiplier, patchGeo.position, patchGeo.normal, - GetAdditionalRayOffset(volumeVoxelMinSize), + GetAdditionalRayOffset(volumeVoxelMinSize, rayTracingNormalBias), rng.GetSample(0).x, rng.GetSample(1)); @@ -420,11 +400,12 @@ void SampleEnvironmentAndDirectionalBounceAndMultiBounceRadiance( RWStructuredBuffer patchStatistics, CellPatchIndexBufferType cellPatchIndices, PatchUtil::VolumeParamSet volumeParams, + float rayTracingNormalBias, inout SphericalHarmonics::RGBL1 accumulator, inout bool gotValidSamples) { UnifiedRT::Ray ray; - ray.origin = OffsetRayOrigin(patchGeo.position, patchGeo.normal, GetAdditionalRayOffset(volumeParams.voxelMinSize)); + ray.origin = OffsetRayOrigin(patchGeo.position, patchGeo.normal, GetAdditionalRayOffset(volumeParams.voxelMinSize, rayTracingNormalBias)); ray.tMin = 0; ray.tMax = FLT_MAX; @@ -440,8 +421,8 @@ void SampleEnvironmentAndDirectionalBounceAndMultiBounceRadiance( accelStruct, ray, matPoolParams, - _DirectionalLightDirection, - _DirectionalLightIntensity, + _DirectionalLightDirection.xyz, + _DirectionalLightIntensity.xyz, _MultiBounce, _EnvironmentCubemap, _EnvironmentIntensityMultiplier, @@ -502,7 +483,7 @@ void Estimate(uint patchIdx : SV_DispatchThreadID, uint groupThreadIndex : SV_Gr PatchUtil::VolumeParamSet volumeParams; volumeParams.spatialResolution = _VolumeSpatialResolution; volumeParams.voxelMinSize = _VolumeVoxelMinSize; - volumeParams.targetPos = _VolumeTargetPos; + volumeParams.targetPos = _VolumeTargetPos.xyz; volumeParams.cascadeOffsets = _VolumeCascadeOffsets; volumeParams.cascadeCount = _VolumeCascadeCount; volumeParams.patchWarping = _PatchWarping != 0; @@ -544,6 +525,7 @@ void Estimate(uint patchIdx : SV_DispatchThreadID, uint groupThreadIndex : SV_Gr _PatchStatistics, _CellPatchIndices, volumeParams, + _RayTracingNormalBias, radianceEstimate, gotValidSamples); @@ -563,6 +545,7 @@ void Estimate(uint patchIdx : SV_DispatchThreadID, uint groupThreadIndex : SV_Gr _PunctualLightSampleCount, _PunctualLightCandidateCount, _VolumeVoxelMinSize, + _RayTracingNormalBias, patchGeo, radianceEstimate, gotValidSamples); @@ -582,6 +565,7 @@ void Estimate(uint patchIdx : SV_DispatchThreadID, uint groupThreadIndex : SV_Gr matPoolParams, _EmissiveTriangleIntensityMultiplier, _VolumeVoxelMinSize, + _RayTracingNormalBias, patchGeo, radianceEstimate, gotValidSamples); diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EstimationConstants.cs b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EstimationConstants.cs new file mode 100644 index 00000000000..ba374911e7e --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EstimationConstants.cs @@ -0,0 +1,36 @@ +namespace UnityEngine.Rendering +{ + [GenerateHLSL(needAccessors = false, generateCBuffer = true)] + internal struct SurfaceCacheEstimationConstants + { + // Vectors are declared as Vector4 because some platforms (e.g. Metal) don't pack a scalar into the last component of a float3. + public Vector4 _VolumeTargetPos; // xyz: position, w: unused. + public Vector4 _DirectionalLightDirection; // xyz: direction, w: unused. + public Vector4 _DirectionalLightIntensity; // xyz: intensity, w: unused. + + public uint _PunctualLightCount; + public uint _FrameIdx; + public uint _VolumeSpatialResolution; + public uint _VolumeCascadeCount; + + public uint _MultiBounce; + public uint _SampleCount; + public uint _WarmUpSampleMultiplier; + public uint _RingConfigOffset; + + public int _PatchWarping; + public float _AlbedoBoost; + public float _EnvironmentIntensityMultiplier; + public float _EmissiveTriangleIntensityMultiplier; + + public uint _PunctualLightSampleCount; + public uint _BouncePatchAllocation; + public float _VolumeVoxelMinSize; + public float _ShortHysteresis; + + public float _MaterialAtlasTexelSize; // The size of 1 texel in the material atlases. + public uint _PunctualLightCandidateCount; + public float _RayTracingNormalBias; + public uint _EstimationPad0; + } +} diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EstimationConstants.cs.hlsl b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EstimationConstants.cs.hlsl new file mode 100644 index 00000000000..9c62693a27b --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EstimationConstants.cs.hlsl @@ -0,0 +1,36 @@ +// +// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead +// + +#ifndef SURFACECACHEESTIMATIONCONSTANTS_CS_HLSL +#define SURFACECACHEESTIMATIONCONSTANTS_CS_HLSL +// Generated from UnityEngine.Rendering.SurfaceCacheEstimationConstants +// PackingRules = Exact +CBUFFER_START(SurfaceCacheEstimationConstants) + float4 _VolumeTargetPos; + float4 _DirectionalLightDirection; + float4 _DirectionalLightIntensity; + uint _PunctualLightCount; + uint _FrameIdx; + uint _VolumeSpatialResolution; + uint _VolumeCascadeCount; + uint _MultiBounce; + uint _SampleCount; + uint _WarmUpSampleMultiplier; + uint _RingConfigOffset; + int _PatchWarping; + float _AlbedoBoost; + float _EnvironmentIntensityMultiplier; + float _EmissiveTriangleIntensityMultiplier; + uint _PunctualLightSampleCount; + uint _BouncePatchAllocation; + float _VolumeVoxelMinSize; + float _ShortHysteresis; + float _MaterialAtlasTexelSize; + uint _PunctualLightCandidateCount; + float _RayTracingNormalBias; + uint _EstimationPad0; +CBUFFER_END + + +#endif diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EstimationConstants.cs.hlsl.meta b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EstimationConstants.cs.hlsl.meta new file mode 100644 index 00000000000..ac4260b901b --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EstimationConstants.cs.hlsl.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 5e7b3ab81bfb84c72a91b994db44b801 +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EstimationConstants.cs.meta b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EstimationConstants.cs.meta new file mode 100644 index 00000000000..8b6b629c3eb --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EstimationConstants.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 19773ad9d772640b585c881a13cb0d9a \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/Eviction.compute b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/Eviction.compute index 1aefb134e5c..8cf404f2125 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/Eviction.compute +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/Eviction.compute @@ -10,9 +10,7 @@ RWStructuredBuffer _CellAllocationMarks; RWStructuredBuffer _CellPatchIndices; RWStructuredBuffer _PatchCellIndices; -uint _RingConfigOffset; -uint _FrameIdx; -uint _BouncePatchAllocation; +#include "EvictionConstants.cs.hlsl" [numthreads(256, 1, 1)] void Evict(uint patchIdx : SV_DispatchThreadID) diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EvictionConstants.cs b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EvictionConstants.cs new file mode 100644 index 00000000000..ee05895fda5 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EvictionConstants.cs @@ -0,0 +1,11 @@ +namespace UnityEngine.Rendering +{ + [GenerateHLSL(needAccessors = false, generateCBuffer = true)] + internal struct SurfaceCacheEvictionConstants + { + public uint _RingConfigOffset; + public uint _FrameIdx; + public uint _BouncePatchAllocation; + public uint _EvictionPad0; + } +} diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EvictionConstants.cs.hlsl b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EvictionConstants.cs.hlsl new file mode 100644 index 00000000000..0a9b339166c --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EvictionConstants.cs.hlsl @@ -0,0 +1,17 @@ +// +// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead +// + +#ifndef SURFACECACHEEVICTIONCONSTANTS_CS_HLSL +#define SURFACECACHEEVICTIONCONSTANTS_CS_HLSL +// Generated from UnityEngine.Rendering.SurfaceCacheEvictionConstants +// PackingRules = Exact +CBUFFER_START(SurfaceCacheEvictionConstants) + uint _RingConfigOffset; + uint _FrameIdx; + uint _BouncePatchAllocation; + uint _EvictionPad0; +CBUFFER_END + + +#endif diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EvictionConstants.cs.hlsl.meta b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EvictionConstants.cs.hlsl.meta new file mode 100644 index 00000000000..ab77aecf188 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EvictionConstants.cs.hlsl.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: feb000f0bdb104ad0bdfca7b87d30cc7 +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EvictionConstants.cs.meta b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EvictionConstants.cs.meta new file mode 100644 index 00000000000..65326bcf648 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/EvictionConstants.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c044e386cef85449c95103896d7ecf31 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/GlobalProbe.compute b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/GlobalProbe.compute index 73418c46cbc..626d3683b93 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/GlobalProbe.compute +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/GlobalProbe.compute @@ -8,7 +8,7 @@ RWStructuredBuffer _GlobalProbe; TextureCube _EnvironmentCubemap; SamplerState sampler_EnvironmentCubemap; -float _EnvironmentIntensityMultiplier; +#include "GlobalProbeConstants.cs.hlsl" #define SAMPLE_COUNT 32 diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/GlobalProbeConstants.cs b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/GlobalProbeConstants.cs new file mode 100644 index 00000000000..38c0a4a83e3 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/GlobalProbeConstants.cs @@ -0,0 +1,11 @@ +namespace UnityEngine.Rendering +{ + [GenerateHLSL(needAccessors = false, generateCBuffer = true)] + internal struct SurfaceCacheGlobalProbeConstants + { + public float _EnvironmentIntensityMultiplier; + public uint _GlobalProbePad0; + public uint _GlobalProbePad1; + public uint _GlobalProbePad2; + } +} diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/GlobalProbeConstants.cs.hlsl b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/GlobalProbeConstants.cs.hlsl new file mode 100644 index 00000000000..059a13ea824 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/GlobalProbeConstants.cs.hlsl @@ -0,0 +1,17 @@ +// +// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead +// + +#ifndef SURFACECACHEGLOBALPROBECONSTANTS_CS_HLSL +#define SURFACECACHEGLOBALPROBECONSTANTS_CS_HLSL +// Generated from UnityEngine.Rendering.SurfaceCacheGlobalProbeConstants +// PackingRules = Exact +CBUFFER_START(SurfaceCacheGlobalProbeConstants) + float _EnvironmentIntensityMultiplier; + uint _GlobalProbePad0; + uint _GlobalProbePad1; + uint _GlobalProbePad2; +CBUFFER_END + + +#endif diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/GlobalProbeConstants.cs.hlsl.meta b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/GlobalProbeConstants.cs.hlsl.meta new file mode 100644 index 00000000000..617bebe1756 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/GlobalProbeConstants.cs.hlsl.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: b38adfb884a024adfba240981d635df4 +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/GlobalProbeConstants.cs.meta b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/GlobalProbeConstants.cs.meta new file mode 100644 index 00000000000..36cbc37d92f --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/GlobalProbeConstants.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: a9c82055287414d099d31ae5d2e83ec5 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PatchAllocation.compute b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PatchAllocation.compute index 17db2447beb..ecb8ae10ba8 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PatchAllocation.compute +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PatchAllocation.compute @@ -18,13 +18,7 @@ StructuredBuffer _Requests; StructuredBuffer _RequestCount; StructuredBuffer _VolumeCascadeOffsets; -uint _RingConfigOffset; -uint _VolumeSpatialResolution; -uint _VolumeCascadeCount; -float _VolumeVoxelMinSize; -float3 _VolumeTargetPos; -int _PatchWarping; -uint _FrameIndex; +#include "PatchAllocationConstants.cs.hlsl" [numthreads(256, 1, 1)] void Allocate(uint threadIdx : SV_DispatchThreadID) @@ -36,7 +30,7 @@ void Allocate(uint threadIdx : SV_DispatchThreadID) PatchUtil::VolumeParamSet volumeParams; volumeParams.spatialResolution = _VolumeSpatialResolution; volumeParams.voxelMinSize = _VolumeVoxelMinSize; - volumeParams.targetPos = _VolumeTargetPos; + volumeParams.targetPos = _VolumeTargetPos.xyz; volumeParams.cascadeOffsets = _VolumeCascadeOffsets; volumeParams.cascadeCount = _VolumeCascadeCount; volumeParams.patchWarping = _PatchWarping != 0; diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PatchAllocationConstants.cs b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PatchAllocationConstants.cs new file mode 100644 index 00000000000..61a7114b4e1 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PatchAllocationConstants.cs @@ -0,0 +1,18 @@ +namespace UnityEngine.Rendering +{ + [GenerateHLSL(needAccessors = false, generateCBuffer = true)] + internal struct SurfaceCachePatchAllocationConstants + { + public Vector4 _VolumeTargetPos; // xyz: position, w: unused. + + public uint _RingConfigOffset; + public uint _VolumeSpatialResolution; + public uint _VolumeCascadeCount; + public int _PatchWarping; + + public float _VolumeVoxelMinSize; + public uint _FrameIndex; + public uint _PatchAllocationPad0; + public uint _PatchAllocationPad1; + } +} diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PatchAllocationConstants.cs.hlsl b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PatchAllocationConstants.cs.hlsl new file mode 100644 index 00000000000..7b50b2a6d83 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PatchAllocationConstants.cs.hlsl @@ -0,0 +1,22 @@ +// +// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead +// + +#ifndef SURFACECACHEPATCHALLOCATIONCONSTANTS_CS_HLSL +#define SURFACECACHEPATCHALLOCATIONCONSTANTS_CS_HLSL +// Generated from UnityEngine.Rendering.SurfaceCachePatchAllocationConstants +// PackingRules = Exact +CBUFFER_START(SurfaceCachePatchAllocationConstants) + float4 _VolumeTargetPos; + uint _RingConfigOffset; + uint _VolumeSpatialResolution; + uint _VolumeCascadeCount; + int _PatchWarping; + float _VolumeVoxelMinSize; + uint _FrameIndex; + uint _PatchAllocationPad0; + uint _PatchAllocationPad1; +CBUFFER_END + + +#endif diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PatchAllocationConstants.cs.hlsl.meta b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PatchAllocationConstants.cs.hlsl.meta new file mode 100644 index 00000000000..ec90364c629 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PatchAllocationConstants.cs.hlsl.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 0923fe0000ead484391c30846b711f58 +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PatchAllocationConstants.cs.meta b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PatchAllocationConstants.cs.meta new file mode 100644 index 00000000000..260c8c5889e --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PatchAllocationConstants.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 6217136d0f543485eb6199aca1149ce4 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PathTracing.hlsl b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PathTracing.hlsl index e0f52c8104a..365a084ff6c 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PathTracing.hlsl +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PathTracing.hlsl @@ -55,6 +55,7 @@ struct MaterialPoolParamSet }; static const float3 invalidRadiance = float3(-1.0f, -1.0f, -1.0f); +static const float alphaCutoutThreshold = 0.5f; struct RadianceSample { @@ -137,13 +138,46 @@ UnifiedRT::Hit TraceRayClosestHit( uint dispatchThreadIndex, uint groupThreadIndex, UnifiedRT::RayTracingAccelStruct accelStruct, - UnifiedRT::Ray ray) + UnifiedRT::Ray ray, + StructuredBuffer materialEntries, + Texture2DArray albedoTextures, + SamplerState albedoSampler, + float atlasTexelSize) { const uint instanceMask = 0xFFFFFFFF; +#if defined(SURFACE_CACHE_PATH_TRACING_TRANSPARENCY_MODE_CUTOUTS) + UNIFIED_RT_RAY_QUERY_TYPE(UnifiedRT::kRayFlagNone) rayQuery; + UNIFIED_RT_INIT_RAY_QUERY(UnifiedRT::kRayFlagNone, rayQuery, dispatchThreadIndex, groupThreadIndex, accelStruct, UnifiedRT::kRayFlagNone, instanceMask, ray); + + while (rayQuery.Proceed()) + { + if (rayQuery.CandidateType() != UnifiedRT::kCandidateNonOpaqueTriangle) + continue; + + // Fetch candidate hit info + const uint candidateInstanceID = rayQuery.CandidateInstanceID(); + const uint candidatePrimitiveIndex = rayQuery.CandidatePrimitiveIndex(); + const float2 candidateUvBarycentrics = rayQuery.CandidateTriangleBarycentrics(); + const UnifiedRT::InstanceData hitInstance = UnifiedRT::GetInstance(candidateInstanceID); + const int geometryIndex = g_AccelStructInstanceList[candidateInstanceID].geometryIndex; + const UnifiedRT::HitGeomAttributes attributes = UnifiedRT::FetchHitGeomAttributes( + geometryIndex, + candidatePrimitiveIndex, + candidateUvBarycentrics, + UnifiedRT::kGeomAttribTexCoord0 | UnifiedRT::kGeomAttribTexCoord1); + + // Check if we must continue the ray based on alpha + const MaterialPool::MaterialEntry matEntry = materialEntries[hitInstance.userMaterialID]; + const float alpha = MaterialPool::LoadAlbedo(matEntry, albedoTextures, albedoSampler, atlasTexelSize, attributes.uv0, attributes.uv1).a; + if (alpha > alphaCutoutThreshold) + rayQuery.CommitNonOpaqueTriangleHit(); + } +#elif defined(SURFACE_CACHE_PATH_TRACING_TRANSPARENCY_MODE_OPAQUES_ONLY) UNIFIED_RT_RAY_QUERY_TYPE(UnifiedRT::kRayFlagForceOpaque) rayQuery; UNIFIED_RT_INIT_RAY_QUERY(UnifiedRT::kRayFlagForceOpaque, rayQuery, dispatchThreadIndex, groupThreadIndex, accelStruct, UnifiedRT::kRayFlagNone, instanceMask, ray); rayQuery.Proceed(); +#endif UnifiedRT::Hit hitResult = UnifiedRT::Hit::Invalid(); if (rayQuery.CommittedStatus() == UnifiedRT::kCommittedTriangleHit) @@ -162,8 +196,7 @@ RadianceSample EvaluateUnshadowedPunctualLightSampleBounceRadiance( StructuredBuffer lights, PunctualLightSample punctualLightSample, float3 position, - float3 normal, - float3 reconnectionRayOrigin) + float3 normal) { RadianceSample result = (RadianceSample)0; @@ -171,7 +204,7 @@ RadianceSample EvaluateUnshadowedPunctualLightSampleBounceRadiance( const float planeDistance = dot(normal, punctualLightSample.hitPos - position); if (epsilon < planeDistance) // Light sample hit point must be "in front" of the patch. { - const float reconnectionDistance = distance(reconnectionRayOrigin, punctualLightSample.hitPos); + const float reconnectionDistance = distance(position, punctualLightSample.hitPos); const float reciprocalReconnectionDistance = rcp(reconnectionDistance); const PunctualLight light = lights[punctualLightSample.lightIndex]; @@ -225,16 +258,15 @@ bool RejectPunctualLightSample( float3 hitPos, uint hitInstanceId, uint hitPrimitiveIndex, - float3 position, float3 reconnectionRayOrigin, out bool discardSample) { UnifiedRT::Ray reconnectionRay; reconnectionRay.origin = reconnectionRayOrigin; - reconnectionRay.direction = normalize(hitPos - position); + reconnectionRay.direction = normalize(hitPos - reconnectionRayOrigin); reconnectionRay.tMin = 0; reconnectionRay.tMax = FLT_MAX; - UnifiedRT::Hit reconnectionResult = TraceRayClosestHit(dispatchThreadIndex, groupThreadIndex, accelStruct, reconnectionRay); + UnifiedRT::Hit reconnectionResult = TraceRayClosestHit(dispatchThreadIndex, groupThreadIndex, accelStruct, reconnectionRay, matPoolParams.materialEntries, matPoolParams.albedoTextures, matPoolParams.albedoSampler, matPoolParams.atlasTexelSize); bool reconnectionOccluded = false; discardSample = !reconnectionResult.IsValid(); @@ -337,7 +369,15 @@ EmissiveTriangleSample SampleEmissiveTriangles( const float2 uv1 = bary0 * tri.v0.uv1 + bary1 * tri.v1.uv1 + bary2 * tri.v2.uv1; const MaterialPool::MaterialEntry matEntry = matPoolParams.materialEntries[instance.userMaterialID]; - const float3 emission = MaterialPool::LoadEmission(matEntry, matPoolParams.emissionTextures, matPoolParams.emissionSampler, matPoolParams.atlasTexelSize, uv0, uv1); + float3 emission = MaterialPool::LoadEmission(matEntry, matPoolParams.emissionTextures, matPoolParams.emissionSampler, matPoolParams.atlasTexelSize, uv0, uv1); +#if defined(SURFACE_CACHE_PATH_TRACING_TRANSPARENCY_MODE_CUTOUTS) + if (MaterialPool::IsTransmissive(matEntry.flags)) + { + const float alpha = MaterialPool::LoadAlbedo(matEntry, matPoolParams.albedoTextures, matPoolParams.albedoSampler, matPoolParams.atlasTexelSize, uv0, uv1).a; + if (alpha <= alphaCutoutThreshold) + emission = 0.0f; + } +#endif emissiveSample.pos = bary0 * tri.w0 + bary1 * tri.w1 + bary2 * tri.w2; emissiveSample.normal = crossProduct * instance.localToWorldDetSign / doubleArea; @@ -403,7 +443,7 @@ RadianceSample EstimateIncomingRadianceFromEmissiveTriangles( shadowRay.direction = shadowRayDirection; shadowRay.tMin = 0; shadowRay.tMax = distanceToLight * (1.0f - epsilon); // Just a bit shorter than the real distance - UnifiedRT::Hit shadowHit = TraceRayClosestHit(dispatchThreadIndex, groupThreadIndex, accelStruct, shadowRay); + UnifiedRT::Hit shadowHit = TraceRayClosestHit(dispatchThreadIndex, groupThreadIndex, accelStruct, shadowRay, matPoolParams.materialEntries, matPoolParams.albedoTextures, matPoolParams.albedoSampler, matPoolParams.atlasTexelSize); if (shadowHit.IsValid()) { const UnifiedRT::InstanceData hitInstance = UnifiedRT::GetInstance(shadowHit.instanceID); @@ -443,6 +483,7 @@ float3 OutgoingDirectionalBounceAndMultiBounceRadiance( uint dispatchThreadIndex, uint groupThreadIndex, UnifiedRT::RayTracingAccelStruct accelStruct, + MaterialPoolParamSet matPoolParams, float3 dirLightDirection, float3 dirLightIntensity, bool multiBounce, @@ -465,7 +506,7 @@ float3 OutgoingDirectionalBounceAndMultiBounceRadiance( shadowRay.tMin = 0; shadowRay.tMax = FLT_MAX; - UnifiedRT::Hit hitResult = TraceRayClosestHit(dispatchThreadIndex, groupThreadIndex, accelStruct, shadowRay); + UnifiedRT::Hit hitResult = TraceRayClosestHit(dispatchThreadIndex, groupThreadIndex, accelStruct, shadowRay, matPoolParams.materialEntries, matPoolParams.albedoTextures, matPoolParams.albedoSampler, matPoolParams.atlasTexelSize); if (!hitResult.IsValid()) { radiance += dirLightIntensity * dot(-dirLightDirection, normal); @@ -513,7 +554,7 @@ float3 IncomingEnvironmentAndDirectionalBounceAndMultiBounceAndEmissionRadiance( bool enablePatchAllocation, uint frameIndex) { - UnifiedRT::Hit hitResult = TraceRayClosestHit(dispatchThreadIndex, groupThreadIndex, accelStruct, ray); + UnifiedRT::Hit hitResult = TraceRayClosestHit(dispatchThreadIndex, groupThreadIndex, accelStruct, ray, matPoolParams.materialEntries, matPoolParams.albedoTextures, matPoolParams.albedoSampler, matPoolParams.atlasTexelSize); float3 radiance; if (hitResult.IsValid()) { @@ -551,6 +592,7 @@ float3 IncomingEnvironmentAndDirectionalBounceAndMultiBounceAndEmissionRadiance( dispatchThreadIndex, groupThreadIndex, accelStruct, + matPoolParams, dirLightDirection, dirLightIntensity, multiBounce, diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PunctualLightSampling.compute b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PunctualLightSampling.compute index 487c7080c01..8112a13e46d 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PunctualLightSampling.compute +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PunctualLightSampling.compute @@ -9,6 +9,7 @@ #pragma kernel SamplePunctualLightsCompute SamplePunctualLights=SamplePunctualLightsCompute UNIFIED_RT_BACKEND_COMPUTE #pragma kernel SamplePunctualLightsHardware SamplePunctualLights=SamplePunctualLightsHardware UNIFIED_RT_BACKEND_HARDWARE #pragma require inlineraytracing : UNIFIED_RT_BACKEND_HARDWARE +#pragma multi_compile_local SURFACE_CACHE_PATH_TRACING_TRANSPARENCY_MODE_OPAQUES_ONLY SURFACE_CACHE_PATH_TRACING_TRANSPARENCY_MODE_CUTOUTS // Shader variant 'SamplePunctualLightsHardware' fails to compile on Metal with inlineraytracing // enabled due to inlineraytracing requiring DXC over FXC compilation path. @@ -38,11 +39,7 @@ RWStructuredBuffer _Samples; StructuredBuffer _MaterialEntries; Texture2DArray _AlbedoTextures; SamplerState sampler_AlbedoTextures; -float _MaterialAtlasTexelSize; -float _AlbedoBoost; -uint _FrameIdx; -uint _PunctualLightCount; -uint _SamplesPerPunctualLight; +#include "PunctualLightSamplingConstants.cs.hlsl" [numthreads(THREAD_GROUP_SIZE, 1, 1)] void SamplePunctualLights(uint dispatchThreadIdx : SV_DispatchThreadID, uint groupThreadIdx : SV_GroupIndex) @@ -79,7 +76,7 @@ void SamplePunctualLights(uint dispatchThreadIdx : SV_DispatchThreadID, uint gro PunctualLightSample lightSample = (PunctualLightSample)0; lightSample.rayDirection = ray.direction; - UnifiedRT::Hit hitResult = TraceRayClosestHit(dispatchThreadIdx, groupThreadIdx, accelStruct, ray); + UnifiedRT::Hit hitResult = TraceRayClosestHit(dispatchThreadIdx, groupThreadIdx, accelStruct, ray, matPoolParams.materialEntries, matPoolParams.albedoTextures, matPoolParams.albedoSampler, matPoolParams.atlasTexelSize); if (hitResult.IsValid()) { const UnifiedRT::InstanceData hitInstance = UnifiedRT::GetInstance(hitResult.instanceID); diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PunctualLightSamplingConstants.cs b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PunctualLightSamplingConstants.cs new file mode 100644 index 00000000000..64ed21835c8 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PunctualLightSamplingConstants.cs @@ -0,0 +1,16 @@ +namespace UnityEngine.Rendering +{ + [GenerateHLSL(needAccessors = false, generateCBuffer = true)] + internal struct SurfaceCachePunctualLightSamplingConstants + { + public float _MaterialAtlasTexelSize; + public float _AlbedoBoost; + public uint _FrameIdx; + public uint _PunctualLightCount; + + public uint _SamplesPerPunctualLight; + public uint _PunctualLightSamplingPad0; + public uint _PunctualLightSamplingPad1; + public uint _PunctualLightSamplingPad2; + } +} diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PunctualLightSamplingConstants.cs.hlsl b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PunctualLightSamplingConstants.cs.hlsl new file mode 100644 index 00000000000..578010a002b --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PunctualLightSamplingConstants.cs.hlsl @@ -0,0 +1,21 @@ +// +// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead +// + +#ifndef SURFACECACHEPUNCTUALLIGHTSAMPLINGCONSTANTS_CS_HLSL +#define SURFACECACHEPUNCTUALLIGHTSAMPLINGCONSTANTS_CS_HLSL +// Generated from UnityEngine.Rendering.SurfaceCachePunctualLightSamplingConstants +// PackingRules = Exact +CBUFFER_START(SurfaceCachePunctualLightSamplingConstants) + float _MaterialAtlasTexelSize; + float _AlbedoBoost; + uint _FrameIdx; + uint _PunctualLightCount; + uint _SamplesPerPunctualLight; + uint _PunctualLightSamplingPad0; + uint _PunctualLightSamplingPad1; + uint _PunctualLightSamplingPad2; +CBUFFER_END + + +#endif diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PunctualLightSamplingConstants.cs.hlsl.meta b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PunctualLightSamplingConstants.cs.hlsl.meta new file mode 100644 index 00000000000..40c60f29442 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PunctualLightSamplingConstants.cs.hlsl.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: ece9befcde53b494c810f87aae6f6b0e +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PunctualLightSamplingConstants.cs.meta b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PunctualLightSamplingConstants.cs.meta new file mode 100644 index 00000000000..67cd1c9ab93 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PunctualLightSamplingConstants.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 431dcf5ba50264b3f8cd3b1c4c22fcfd \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/Scrolling.compute b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/Scrolling.compute index 0365f87535d..adb571a349e 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/Scrolling.compute +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/Scrolling.compute @@ -12,9 +12,7 @@ RWStructuredBuffer _PatchCellIndices; StructuredBuffer _NewVolumeCascadeOffsets; -int4 _OldVolumeCascadeOffsets[cascadeMax]; -uint _VolumeSpatialResolution; -uint _VolumeCascadeCount; +#include "ScrollingConstants.cs.hlsl" [numthreads(8, 8, 8)] void Scroll(uint3 threadId : SV_DispatchThreadID) @@ -26,7 +24,7 @@ void Scroll(uint3 threadId : SV_DispatchThreadID) const uint cascadeIdx = threadId.z / _VolumeSpatialResolution; const int3 newCascadeOffset = _NewVolumeCascadeOffsets[cascadeIdx]; - const int3 oldCascadeOffset = _OldVolumeCascadeOffsets[cascadeIdx].xyz; + const int3 oldCascadeOffset = asint(_OldVolumeCascadeOffsets[cascadeIdx].xyz); const int3 positionStorageSpaceInt = int3(positionStorageSpace); const int3 oldPositionVolumeSpace = PatchUtil::ConvertStorageSpaceToVolumeSpace(positionStorageSpaceInt, _VolumeSpatialResolution, oldCascadeOffset); diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/ScrollingConstants.cs b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/ScrollingConstants.cs new file mode 100644 index 00000000000..c6fbc2636d5 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/ScrollingConstants.cs @@ -0,0 +1,15 @@ +namespace UnityEngine.Rendering +{ + [GenerateHLSL(needAccessors = false, generateCBuffer = true)] + internal unsafe struct SurfaceCacheScrollingConstants + { + // Signed offsets stored as uints, since constant buffer arrays must be declared with 4-component elements. + [HLSLArray((int)SurfaceCache.CascadeMax, typeof(ShaderGenUInt4))] + public fixed uint _OldVolumeCascadeOffsets[(int)SurfaceCache.CascadeMax * 4]; + + public uint _VolumeSpatialResolution; + public uint _VolumeCascadeCount; + public uint _ScrollingPad0; + public uint _ScrollingPad1; + } +} diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/ScrollingConstants.cs.hlsl b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/ScrollingConstants.cs.hlsl new file mode 100644 index 00000000000..e186ae73ecb --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/ScrollingConstants.cs.hlsl @@ -0,0 +1,18 @@ +// +// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead +// + +#ifndef SURFACECACHESCROLLINGCONSTANTS_CS_HLSL +#define SURFACECACHESCROLLINGCONSTANTS_CS_HLSL +// Generated from UnityEngine.Rendering.SurfaceCacheScrollingConstants +// PackingRules = Exact +CBUFFER_START(SurfaceCacheScrollingConstants) + uint4 _OldVolumeCascadeOffsets[8]; + uint _VolumeSpatialResolution; + uint _VolumeCascadeCount; + uint _ScrollingPad0; + uint _ScrollingPad1; +CBUFFER_END + + +#endif diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/ScrollingConstants.cs.hlsl.meta b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/ScrollingConstants.cs.hlsl.meta new file mode 100644 index 00000000000..0b59820e721 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/ScrollingConstants.cs.hlsl.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: cb0c3ac2d829b4a38bf175afb71df8c1 +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/ScrollingConstants.cs.meta b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/ScrollingConstants.cs.meta new file mode 100644 index 00000000000..ce7e3dd10df --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/ScrollingConstants.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f558cbd235509460ab2af8fba129edbb \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/SpatialFiltering.compute b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/SpatialFiltering.compute index c4bc12d710a..cc8ae0d40c4 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/SpatialFiltering.compute +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/SpatialFiltering.compute @@ -14,15 +14,7 @@ RWStructuredBuffer _OutputPatchIrradiances; StructuredBuffer _CellPatchIndices; StructuredBuffer _VolumeCascadeOffsets; -uint _FrameIdx; -float _VolumeVoxelMinSize; -uint _VolumeCascadeCount; -uint _VolumeSpatialResolution; -uint _SampleCount; -uint _RingConfigOffset; -float _Radius; -float3 _VolumeTargetPos; -int _PatchWarping; +#include "SpatialFilteringConstants.cs.hlsl" [numthreads(64, 1, 1)] void FilterSpatially(uint patchIdx : SV_DispatchThreadID) @@ -42,11 +34,11 @@ void FilterSpatially(uint patchIdx : SV_DispatchThreadID) float3 right; OrthoBasisFromVector(patchGeo.normal, up, right); - const int cascadeResolution = PatchUtil::ResolveCascadeIndex(_VolumeTargetPos, patchGeo.position, _VolumeSpatialResolution, _VolumeCascadeCount, _VolumeVoxelMinSize); + const int cascadeResolution = PatchUtil::ResolveCascadeIndex(_VolumeTargetPos.xyz, patchGeo.position, _VolumeSpatialResolution, _VolumeCascadeCount, _VolumeVoxelMinSize); const uint cascadeIdx = cascadeResolution != -1 ? cascadeResolution : _VolumeCascadeCount - 1; PatchUtil::VolumeParamSet volume; - volume.targetPos = _VolumeTargetPos; + volume.targetPos = _VolumeTargetPos.xyz; volume.spatialResolution = _VolumeSpatialResolution; volume.voxelMinSize = _VolumeVoxelMinSize; volume.cascadeOffsets = _VolumeCascadeOffsets; diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/SpatialFilteringConstants.cs b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/SpatialFilteringConstants.cs new file mode 100644 index 00000000000..b0d6b73b17c --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/SpatialFilteringConstants.cs @@ -0,0 +1,18 @@ +namespace UnityEngine.Rendering +{ + [GenerateHLSL(needAccessors = false, generateCBuffer = true)] + internal struct SurfaceCacheSpatialFilteringConstants + { + public Vector4 _VolumeTargetPos; // xyz: position, w: unused. + + public uint _FrameIdx; + public uint _VolumeCascadeCount; + public uint _VolumeSpatialResolution; + public uint _SampleCount; + + public uint _RingConfigOffset; + public float _Radius; + public int _PatchWarping; + public float _VolumeVoxelMinSize; + } +} diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/SpatialFilteringConstants.cs.hlsl b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/SpatialFilteringConstants.cs.hlsl new file mode 100644 index 00000000000..79a94d2ee18 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/SpatialFilteringConstants.cs.hlsl @@ -0,0 +1,22 @@ +// +// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead +// + +#ifndef SURFACECACHESPATIALFILTERINGCONSTANTS_CS_HLSL +#define SURFACECACHESPATIALFILTERINGCONSTANTS_CS_HLSL +// Generated from UnityEngine.Rendering.SurfaceCacheSpatialFilteringConstants +// PackingRules = Exact +CBUFFER_START(SurfaceCacheSpatialFilteringConstants) + float4 _VolumeTargetPos; + uint _FrameIdx; + uint _VolumeCascadeCount; + uint _VolumeSpatialResolution; + uint _SampleCount; + uint _RingConfigOffset; + float _Radius; + int _PatchWarping; + float _VolumeVoxelMinSize; +CBUFFER_END + + +#endif diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/SpatialFilteringConstants.cs.hlsl.meta b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/SpatialFilteringConstants.cs.hlsl.meta new file mode 100644 index 00000000000..c12c259ed19 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/SpatialFilteringConstants.cs.hlsl.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 01ed1bb7c414749fbad9d62300572bb2 +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/SpatialFilteringConstants.cs.meta b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/SpatialFilteringConstants.cs.meta new file mode 100644 index 00000000000..e1c86622f2e --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/SpatialFilteringConstants.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 5b7e818984e2f421a89e97590ad10355 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/SurfaceCache.cs b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/SurfaceCache.cs index 233d98a5a69..8f15cb1a803 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/SurfaceCache.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/SurfaceCache.cs @@ -182,6 +182,8 @@ internal struct SurfaceCacheEstimationParameterSet public uint WarmUpSampleMultiplier; public uint PunctualLightCandidateCount; public bool DistanceFallback; + public bool AlphaCutouts; + public float RayTracingNormalBias; } internal struct SurfaceCachePatchFilteringParameterSet @@ -195,6 +197,9 @@ internal struct SurfaceCachePatchFilteringParameterSet internal class SurfaceCacheResourceSet { + internal const string OpaquesOnlyKeyword = "SURFACE_CACHE_PATH_TRACING_TRANSPARENCY_MODE_OPAQUES_ONLY"; + internal const string CutoutsKeyword = "SURFACE_CACHE_PATH_TRACING_TRANSPARENCY_MODE_CUTOUTS"; + internal RayTracingBackend RayTracingBackend; internal ComputeShader ScrollingShader; @@ -217,10 +222,14 @@ internal class SurfaceCacheResourceSet internal ComputeShader EstimationShader; internal int EstimationKernel; internal uint EstimationKernelGroupSize; + internal LocalKeyword EstimationOpaquesOnlyKeyword; + internal LocalKeyword EstimationCutoutsKeyword; internal ComputeShader PunctualLightSamplingShader; internal int PunctualLightSamplingKernel; internal uint PunctualLightSamplingKernelGroupSize; + internal LocalKeyword PunctualLightSamplingOpaquesOnlyKeyword; + internal LocalKeyword PunctualLightSamplingCutoutsKeyword; internal ComputeShader SpatialFilteringShader; internal int SpatialFilteringKernel; @@ -276,11 +285,19 @@ internal void Load( EstimationShader = estimationShader; EstimationKernel = estimationShader.FindKernel(rtBackend == RayTracingBackend.Compute ? "EstimateCompute" : "EstimateHardware"); + EstimationOpaquesOnlyKeyword = new LocalKeyword(EstimationShader, OpaquesOnlyKeyword); + EstimationCutoutsKeyword = new LocalKeyword(EstimationShader, CutoutsKeyword); + EstimationShader.EnableKeyword(EstimationOpaquesOnlyKeyword); EstimationShader.GetKernelThreadGroupSizes(EstimationKernel, out EstimationKernelGroupSize, out _, out _); + EstimationShader.DisableKeyword(EstimationOpaquesOnlyKeyword); PunctualLightSamplingShader = punctualLightSamplingShader; PunctualLightSamplingKernel = PunctualLightSamplingShader.FindKernel(rtBackend == RayTracingBackend.Compute ? "SamplePunctualLightsCompute" : "SamplePunctualLightsHardware"); + PunctualLightSamplingOpaquesOnlyKeyword = new LocalKeyword(PunctualLightSamplingShader, OpaquesOnlyKeyword); + PunctualLightSamplingCutoutsKeyword = new LocalKeyword(PunctualLightSamplingShader, CutoutsKeyword); + PunctualLightSamplingShader.EnableKeyword(PunctualLightSamplingOpaquesOnlyKeyword); PunctualLightSamplingShader.GetKernelThreadGroupSizes(PunctualLightSamplingKernel, out PunctualLightSamplingKernelGroupSize, out _, out _); + PunctualLightSamplingShader.DisableKeyword(PunctualLightSamplingOpaquesOnlyKeyword); GlobalProbeShader = globalProbeShader; GlobalProbeKernel = globalProbeShader.FindKernel("Update"); @@ -296,6 +313,32 @@ internal void Load( } } + internal class SurfaceCacheConstantBufferSet : IDisposable + { + public readonly ConstantBuffer Scrolling = new(); + public readonly ConstantBuffer Eviction = new(); + public readonly ConstantBuffer Defrag = new(); + public readonly ConstantBuffer GlobalProbe = new(); + public readonly ConstantBuffer PunctualLightSampling = new(); + public readonly ConstantBuffer Estimation = new(); + public readonly ConstantBuffer PatchAllocation = new(); + public readonly ConstantBuffer SpatialFiltering = new(); + public readonly ConstantBuffer TemporalFiltering = new(); + + public void Dispose() + { + Scrolling.Release(); + Eviction.Release(); + Defrag.Release(); + GlobalProbe.Release(); + PunctualLightSampling.Release(); + Estimation.Release(); + PatchAllocation.Release(); + SpatialFiltering.Release(); + TemporalFiltering.Release(); + } + } + internal class SurfaceCache : IDisposable { public const uint CascadeMax = 8; @@ -311,6 +354,8 @@ internal class SurfaceCache : IDisposable private readonly SurfaceCacheResourceSet _resources; private readonly GraphicsBuffer _globalProbe; + private readonly SurfaceCacheConstantBufferSet _constantBuffers = new(); + private GraphicsBuffer _traceScratch; uint[] _zero = new uint[] { 0 }; @@ -335,6 +380,7 @@ internal class SurfaceCache : IDisposable private class ScrollingPassData { internal ComputeShader Shader; + internal ConstantBuffer Constants; internal int KernelIndex; internal uint3 ThreadGroupSize; internal GraphicsBuffer CellAllocationMarks; @@ -351,6 +397,7 @@ private class EvictionPassData { internal uint PatchCapacity; internal ComputeShader Shader; + internal ConstantBuffer Constants; internal int KernelIndex; internal uint3 ThreadGroupSize; internal GraphicsBuffer RingConfigBuffer; @@ -366,6 +413,7 @@ private class EvictionPassData private class DefragPassData { internal ComputeShader Shader; + internal ConstantBuffer Constants; internal int KernelIndex; internal LocalKeyword Keyword; internal uint PatchCapacity; @@ -388,11 +436,15 @@ private class EstimationPassData { internal uint PatchCapacity; internal ComputeShader EstimationShader; + internal ConstantBuffer EstimationConstants; internal int EstimationKernelIndex; internal uint EstimationKernelGroupSize; + internal LocalKeyword EstimationTransparencyModeKeyword; internal ComputeShader PunctualLightSamplingShader; + internal ConstantBuffer PunctualLightSamplingConstants; internal int PunctualLightSamplingKernelIndex; internal uint PunctualLightSamplingKernelGroupSize; + internal LocalKeyword PunctualLightSamplingTransparencyModeKeyword; internal GraphicsBuffer RingConfigBuffer; internal GraphicsBuffer PatchIrradiances; internal GraphicsBuffer PatchGeometries; @@ -411,6 +463,7 @@ private class EstimationPassData internal uint CascadeCount; internal bool MultiBounce; internal ComputeShader GlobalProbeShader; + internal ConstantBuffer GlobalProbeConstants; internal int GlobalProbeKernelIndex; internal uint3 GlobalProbeKernelGroupSize; internal bool UpdateGlobalProbe; @@ -423,6 +476,7 @@ private class EstimationPassData internal uint PunctualLightCandidateCount; internal uint VolumeSpatialResolution; internal float VolumeVoxelMinSize; + internal float RayTracingNormalBias; internal bool PatchWarpingEnabled; internal Vector3 VolumeTargetPos; internal GraphicsBuffer TraceScratchBuffer; @@ -432,6 +486,7 @@ private class EstimationPassData private class PatchAllocationPassData { internal ComputeShader Shader; + internal ConstantBuffer Constants; internal int KernelIndex; internal uint3 ThreadGroupSize; internal GraphicsBuffer Requests; @@ -463,6 +518,7 @@ private class SpatialFilterPassData internal GraphicsBuffer CellPatchIndices; internal GraphicsBuffer VolumeCascadeOffsets; internal ComputeShader Shader; + internal ConstantBuffer Constants; internal int KernelIndex; internal uint3 ThreadGroupSize; internal uint PatchCapacity; @@ -480,6 +536,7 @@ private class SpatialFilterPassData private class TemporalFilterPassData { internal ComputeShader Shader; + internal ConstantBuffer Constants; internal int KernelIndex; internal uint3 ThreadGroupSize; internal GraphicsBuffer InputPatchIrradiances; @@ -494,35 +551,13 @@ private class TemporalFilterPassData internal static class ShaderIDs { public static readonly int _CellAllocationMarks = Shader.PropertyToID("_CellAllocationMarks"); - public static readonly int _BouncePatchAllocation = Shader.PropertyToID("_BouncePatchAllocation"); public static readonly int _CellPatchIndices = Shader.PropertyToID("_CellPatchIndices"); public static readonly int _MaterialEntries = Shader.PropertyToID("_MaterialEntries"); public static readonly int _AlbedoTextures = Shader.PropertyToID("_AlbedoTextures"); - public static readonly int _AlbedoBoost = Shader.PropertyToID("_AlbedoBoost"); - public static readonly int _EnvironmentIntensityMultiplier = Shader.PropertyToID("_EnvironmentIntensityMultiplier"); - public static readonly int _EmissiveTriangleIntensityMultiplier = Shader.PropertyToID("_EmissiveTriangleIntensityMultiplier"); - public static readonly int _DirectionalLightDirection = Shader.PropertyToID("_DirectionalLightDirection"); - public static readonly int _DirectionalLightIntensity = Shader.PropertyToID("_DirectionalLightIntensity"); - public static readonly int _MaterialAtlasTexelSize = Shader.PropertyToID("_MaterialAtlasTexelSize"); - public static readonly int _PunctualLightCount = Shader.PropertyToID("_PunctualLightCount"); - public static readonly int _SamplesPerPunctualLight = Shader.PropertyToID("_SamplesPerPunctualLight"); public static readonly int _GlobalProbe = Shader.PropertyToID("_GlobalProbe"); public static readonly int _EmissionTextures = Shader.PropertyToID("_EmissionTextures"); - public static readonly int _VolumeTargetPos = Shader.PropertyToID("_VolumeTargetPos"); public static readonly int _EnvironmentCubemap = Shader.PropertyToID("_EnvironmentCubemap"); public static readonly int _NewVolumeCascadeOffsets = Shader.PropertyToID("_NewVolumeCascadeOffsets"); - public static readonly int _OldVolumeCascadeOffsets = Shader.PropertyToID("_OldVolumeCascadeOffsets"); - public static readonly int _VolumeSpatialResolution = Shader.PropertyToID("_VolumeSpatialResolution"); - public static readonly int _VolumeCascadeCount = Shader.PropertyToID("_VolumeCascadeCount"); - public static readonly int _SampleCount = Shader.PropertyToID("_SampleCount"); - public static readonly int _WarmUpSampleMultiplier = Shader.PropertyToID("_WarmUpSampleMultiplier"); - public static readonly int _PunctualLightCandidateCount = Shader.PropertyToID("_PunctualLightCandidateCount"); - public static readonly int _MultiBounce = Shader.PropertyToID("_MultiBounce"); - public static readonly int _VolumeVoxelMinSize = Shader.PropertyToID("_VolumeVoxelMinSize"); - public static readonly int _PatchWarping = Shader.PropertyToID("_PatchWarping"); - public static readonly int _PunctualLightSampleCount = Shader.PropertyToID("_PunctualLightSampleCount"); - public static readonly int _ShortHysteresis = Shader.PropertyToID("_ShortHysteresis"); - public static readonly int _TemporalSmoothing = Shader.PropertyToID("_TemporalSmoothing"); public static readonly int _PatchCellIndices = Shader.PropertyToID("_PatchCellIndices"); public static readonly int _RingConfigBuffer = Shader.PropertyToID("_RingConfigBuffer"); public static readonly int _Requests = Shader.PropertyToID("_Requests"); @@ -530,26 +565,28 @@ internal static class ShaderIDs public static readonly int _PunctualLights = Shader.PropertyToID("_PunctualLights"); public static readonly int _PatchAllocationRequests = Shader.PropertyToID("_PatchAllocationRequests"); public static readonly int _PatchAllocationRequestCount = Shader.PropertyToID("_PatchAllocationRequestCount"); - public static readonly int _Radius = Shader.PropertyToID("_Radius"); public static readonly int _InputPatchIrradiances = Shader.PropertyToID("_InputPatchIrradiances"); public static readonly int _OutputPatchIrradiances = Shader.PropertyToID("_OutputPatchIrradiances"); public static readonly int _InputOutputPatchIrradiances = Shader.PropertyToID("_InputOutputPatchIrradiances"); public static readonly int _PatchIrradiances = Shader.PropertyToID("_PatchIrradiances"); - public static readonly int _FrameIdx = Shader.PropertyToID("_FrameIdx"); - public static readonly int _FrameIndex = Shader.PropertyToID("_FrameIndex"); public static readonly int _VolumeCascadeOffsets = Shader.PropertyToID("_VolumeCascadeOffsets"); public static readonly int _PatchIrradiances0 = Shader.PropertyToID("_PatchIrradiances0"); public static readonly int _PatchIrradiances1 = Shader.PropertyToID("_PatchIrradiances1"); public static readonly int _PatchStatistics = Shader.PropertyToID("_PatchStatistics"); - public static readonly int _RingConfigReadOffset = Shader.PropertyToID("_RingConfigReadOffset"); - public static readonly int _RingConfigWriteOffset = Shader.PropertyToID("_RingConfigWriteOffset"); - public static readonly int _PatchOffset = Shader.PropertyToID("_PatchOffset"); public static readonly int _PatchGeometries = Shader.PropertyToID("_PatchGeometries"); public static readonly int _PunctualLightSamples = Shader.PropertyToID("_PunctualLightSamples"); public static readonly int _EmissiveTriangles = Shader.PropertyToID("_EmissiveTriangles"); public static readonly int _EmissiveTriangleCount = Shader.PropertyToID("_EmissiveTriangleCount"); public static readonly int _Samples = Shader.PropertyToID("_Samples"); - public static readonly int _RingConfigOffset = Shader.PropertyToID("_RingConfigOffset"); + public static readonly int SurfaceCachePatchAllocationConstants = Shader.PropertyToID("SurfaceCachePatchAllocationConstants"); + public static readonly int SurfaceCacheGlobalProbeConstants = Shader.PropertyToID("SurfaceCacheGlobalProbeConstants"); + public static readonly int SurfaceCachePunctualLightSamplingConstants = Shader.PropertyToID("SurfaceCachePunctualLightSamplingConstants"); + public static readonly int SurfaceCacheEstimationConstants = Shader.PropertyToID("SurfaceCacheEstimationConstants"); + public static readonly int SurfaceCacheDefragConstants = Shader.PropertyToID("SurfaceCacheDefragConstants"); + public static readonly int SurfaceCacheSpatialFilteringConstants = Shader.PropertyToID("SurfaceCacheSpatialFilteringConstants"); + public static readonly int SurfaceCacheTemporalFilteringConstants = Shader.PropertyToID("SurfaceCacheTemporalFilteringConstants"); + public static readonly int SurfaceCacheScrollingConstants = Shader.PropertyToID("SurfaceCacheScrollingConstants"); + public static readonly int SurfaceCacheEvictionConstants = Shader.PropertyToID("SurfaceCacheEvictionConstants"); } public SurfaceCache( @@ -655,6 +692,7 @@ private void RecordDefragmentation(RenderGraph renderGraph, uint frameIdx) passData.IterationOffset = _defragOffset; passData.IterationCount = _defragCount; passData.Shader = _resources.DefragShader; + passData.Constants = _constantBuffers.Defrag; passData.Keyword = _resources.DefragKeyword; passData.KernelIndex = _resources.DefragKernel; passData.PatchCapacity = Patches.Capacity; @@ -684,6 +722,7 @@ private void RecordEviction(RenderGraph renderGraph, uint frameIdx) using (var builder = renderGraph.AddComputePass("Surface Cache Eviction", out EvictionPassData passData)) { passData.Shader = _resources.EvictionShader; + passData.Constants = _constantBuffers.Eviction; passData.KernelIndex = _resources.EvictionKernel; passData.ThreadGroupSize = _resources.EvictionKernelGroupSize; passData.RingConfigBuffer = RingConfig.Buffer; @@ -714,6 +753,7 @@ private uint RecordFiltering(RenderGraph renderGraph, uint frameIdx) passData.PatchGeometries = Patches.Geometries; passData.RingConfigBuffer = RingConfig.Buffer; passData.Shader = _resources.SpatialFilteringShader; + passData.Constants = _constantBuffers.SpatialFiltering; passData.KernelIndex = _resources.SpatialFilteringKernel; passData.ThreadGroupSize = _resources.SpatialFilteringKernelGroupSize; passData.PatchCapacity = Patches.Capacity; @@ -739,6 +779,7 @@ private uint RecordFiltering(RenderGraph renderGraph, uint frameIdx) using (var builder = renderGraph.AddComputePass("Surface Cache Temporal Filter", out TemporalFilterPassData passData)) { passData.Shader = _resources.TemporalFilteringShader; + passData.Constants = _constantBuffers.TemporalFiltering; passData.KernelIndex = _resources.TemporalFilteringKernel; passData.ThreadGroupSize = _resources.TemporalFilteringKernelGroupSize; passData.InputPatchIrradiances = Patches.Irradiances[outputIrradianceBufferIdx]; @@ -766,11 +807,15 @@ private void RecordEstimation(RenderGraph renderGraph, uint frameIdx, SurfaceCac { passData.PatchCapacity = Patches.Capacity; passData.EstimationShader = _resources.EstimationShader; + passData.EstimationConstants = _constantBuffers.Estimation; passData.EstimationKernelIndex = _resources.EstimationKernel; passData.EstimationKernelGroupSize = _resources.EstimationKernelGroupSize; + passData.EstimationTransparencyModeKeyword = _estimationParams.AlphaCutouts ? _resources.EstimationCutoutsKeyword : _resources.EstimationOpaquesOnlyKeyword; passData.PunctualLightSamplingShader = _resources.PunctualLightSamplingShader; + passData.PunctualLightSamplingConstants = _constantBuffers.PunctualLightSampling; passData.PunctualLightSamplingKernelIndex = _resources.PunctualLightSamplingKernel; passData.PunctualLightSamplingKernelGroupSize = _resources.PunctualLightSamplingKernelGroupSize; + passData.PunctualLightSamplingTransparencyModeKeyword = _estimationParams.AlphaCutouts ? _resources.PunctualLightSamplingCutoutsKeyword : _resources.PunctualLightSamplingOpaquesOnlyKeyword; passData.PatchAllocationRequestCount = _patchAllocationRequests.Count; passData.PatchAllocationRequests = _patchAllocationRequests.Requests; passData.RingConfigBuffer = RingConfig.Buffer; @@ -792,6 +837,7 @@ private void RecordEstimation(RenderGraph renderGraph, uint frameIdx, SurfaceCac passData.MultiBounce = _estimationParams.MultiBounce; passData.BouncePatchAllocation = _estimationParams.BouncePatchAllocation; passData.GlobalProbeShader = _resources.GlobalProbeShader; + passData.GlobalProbeConstants = _constantBuffers.GlobalProbe; passData.GlobalProbeKernelIndex = _resources.GlobalProbeKernel; int newEnvCubemapHash = world.GetEnvironmentCubemapHash(); bool updateGlobalProbe = _estimationParams.DistanceFallback && (_globalProbeCubemapHash != newEnvCubemapHash || _globalProbeEnvIntensity != world.GetEnvironmentIntensityMultiplier()); @@ -808,6 +854,7 @@ private void RecordEstimation(RenderGraph renderGraph, uint frameIdx, SurfaceCac passData.WarmUpSampleMultiplier = _estimationParams.WarmUpSampleMultiplier; passData.PunctualLightCandidateCount = _estimationParams.PunctualLightCandidateCount; passData.VolumeVoxelMinSize = Volume.VoxelMinSize; + passData.RayTracingNormalBias = _estimationParams.RayTracingNormalBias; passData.PatchWarpingEnabled = Volume.PatchWarpingEnabled; passData.Zero = _zero; @@ -824,6 +871,7 @@ private void RecordPatchAllocation(RenderGraph renderGraph, uint frameIdx) using (var builder = renderGraph.AddComputePass("Surface Cache Patch Allocation", out PatchAllocationPassData passData)) { passData.Shader = _resources.PatchAllocationShader; + passData.Constants = _constantBuffers.PatchAllocation; passData.KernelIndex = _resources.PatchAllocationKernel; passData.ThreadGroupSize = _resources.PatchAllocationKernelGroupSize; passData.Requests = _patchAllocationRequests.Requests; @@ -873,6 +921,7 @@ private void RecordScrolling(RenderGraph renderGraph) using (var builder = renderGraph.AddComputePass("Surface Cache Scrolling", out ScrollingPassData passData)) { passData.Shader = _resources.ScrollingShader; + passData.Constants = _constantBuffers.Scrolling; passData.KernelIndex = _resources.ScrollingKernel; passData.ThreadGroupSize = _resources.ScrollingKernelGroupSize; passData.CellAllocationMarks = Volume.CellAllocationMarks; @@ -907,13 +956,18 @@ static void AllocatePatches(PatchAllocationPassData passData, ComputeGraphContex cmd.SetComputeBufferParam(shader, kernelIndex, ShaderIDs._CellAllocationMarks, passData.CellAllocationMarks); cmd.SetComputeBufferParam(shader, kernelIndex, ShaderIDs._RingConfigBuffer, passData.RingConfigBuffer); cmd.SetComputeBufferParam(shader, kernelIndex, ShaderIDs._VolumeCascadeOffsets, passData.VolumeCascadeOffsets); - cmd.SetComputeIntParam(shader, ShaderIDs._RingConfigOffset, (int)passData.RingConfigOffset); - cmd.SetComputeIntParam(shader, ShaderIDs._VolumeSpatialResolution, (int)passData.VolumeSpatialResolution); - cmd.SetComputeIntParam(shader, ShaderIDs._VolumeCascadeCount, (int)passData.CascadeCount); - cmd.SetComputeFloatParam(shader, ShaderIDs._VolumeVoxelMinSize, passData.VolumeVoxelMinSize); - cmd.SetComputeIntParam(shader, ShaderIDs._PatchWarping, passData.PatchWarpingEnabled ? 1 : 0); - cmd.SetComputeVectorParam(shader, ShaderIDs._VolumeTargetPos, passData.VolumeTargetPos); - cmd.SetComputeIntParam(shader, ShaderIDs._FrameIndex, (int)passData.FrameIndex); + var constants = new SurfaceCachePatchAllocationConstants + { + _VolumeTargetPos = passData.VolumeTargetPos, + _VolumeVoxelMinSize = passData.VolumeVoxelMinSize, + _RingConfigOffset = passData.RingConfigOffset, + _VolumeSpatialResolution = passData.VolumeSpatialResolution, + _VolumeCascadeCount = passData.CascadeCount, + _PatchWarping = passData.PatchWarpingEnabled ? 1 : 0, + _FrameIndex = passData.FrameIndex, + }; + passData.Constants.UpdateData(cmd, constants); + passData.Constants.Set(cmd, shader, ShaderIDs.SurfaceCachePatchAllocationConstants); uint3 groupCount = DivUp(new uint3(SurfaceCachePatchAllocationRequestList.RequestMax, 1, 1), passData.ThreadGroupSize); cmd.DispatchCompute(shader, kernelIndex, (int)groupCount.x, (int)groupCount.y, 1); @@ -931,7 +985,9 @@ static void Estimate(EstimationPassData data, UnsafeGraphContext graphCtx) { cmd.SetComputeBufferParam(data.GlobalProbeShader, data.GlobalProbeKernelIndex, ShaderIDs._GlobalProbe, data.GlobalProbeBuffer); cmd.SetComputeTextureParam(data.GlobalProbeShader, data.GlobalProbeKernelIndex, ShaderIDs._EnvironmentCubemap, data.World.GetEnvironmentCubemap()); - cmd.SetComputeFloatParam(data.GlobalProbeShader, ShaderIDs._EnvironmentIntensityMultiplier, data.EnvironmentIntensityMultiplier); + var constants = new SurfaceCacheGlobalProbeConstants { _EnvironmentIntensityMultiplier = data.EnvironmentIntensityMultiplier }; + data.GlobalProbeConstants.UpdateData(cmd, constants); + data.GlobalProbeConstants.Set(cmd, data.GlobalProbeShader, ShaderIDs.SurfaceCacheGlobalProbeConstants); cmd.DispatchCompute(data.GlobalProbeShader, data.GlobalProbeKernelIndex, (int)(SurfaceCacheVolume.AngularResolution * SurfaceCacheVolume.AngularResolution), 1, 1); } @@ -944,20 +1000,27 @@ static void Estimate(EstimationPassData data, UnsafeGraphContext graphCtx) { var shader = data.PunctualLightSamplingShader; var kernelIdx = data.PunctualLightSamplingKernelIndex; + var constants = new SurfaceCachePunctualLightSamplingConstants + { + _MaterialAtlasTexelSize = GetMaterialAtlasTexelSize(data.World.GetMaterialAlbedoTextures()), + _AlbedoBoost = data.AlbedoBoost, + _FrameIdx = data.FrameIdx, + _PunctualLightCount = (uint)punctualLightCount, + _SamplesPerPunctualLight = SamplesPerPunctualLight, + }; + data.PunctualLightSamplingConstants.UpdateData(cmd, constants); + data.PunctualLightSamplingConstants.Set(cmd, shader, ShaderIDs.SurfaceCachePunctualLightSamplingConstants); + cmd.EnableKeyword(shader, data.PunctualLightSamplingTransparencyModeKeyword); cmd.SetComputeBufferParam(shader, kernelIdx, ShaderIDs._PunctualLights, punctualLightBuffer); - cmd.SetComputeIntParam(shader, ShaderIDs._PunctualLightCount, punctualLightCount); - cmd.SetComputeIntParam(shader, ShaderIDs._SamplesPerPunctualLight, (int)SamplesPerPunctualLight); - cmd.SetComputeFloatParam(shader, ShaderIDs._FrameIdx, data.FrameIdx); cmd.SetComputeBufferParam(shader, kernelIdx, ShaderIDs._Samples, data.PunctualLightSamples); cmd.SetComputeBufferParam(shader, kernelIdx, ShaderIDs._MaterialEntries, data.World.GetMaterialListBuffer()); cmd.SetComputeTextureParam(shader, kernelIdx, ShaderIDs._AlbedoTextures, data.World.GetMaterialAlbedoTextures()); - cmd.SetComputeFloatParam(shader, ShaderIDs._AlbedoBoost, data.AlbedoBoost); - cmd.SetComputeFloatParam(shader, ShaderIDs._MaterialAtlasTexelSize, GetMaterialAtlasTexelSize(data.World.GetMaterialAlbedoTextures())); InlineRayTracing.SetAccelerationStructure(cmd, shader, kernelIdx, "_RayTracingAccelerationStructure", data.World.GetAccelerationStructure().GetAccelerationStructure()); data.World.GetAccelerationStructure().Instances.Bind(cmd, shader, kernelIdx); InlineRayTracing.SetTraceScratchBuffer(cmd, shader, kernelIdx, data.TraceScratchBuffer); uint groupCount = DivUp(data.PunctualLightSampleCount, data.PunctualLightSamplingKernelGroupSize); cmd.DispatchCompute(shader, data.PunctualLightSamplingKernelIndex, (int)groupCount, 1, 1); + cmd.DisableKeyword(shader, data.PunctualLightSamplingTransparencyModeKeyword); } { @@ -965,6 +1028,7 @@ static void Estimate(EstimationPassData data, UnsafeGraphContext graphCtx) var kernelIdx = data.EstimationKernelIndex; var (dirLightDirection, dirLightIntensity) = GetDirectionalLightUniforms(data.World.GetDirectionalLight()); + cmd.EnableKeyword(shader, data.EstimationTransparencyModeKeyword); cmd.SetComputeBufferParam(shader, kernelIdx, ShaderIDs._PunctualLights, punctualLightBuffer); cmd.SetComputeBufferParam(shader, kernelIdx, ShaderIDs._PatchAllocationRequestCount, data.PatchAllocationRequestCount); cmd.SetComputeBufferParam(shader, kernelIdx, ShaderIDs._PatchAllocationRequests, data.PatchAllocationRequests); @@ -976,37 +1040,44 @@ static void Estimate(EstimationPassData data, UnsafeGraphContext graphCtx) cmd.SetComputeBufferParam(shader, kernelIdx, ShaderIDs._PatchGeometries, data.PatchGeometries); cmd.SetComputeBufferParam(shader, kernelIdx, ShaderIDs._PatchStatistics, data.PatchStatistics); cmd.SetComputeBufferParam(shader, kernelIdx, ShaderIDs._VolumeCascadeOffsets, data.VolumeCascadeOffsets); - cmd.SetComputeIntParam(shader, ShaderIDs._FrameIdx, (int)data.FrameIdx); - cmd.SetComputeIntParam(shader, ShaderIDs._VolumeSpatialResolution, (int)data.VolumeSpatialResolution); - cmd.SetComputeIntParam(shader, ShaderIDs._VolumeCascadeCount, (int)data.CascadeCount); - cmd.SetComputeIntParam(shader, ShaderIDs._SampleCount, (int)data.SampleCount); - cmd.SetComputeIntParam(shader, ShaderIDs._WarmUpSampleMultiplier, (int)data.WarmUpSampleMultiplier); - cmd.SetComputeIntParam(shader, ShaderIDs._PunctualLightCandidateCount, (int)data.PunctualLightCandidateCount); - cmd.SetComputeIntParam(shader, ShaderIDs._MultiBounce, data.MultiBounce ? 1 : 0); - cmd.SetComputeIntParam(shader, ShaderIDs._PatchWarping, data.PatchWarpingEnabled ? 1 : 0); - cmd.SetComputeFloatParam(shader, ShaderIDs._VolumeVoxelMinSize, data.VolumeVoxelMinSize); - cmd.SetComputeFloatParam(shader, ShaderIDs._PunctualLightSampleCount, data.PunctualLightSampleCount); - cmd.SetComputeFloatParam(shader, ShaderIDs._ShortHysteresis, data.ShortHysteresis); - cmd.SetComputeIntParam(shader, ShaderIDs._RingConfigOffset, (int)data.RingConfigOffset); cmd.SetComputeBufferParam(shader, kernelIdx, ShaderIDs._CellPatchIndices, data.CellPatchIndices); - cmd.SetComputeVectorParam(shader, ShaderIDs._VolumeTargetPos, data.VolumeTargetPos); cmd.SetComputeTextureParam(shader, kernelIdx, ShaderIDs._EnvironmentCubemap, data.World.GetEnvironmentCubemap()); cmd.SetComputeBufferParam(shader, kernelIdx, ShaderIDs._MaterialEntries, data.World.GetMaterialListBuffer()); cmd.SetComputeTextureParam(shader, kernelIdx, ShaderIDs._AlbedoTextures, data.World.GetMaterialAlbedoTextures()); cmd.SetComputeTextureParam(shader, kernelIdx, ShaderIDs._EmissionTextures, data.World.GetMaterialEmissionTextures()); - cmd.SetComputeFloatParam(shader, ShaderIDs._AlbedoBoost, data.AlbedoBoost); - cmd.SetComputeFloatParam(shader, ShaderIDs._EnvironmentIntensityMultiplier, data.EnvironmentIntensityMultiplier); - cmd.SetComputeFloatParam(shader, ShaderIDs._EmissiveTriangleIntensityMultiplier, data.EmissiveTriangleIntensityMultiplier); - cmd.SetComputeFloatParam(shader, ShaderIDs._MaterialAtlasTexelSize, GetMaterialAtlasTexelSize(data.World.GetMaterialAlbedoTextures())); - cmd.SetComputeIntParam(shader, ShaderIDs._PunctualLightCount, punctualLightCount); - cmd.SetComputeIntParam(shader, ShaderIDs._BouncePatchAllocation, data.BouncePatchAllocation ? 1 : 0); - cmd.SetComputeVectorParam(shader, ShaderIDs._DirectionalLightDirection, dirLightDirection); - cmd.SetComputeVectorParam(shader, ShaderIDs._DirectionalLightIntensity, dirLightIntensity); + var constants = new SurfaceCacheEstimationConstants + { + _VolumeTargetPos = data.VolumeTargetPos, + _VolumeVoxelMinSize = data.VolumeVoxelMinSize, + _RayTracingNormalBias = data.RayTracingNormalBias, + _DirectionalLightDirection = dirLightDirection, + _ShortHysteresis = data.ShortHysteresis, + _DirectionalLightIntensity = dirLightIntensity, + _MaterialAtlasTexelSize = GetMaterialAtlasTexelSize(data.World.GetMaterialAlbedoTextures()), + _PunctualLightCount = (uint)punctualLightCount, + _FrameIdx = data.FrameIdx, + _VolumeSpatialResolution = data.VolumeSpatialResolution, + _VolumeCascadeCount = data.CascadeCount, + _MultiBounce = data.MultiBounce ? 1u : 0u, + _SampleCount = data.SampleCount, + _WarmUpSampleMultiplier = data.WarmUpSampleMultiplier, + _PunctualLightCandidateCount = data.PunctualLightCandidateCount, + _RingConfigOffset = data.RingConfigOffset, + _PatchWarping = data.PatchWarpingEnabled ? 1 : 0, + _AlbedoBoost = data.AlbedoBoost, + _EnvironmentIntensityMultiplier = data.EnvironmentIntensityMultiplier, + _EmissiveTriangleIntensityMultiplier = data.EmissiveTriangleIntensityMultiplier, + _PunctualLightSampleCount = data.PunctualLightSampleCount, + _BouncePatchAllocation = data.BouncePatchAllocation ? 1u : 0u, + }; + data.EstimationConstants.UpdateData(cmd, constants); + data.EstimationConstants.Set(cmd, shader, ShaderIDs.SurfaceCacheEstimationConstants); InlineRayTracing.SetAccelerationStructure(cmd, shader, kernelIdx, "_RayTracingAccelerationStructure", data.World.GetAccelerationStructure().GetAccelerationStructure()); data.World.GetAccelerationStructure().Instances.Bind(cmd, shader, kernelIdx); InlineRayTracing.SetTraceScratchBuffer(cmd, shader, kernelIdx, data.TraceScratchBuffer); uint groupCount = DivUp(data.PatchCapacity, data.EstimationKernelGroupSize); cmd.DispatchCompute(shader, data.EstimationKernelIndex, (int)groupCount, 1, 1); + cmd.DisableKeyword(shader, data.EstimationTransparencyModeKeyword); } } @@ -1041,9 +1112,14 @@ static void Defrag(DefragPassData data, ComputeGraphContext cgContext) uint writeOffset = SurfaceCacheRingConfig.GetOffsetB(flipflop); uint patchOffset = iterationIndex % 2 * (data.ComputeSubGroupSize / 2); - cmd.SetComputeIntParam(shader, ShaderIDs._RingConfigReadOffset, (int)readOffset); - cmd.SetComputeIntParam(shader, ShaderIDs._RingConfigWriteOffset, (int)writeOffset); - cmd.SetComputeIntParam(shader, ShaderIDs._PatchOffset, (int)patchOffset); + var constants = new SurfaceCacheDefragConstants + { + _RingConfigReadOffset = readOffset, + _RingConfigWriteOffset = writeOffset, + _PatchOffset = patchOffset, + }; + data.Constants.UpdateData(cmd, constants); + data.Constants.Set(cmd, shader, ShaderIDs.SurfaceCacheDefragConstants); uint3 groupCount = DivUp(new uint3(data.PatchCapacity, 1, 1), data.ThreadGroupSize); cmd.DispatchCompute(shader, kernelIndex, (int)groupCount.x, (int)groupCount.y, (int)groupCount.z); @@ -1065,15 +1141,20 @@ static void FilterSpatially(SpatialFilterPassData data, ComputeGraphContext cgCo cmd.SetComputeBufferParam(shader, kernelIndex, ShaderIDs._PatchGeometries, data.PatchGeometries); cmd.SetComputeBufferParam(shader, kernelIndex, ShaderIDs._CellPatchIndices, data.CellPatchIndices); cmd.SetComputeBufferParam(shader, kernelIndex, ShaderIDs._VolumeCascadeOffsets, data.VolumeCascadeOffsets); - cmd.SetComputeIntParam(shader, ShaderIDs._FrameIdx, (int)data.FrameIdx); - cmd.SetComputeIntParam(shader, ShaderIDs._VolumeCascadeCount, (int)data.CascadeCount); - cmd.SetComputeIntParam(shader, ShaderIDs._VolumeSpatialResolution, (int)data.VolumeSpatialResolution); - cmd.SetComputeFloatParam(shader, ShaderIDs._VolumeVoxelMinSize, data.VolumeVoxelMinSize); - cmd.SetComputeIntParam(shader, ShaderIDs._PatchWarping, data.PatchWarpingEnabled ? 1 : 0); - cmd.SetComputeIntParam(shader, ShaderIDs._SampleCount, (int)data.SampleCount); - cmd.SetComputeFloatParam(shader, ShaderIDs._Radius, data.Radius); - cmd.SetComputeIntParam(shader, ShaderIDs._RingConfigOffset, (int)data.RingConfigOffset); - cmd.SetComputeVectorParam(shader, ShaderIDs._VolumeTargetPos, data.VolumeTargetPos); + var constants = new SurfaceCacheSpatialFilteringConstants + { + _VolumeTargetPos = data.VolumeTargetPos, + _VolumeVoxelMinSize = data.VolumeVoxelMinSize, + _FrameIdx = data.FrameIdx, + _VolumeCascadeCount = data.CascadeCount, + _VolumeSpatialResolution = data.VolumeSpatialResolution, + _SampleCount = data.SampleCount, + _RingConfigOffset = data.RingConfigOffset, + _Radius = data.Radius, + _PatchWarping = data.PatchWarpingEnabled ? 1 : 0, + }; + data.Constants.UpdateData(cmd, constants); + data.Constants.Set(cmd, shader, ShaderIDs.SurfaceCacheSpatialFilteringConstants); uint3 groupCount = DivUp(new uint3(data.PatchCapacity, 1, 1), data.ThreadGroupSize); cmd.DispatchCompute(shader, kernelIndex, (int)groupCount.x, (int)groupCount.y, 1); @@ -1088,8 +1169,13 @@ static void FilterTemporally(TemporalFilterPassData data, ComputeGraphContext cg cmd.SetComputeBufferParam(shader, kernelIndex, ShaderIDs._PatchStatistics, data.PatchStatistics); cmd.SetComputeBufferParam(shader, kernelIndex, ShaderIDs._InputPatchIrradiances, data.InputPatchIrradiances); cmd.SetComputeBufferParam(shader, kernelIndex, ShaderIDs._InputOutputPatchIrradiances, data.InputOutputPatchIrradiances); - cmd.SetComputeIntParam(shader, ShaderIDs._RingConfigOffset, (int)data.RingConfigOffset); - cmd.SetComputeFloatParam(shader, ShaderIDs._TemporalSmoothing, data.TemporalSmoothing); + var constants = new SurfaceCacheTemporalFilteringConstants + { + _RingConfigOffset = data.RingConfigOffset, + _TemporalSmoothing = data.TemporalSmoothing, + }; + data.Constants.UpdateData(cmd, constants); + data.Constants.Set(cmd, shader, ShaderIDs.SurfaceCacheTemporalFilteringConstants); uint3 groupCount = DivUp(new uint3(data.PatchCapacity, 1, 1), data.ThreadGroupSize); cmd.DispatchCompute(shader, kernelIndex, (int)groupCount.x, (int)groupCount.y, 1); @@ -1104,6 +1190,8 @@ public void Dispose() _punctualLightSamples.Dispose(); _traceScratch?.Dispose(); _patchAllocationRequests.Dispose(); + + _constantBuffers.Dispose(); } private static uint3 DivUp(uint3 x, uint3 y) => (x + y - 1) / y; @@ -1120,20 +1208,23 @@ static void Scroll(ScrollingPassData data, ComputeGraphContext cgContext) cmd.SetComputeBufferParam(data.Shader, data.KernelIndex, ShaderIDs._CellPatchIndices, data.CellPatchIndices); cmd.SetComputeBufferParam(data.Shader, data.KernelIndex, ShaderIDs._NewVolumeCascadeOffsets, data.NewVolumeCascadeOffsetsDevice); cmd.SetComputeBufferParam(data.Shader, data.KernelIndex, ShaderIDs._PatchCellIndices, data.PatchCellIndices); - cmd.SetComputeIntParam(data.Shader, ShaderIDs._VolumeSpatialResolution, (int)data.VolumeSpatialResolution); - cmd.SetComputeIntParam(data.Shader, ShaderIDs._VolumeCascadeCount, (int)data.VolumeCascadeCount); + var constants = new SurfaceCacheScrollingConstants + { + _VolumeSpatialResolution = data.VolumeSpatialResolution, + _VolumeCascadeCount = data.VolumeCascadeCount, + }; + unsafe { - var oldCascadeOffsetsInts = new int[data.OldVolumeCascadeOffsetsHost.Length * 4]; for (uint cascadeIdx = 0; cascadeIdx < cascadeCount; ++cascadeIdx) { - oldCascadeOffsetsInts[cascadeIdx * 4] = data.OldVolumeCascadeOffsetsHost[cascadeIdx][0]; - oldCascadeOffsetsInts[cascadeIdx * 4 + 1] = data.OldVolumeCascadeOffsetsHost[cascadeIdx][1]; - oldCascadeOffsetsInts[cascadeIdx * 4 + 2] = data.OldVolumeCascadeOffsetsHost[cascadeIdx][2]; - oldCascadeOffsetsInts[cascadeIdx * 4 + 3] = 0; + constants._OldVolumeCascadeOffsets[cascadeIdx * 4] = (uint)data.OldVolumeCascadeOffsetsHost[cascadeIdx].x; + constants._OldVolumeCascadeOffsets[cascadeIdx * 4 + 1] = (uint)data.OldVolumeCascadeOffsetsHost[cascadeIdx].y; + constants._OldVolumeCascadeOffsets[cascadeIdx * 4 + 2] = (uint)data.OldVolumeCascadeOffsetsHost[cascadeIdx].z; } - cmd.SetComputeIntParams(data.Shader, ShaderIDs._OldVolumeCascadeOffsets, oldCascadeOffsetsInts); } + data.Constants.UpdateData(cmd, constants); + data.Constants.Set(cmd, data.Shader, ShaderIDs.SurfaceCacheScrollingConstants); uint3 groupCount = DivUp(new uint3(data.VolumeSpatialResolution, data.VolumeSpatialResolution, data.VolumeSpatialResolution * data.VolumeCascadeCount), data.ThreadGroupSize); cmd.DispatchCompute(data.Shader, data.KernelIndex, (int)groupCount.x, (int)groupCount.y, (int)groupCount.z); @@ -1149,9 +1240,14 @@ static void Evict(EvictionPassData passData, ComputeGraphContext cgContext) cmd.SetComputeBufferParam(shader, kernelIndex, ShaderIDs._PatchCellIndices, passData.PatchCellIndices); cmd.SetComputeBufferParam(shader, kernelIndex, ShaderIDs._CellAllocationMarks, passData.CellAllocationMarks); cmd.SetComputeBufferParam(shader, kernelIndex, ShaderIDs._CellPatchIndices, passData.CellPatchIndices); - cmd.SetComputeIntParam(shader, ShaderIDs._FrameIdx, (int)passData.FrameIdx); - cmd.SetComputeIntParam(shader, ShaderIDs._RingConfigOffset, (int)passData.RingConfigOffset); - cmd.SetComputeIntParam(shader, ShaderIDs._BouncePatchAllocation, passData.BouncePatchAllocation ? 1 : 0); + var constants = new SurfaceCacheEvictionConstants + { + _RingConfigOffset = passData.RingConfigOffset, + _FrameIdx = passData.FrameIdx, + _BouncePatchAllocation = passData.BouncePatchAllocation ? 1u : 0u, + }; + passData.Constants.UpdateData(cmd, constants); + passData.Constants.Set(cmd, shader, ShaderIDs.SurfaceCacheEvictionConstants); uint3 groupCount = DivUp(new uint3(passData.PatchCapacity, 1, 1), passData.ThreadGroupSize); cmd.DispatchCompute(shader, kernelIndex, (int)groupCount.x, (int)groupCount.y, 1); diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/SurfaceCacheWorld.cs b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/SurfaceCacheWorld.cs index 2915d6525d0..0875c8e5b27 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/SurfaceCacheWorld.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/SurfaceCacheWorld.cs @@ -305,14 +305,13 @@ static class ShaderIDs { public static readonly int _EmissiveTriangles = Shader.PropertyToID("_EmissiveTriangles"); public static readonly int _EmissiveTriangleCounter = Shader.PropertyToID("_EmissiveTriangleCounter"); - public static readonly int _SubmeshInstanceId = Shader.PropertyToID("_SubmeshInstanceId"); - public static readonly int _SubmeshTriangleCount = Shader.PropertyToID("_SubmeshTriangleCount"); public static readonly int _SrcTriangles = Shader.PropertyToID("_SrcTriangles"); public static readonly int _SrcTriangleCount = Shader.PropertyToID("_SrcTriangleCount"); public static readonly int _DstTriangles = Shader.PropertyToID("_DstTriangles"); public static readonly int _DstTriangleCount = Shader.PropertyToID("_DstTriangleCount"); public static readonly int _RemovedInstanceIds = Shader.PropertyToID("_RemovedInstanceIds"); - public static readonly int _RemovedInstanceIdCount = Shader.PropertyToID("_RemovedInstanceIdCount"); + public static readonly int SurfaceCacheEmissiveTriangleAdditionConstants = Shader.PropertyToID("SurfaceCacheEmissiveTriangleAdditionConstants"); + public static readonly int SurfaceCacheEmissiveTriangleRemovalConstants = Shader.PropertyToID("SurfaceCacheEmissiveTriangleRemovalConstants"); } // Dependencies @@ -338,6 +337,9 @@ static class ShaderIDs // Temporary buffer used during removal of triangles GraphicsBuffer _removedInstanceIds; + readonly ConstantBuffer _additionConstants = new(); + readonly ConstantBuffer _removalConstants = new(); + public EmissiveTriangleList(ComputeShader additionShader, ComputeShader removalShader) { _additionShader = additionShader; @@ -441,7 +443,9 @@ void RemoveInstancesAndResizeList(CommandBuffer cmd, int targetCapacity) cmd.SetComputeBufferParam(_removalShader, _removeKernel, ShaderIDs._DstTriangles, _emissiveTrianglesScratch); cmd.SetComputeBufferParam(_removalShader, _removeKernel, ShaderIDs._DstTriangleCount, _emissiveTriangleCounterScratch); cmd.SetComputeBufferParam(_removalShader, _removeKernel, ShaderIDs._RemovedInstanceIds, _removedInstanceIds); - cmd.SetComputeIntParam(_removalShader, ShaderIDs._RemovedInstanceIdCount, removedCount); + var constants = new SurfaceCacheEmissiveTriangleRemovalConstants { _RemovedInstanceIdCount = (uint)removedCount }; + _removalConstants.UpdateData(cmd, constants); + _removalConstants.Set(cmd, _removalShader, ShaderIDs.SurfaceCacheEmissiveTriangleRemovalConstants); cmd.DispatchCompute(_removalShader, _removeKernel, GraphicsHelpers.DivUp(_emissiveTriangles.count, _removeGroupSize), 1, 1); // Swap scratch and active buffers @@ -459,8 +463,13 @@ void AddInstances(CommandBuffer cmd) foreach (int instanceID in _pendingAdds) { int triangleCount = _submeshInstanceTriangleCounts[instanceID]; - cmd.SetComputeIntParam(_additionShader, ShaderIDs._SubmeshInstanceId, instanceID); - cmd.SetComputeIntParam(_additionShader, ShaderIDs._SubmeshTriangleCount, triangleCount); + var constants = new SurfaceCacheEmissiveTriangleAdditionConstants + { + _SubmeshInstanceId = (uint)instanceID, + _SubmeshTriangleCount = (uint)triangleCount, + }; + _additionConstants.UpdateData(cmd, constants); + _additionConstants.Set(cmd, _additionShader, ShaderIDs.SurfaceCacheEmissiveTriangleAdditionConstants); cmd.DispatchCompute(_additionShader, _addKernel, GraphicsHelpers.DivUp(triangleCount, _addGroupSize), 1, 1); } } @@ -476,6 +485,8 @@ public void Dispose() _emissiveTriangleCounter?.Dispose(); _emissiveTriangleCounterScratch?.Dispose(); _removedInstanceIds?.Dispose(); + _additionConstants.Release(); + _removalConstants.Release(); } } @@ -510,12 +521,12 @@ private class MaterialInfo public void Init(RayTracingContext ctx, WorldResourceSet worldResources, ComputeShader emissiveTriangleAdditionShader, ComputeShader emissiveTriangleRemovalShader) { - Init(ctx, worldResources, emissiveTriangleAdditionShader, emissiveTriangleRemovalShader, GeometryPoolDesc.NewDefault()); + Init(ctx, worldResources, emissiveTriangleAdditionShader, emissiveTriangleRemovalShader, GeometryPoolDesc.NewDefault(), SystemInfo.maxTextureArraySlices); } - internal void Init(RayTracingContext ctx, WorldResourceSet worldResources, ComputeShader emissiveTriangleAdditionShader, ComputeShader emissiveTriangleRemovalShader, in GeometryPoolDesc geometryPoolDesc) + internal void Init(RayTracingContext ctx, WorldResourceSet worldResources, ComputeShader emissiveTriangleAdditionShader, ComputeShader emissiveTriangleRemovalShader, in GeometryPoolDesc geometryPoolDesc, int materialAtlasMaxSliceCount) { - _materialPool = new MaterialPool(worldResources.SetAlphaChannelShader, worldResources.BlitCubemap, worldResources.BlitGrayScaleCookie); + _materialPool = new MaterialPool(worldResources.SetAlphaChannelShader, worldResources.BlitCubemap, worldResources.BlitGrayScaleCookie, materialAtlasMaxSliceCount); var options = new AccelerationStructureOptions() { @@ -566,11 +577,29 @@ internal int GetMaterialCount() return _materialHandleSet.Count; } + internal void GetMaterialAtlasUsage(out AtlasUsage albedo, out AtlasUsage emission, out AtlasUsage transmission) + { + _materialPool.GetAtlasUsage(out albedo, out emission, out transmission); + } + internal int GetTrackedEmissiveTriangleCount() { return _emissiveTriangles.TrackedTriangleCount; } +#if UNITY_INCLUDE_TESTS + internal List ReadBackMaterialEmissionColors() + { + using (var cmd = new CommandBuffer()) + { + _materialPool.Build(cmd); + Graphics.ExecuteCommandBuffer(cmd); + } + + return _materialPool.ReadBackEmissionColors(); + } +#endif + public void SetEnvironmentMaterial(Material mat) { _cubemapRender.SetMaterial(mat); @@ -666,7 +695,11 @@ public void RemoveMaterial(MaterialHandle materialHandle) public MaterialHandle AddMaterial(in MaterialPool.MaterialDescriptor material, UVChannel albedoAndEmissionUVChannel) { MaterialHandle handle = _materialHandleSet.Add(); - _materialPool.AddMaterial(handle.Value, in material, albedoAndEmissionUVChannel); + if (!_materialPool.AddMaterial(handle.Value, in material, albedoAndEmissionUVChannel)) + { + _materialHandleSet.Remove(handle); + return MaterialHandle.Invalid; + } Debug.Assert(!_trackedMaterials.ContainsKey(handle), "Material handle is already tracked."); _trackedMaterials.Add(handle, new MaterialInfo @@ -677,9 +710,10 @@ public MaterialHandle AddMaterial(in MaterialPool.MaterialDescriptor material, U return handle; } - public void UpdateMaterial(MaterialHandle materialHandle, in MaterialPool.MaterialDescriptor material, UVChannel albedoAndEmissionUVChannel) + public bool UpdateMaterial(MaterialHandle materialHandle, in MaterialPool.MaterialDescriptor material, UVChannel albedoAndEmissionUVChannel) { - _materialPool.UpdateMaterial(materialHandle.Value, in material, albedoAndEmissionUVChannel); + if (!_materialPool.UpdateMaterial(materialHandle.Value, in material, albedoAndEmissionUVChannel)) + return false; // If a material goes from non-emissive to emissive or vice versa, // we need to update any instances referencing the material. @@ -699,6 +733,8 @@ public void UpdateMaterial(MaterialHandle materialHandle, in MaterialPool.Materi } _instancesToRetrack.Clear(); } + + return true; } void RetrackInstance(InstanceHandle instanceHandle) @@ -717,12 +753,15 @@ public InstanceHandle AddInstance( Mesh mesh, Span materials, Span masks, - in Matrix4x4 localToWorldMatrix) + in Matrix4x4 localToWorldMatrix, + int meshLod = 0) { Debug.Assert(mesh.vertexCount > 0); Debug.Assert(mesh.subMeshCount == materials.Length); Debug.Assert(mesh.subMeshCount == masks.Length); + Debug.Assert(meshLod >= 0 && meshLod < mesh.lodCount); + Span validMasks = stackalloc uint[mesh.subMeshCount]; Span materialIndices = stackalloc uint[mesh.subMeshCount]; Span isOpaque = stackalloc bool[mesh.subMeshCount]; for (int i = 0; i < materials.Length; ++i) @@ -730,6 +769,8 @@ public InstanceHandle AddInstance( if (materials[i] == MaterialHandle.Invalid) continue; + validMasks[i] = masks[i]; + bool isTransmissive = false; _materialPool.GetMaterialInfo(materials[i].Value, out materialIndices[i], out isTransmissive); isOpaque[i] = !isTransmissive; @@ -738,13 +779,13 @@ public InstanceHandle AddInstance( Span subMeshTriangleCounts = stackalloc int[mesh.subMeshCount]; for (int i = 0; i < subMeshTriangleCounts.Length; ++i) { - uint indexCount = mesh.GetIndexCount(i); + uint indexCount = mesh.GetIndexCount(i, meshLod); Debug.Assert(indexCount % 3 == 0, "Mesh should contain triangles."); subMeshTriangleCounts[i] = (int)(indexCount / 3); } InstanceHandle instance = _instanceHandleSet.Add(); - _rayTracingAccelerationStructure.AddInstance(instance.Value, mesh, localToWorldMatrix, masks, materialIndices, isOpaque, 0); + _rayTracingAccelerationStructure.AddInstance(instance.Value, mesh, localToWorldMatrix, validMasks, materialIndices, isOpaque, 0, meshLod); TrackInstance(instance, subMeshTriangleCounts, materials); return instance; } @@ -790,13 +831,19 @@ public void UpdateInstanceMaterials(InstanceHandle instance, Span materialIndices = stackalloc uint[materials.Length]; for (int i = 0; i < materials.Length; ++i) { + if (materials[i] == MaterialHandle.Invalid) + continue; + _materialPool.GetMaterialInfo(materials[i].Value, out materialIndices[i], out bool isTransmissive); } _rayTracingAccelerationStructure.UpdateInstanceMaterialIDs(instance.Value, materialIndices); - Debug.Assert(_trackedInstances.ContainsKey(instance), "Cannot update an instance that is not tracked."); - int[] trackedTriangleCounts = _trackedInstances[instance].SubMeshTriangleCounts; + // Terrain instances are not tracked. + if (!_trackedInstances.TryGetValue(instance, out var trackedInfo)) + return; + + int[] trackedTriangleCounts = trackedInfo.SubMeshTriangleCounts; Span copiedTriangleCounts = stackalloc int[trackedTriangleCounts.Length]; trackedTriangleCounts.CopyTo(copiedTriangleCounts); UntrackInstance(instance); @@ -817,8 +864,7 @@ void TrackInstance(InstanceHandle instanceHandle, ReadOnlySpan subMeshTrian int subMeshCount = Math.Min(subMeshTriangleCounts.Length, materialHandles.Length); for (int subMeshIdx = 0; subMeshIdx < subMeshCount; subMeshIdx++) { - Debug.Assert(materialHandles[subMeshIdx] != MaterialHandle.Invalid, "Material referenced by instance is invalid"); - if (!_materialPool.IsEmissive(materialHandles[subMeshIdx].Value, out _)) + if (materialHandles[subMeshIdx] == MaterialHandle.Invalid || !_materialPool.IsEmissive(materialHandles[subMeshIdx].Value, out _)) continue; info.SubMeshEmissiveMask[subMeshIdx] = true; @@ -828,6 +874,9 @@ void TrackInstance(InstanceHandle instanceHandle, ReadOnlySpan subMeshTrian foreach (var materialHandle in materialHandles) { + if (materialHandle == MaterialHandle.Invalid) + continue; + Debug.Assert(_trackedMaterials.ContainsKey(materialHandle), "Cannot reference an untracked material."); _trackedMaterials[materialHandle].Instances.Add(instanceHandle); } @@ -840,6 +889,9 @@ void UntrackInstance(InstanceHandle instanceHandle) foreach (var materialHandle in info.SubMeshMaterials) { + if (materialHandle == MaterialHandle.Invalid) + continue; + Debug.Assert(_trackedMaterials.ContainsKey(materialHandle), "Instance references a material that is not tracked."); _trackedMaterials[materialHandle].Instances.Remove(instanceHandle); } diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/TemporalFiltering.compute b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/TemporalFiltering.compute index a492b133cc1..7bad86621a7 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/TemporalFiltering.compute +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/TemporalFiltering.compute @@ -11,8 +11,7 @@ StructuredBuffer _InputPatchIrradiances; RWStructuredBuffer _PatchStatistics; RWStructuredBuffer _InputOutputPatchIrradiances; -uint _RingConfigOffset; -float _TemporalSmoothing; +#include "TemporalFilteringConstants.cs.hlsl" [numthreads(64, 1, 1)] void FilterTemporally(uint patchIdx : SV_DispatchThreadID) diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/TemporalFilteringConstants.cs b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/TemporalFilteringConstants.cs new file mode 100644 index 00000000000..659b670e2d8 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/TemporalFilteringConstants.cs @@ -0,0 +1,11 @@ +namespace UnityEngine.Rendering +{ + [GenerateHLSL(needAccessors = false, generateCBuffer = true)] + internal struct SurfaceCacheTemporalFilteringConstants + { + public uint _RingConfigOffset; + public float _TemporalSmoothing; + public uint _TemporalFilteringPad0; + public uint _TemporalFilteringPad1; + } +} diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/TemporalFilteringConstants.cs.hlsl b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/TemporalFilteringConstants.cs.hlsl new file mode 100644 index 00000000000..1390843477e --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/TemporalFilteringConstants.cs.hlsl @@ -0,0 +1,17 @@ +// +// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead +// + +#ifndef SURFACECACHETEMPORALFILTERINGCONSTANTS_CS_HLSL +#define SURFACECACHETEMPORALFILTERINGCONSTANTS_CS_HLSL +// Generated from UnityEngine.Rendering.SurfaceCacheTemporalFilteringConstants +// PackingRules = Exact +CBUFFER_START(SurfaceCacheTemporalFilteringConstants) + uint _RingConfigOffset; + float _TemporalSmoothing; + uint _TemporalFilteringPad0; + uint _TemporalFilteringPad1; +CBUFFER_END + + +#endif diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/TemporalFilteringConstants.cs.hlsl.meta b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/TemporalFilteringConstants.cs.hlsl.meta new file mode 100644 index 00000000000..d5f88097ba7 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/TemporalFilteringConstants.cs.hlsl.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 61fb3184dfd0841df807280df883653c +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/TemporalFilteringConstants.cs.meta b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/TemporalFilteringConstants.cs.meta new file mode 100644 index 00000000000..ec08b8fb65f --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/TemporalFilteringConstants.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 8f461e507d668402e8777ca16f670b6f \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/Unity.SurfaceCache.Runtime.asmdef b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/Unity.SurfaceCache.Runtime.asmdef index 4c5e3c7650b..8f9ad2d3f97 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/Unity.SurfaceCache.Runtime.asmdef +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/Unity.SurfaceCache.Runtime.asmdef @@ -20,7 +20,7 @@ "CloudRendering", "XboxOne" ], - "allowUnsafeCode": false, + "allowUnsafeCode": true, "overrideReferences": false, "precompiledReferences": [], "autoReferenced": true, diff --git a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/AGENTS.md b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/AGENTS.md new file mode 100644 index 00000000000..ed058fa6dae --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/AGENTS.md @@ -0,0 +1,3 @@ +# Path tracing library + +This folder is shared library code that the Unity Compute lightmapper and Surface Cache call. The lighting rules in `../Lighting/AGENTS.md` apply here. diff --git a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/AGENTS.md.meta b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/AGENTS.md.meta new file mode 100644 index 00000000000..471f463bde2 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/AGENTS.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 442a54143697642e6912cae7e9a69653 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/AssemblyInfo.cs b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/AssemblyInfo.cs index d2546cc72d7..4b4b34f445b 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/AssemblyInfo.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/AssemblyInfo.cs @@ -4,6 +4,7 @@ [assembly: InternalsVisibleTo("Unity.PathTracing.Editor.Tests")] [assembly: InternalsVisibleTo("Unity.PathTracing.Runtime.Tests")] [assembly: InternalsVisibleTo("Unity.Modules.GI.PathTracing.Tests.Editor")] +[assembly: InternalsVisibleTo("Unity.Modules.GI.LightBaker.Tests.Editor")] [assembly: InternalsVisibleTo("Assembly-CSharp-Editor-testable")] [assembly: InternalsVisibleTo("Unity.RenderPipelines.HighDefinition.Runtime")] [assembly: InternalsVisibleTo("Unity.RenderPipelines.Universal.Editor")] diff --git a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/CLAUDE.md b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/CLAUDE.md new file mode 100644 index 00000000000..43c994c2d36 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/CLAUDE.md.meta b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/CLAUDE.md.meta new file mode 100644 index 00000000000..7b9a3f83e35 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/CLAUDE.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: ab977f49f13de454cb78801b26a38f43 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Core/TextureQuadTree.cs b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Core/TextureQuadTree.cs index 0c1b65aca60..728d881dc21 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Core/TextureQuadTree.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Core/TextureQuadTree.cs @@ -151,5 +151,7 @@ public bool HasSpaceForTexture(int textureSize) } public bool IsFull => _leaves.Count == 0; + + public bool IsEmpty => _leaves.Count == 1 && _leaves[0].Size == _size; } } diff --git a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Core/TextureSlotAllocator.cs b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Core/TextureSlotAllocator.cs index 9cb77d4e32e..d7492e9c7d3 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Core/TextureSlotAllocator.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Core/TextureSlotAllocator.cs @@ -6,6 +6,22 @@ namespace UnityEngine.PathTracing.Core { + internal readonly struct AtlasUsage + { + public readonly int UsedSliceCount; + public readonly int CapacitySliceCount; + public readonly int MaxSliceCount; + public readonly long AllocatedBytes; + + public AtlasUsage(int usedSliceCount, int capacitySliceCount, int maxSliceCount, long allocatedBytes) + { + UsedSliceCount = usedSliceCount; + CapacitySliceCount = capacitySliceCount; + MaxSliceCount = maxSliceCount; + AllocatedBytes = allocatedBytes; + } + } + // Container type that stores a set of arbitrarily sized textures in a 2D texture array, // where each slice is a quadtree. Supports add/update/remove operations. internal class TextureSlotAllocator : IDisposable @@ -28,6 +44,8 @@ public TextureLocation(int atlasIndex, TextureQuadTree.TextureNode textureNode) private readonly int _size; private readonly GraphicsFormat _format; private readonly FilterMode _filterMode; + private readonly int _maxSliceCount; + private readonly long _bytesPerPixel; private readonly CommandBuffer _cmd; private RenderTexture _atlases; @@ -42,17 +60,21 @@ public TextureLocation(int atlasIndex, TextureQuadTree.TextureNode textureNode) public RenderTexture Texture => _atlases; - public TextureSlotAllocator(int size, GraphicsFormat format, FilterMode filterMode) + public TextureSlotAllocator(int size, GraphicsFormat format, FilterMode filterMode, int maxSliceCount) { + Debug.Assert(maxSliceCount > 0, "The atlas must allow at least one slice."); _size = size; _format = format; _filterMode = filterMode; + _maxSliceCount = maxSliceCount; + _bytesPerPixel = GraphicsFormatUtility.GetBlockSize(format); _cmd = new CommandBuffer(); _cmd.name = $"Texture Slot Allocator ({size}, {format})"; // Initial allocation, in order to have a texture atlas in place even if we don't add anything to it. // Note: This is required when binding the textures to ray tracing shaders (compute shaders seem to be OK with null textures) - ResizeAtlas(1); + bool created = TryResizeAtlas(1); + Debug.Assert(created, "Failed to create the initial texture atlas slice."); } public TextureLocation AddTexture(Texture texture, Vector2 scale, Vector2 offset) @@ -65,7 +87,7 @@ public TextureLocation AddTexture(Texture texture, Vector2 scale, Vector2 offset TextureQuadTree atlas = null; foreach (int freeIndex in _freeAtlases) { - if (_textureQuadTrees[freeIndex].HasSpaceForTexture(size)) + if (_textureQuadTrees[freeIndex].HasSpaceForTexture(GetNodeSize(size))) { atlasIndex = freeIndex; atlas = _textureQuadTrees[atlasIndex]; @@ -76,12 +98,18 @@ public TextureLocation AddTexture(Texture texture, Vector2 scale, Vector2 offset // If we couldn't find one, create a new atlas if (atlasIndex == -1 || atlas == null) { + int used = _textureQuadTrees.Length; + if (used >= _maxSliceCount) + return TextureLocation.Invalid; + + if (used == _atlases.volumeDepth && !TryGrowAtlas(used)) + return TextureLocation.Invalid; + // Create a new atlas - atlasIndex = _textureQuadTrees.Length; + atlasIndex = used; Array.Resize(ref _textureQuadTrees, atlasIndex + 1); atlas = new TextureQuadTree(_size); _textureQuadTrees[atlasIndex] = atlas; - ResizeAtlas(atlasIndex + 1); // Add it to the free list _freeAtlases.Add(atlasIndex); @@ -158,7 +186,27 @@ public void GetScaleAndOffset(in TextureLocation location, out Vector2 scale, ou offset = new Vector2(location.TextureNode.PosX / (float)_size, location.TextureNode.PosY / (float)_size); } - private void ResizeAtlas(int sliceCount) + internal int GetNodeSize(int textureSize) => Mathf.Min(Mathf.NextPowerOfTwo(textureSize), _size); + + internal AtlasUsage GetUsage() + { + int capacity = _atlases != null ? _atlases.volumeDepth : 0; + int used = 0; + foreach (var quadTree in _textureQuadTrees) + { + if (!quadTree.IsEmpty) + used++; + } + return new AtlasUsage(used, capacity, _maxSliceCount, capacity * (long)_size * _size * _bytesPerPixel); + } + + private bool TryGrowAtlas(int usedSliceCount) + { + int doubled = Mathf.Min(usedSliceCount * 2, _maxSliceCount); + return TryResizeAtlas(doubled) || (doubled > usedSliceCount + 1 && TryResizeAtlas(usedSliceCount + 1)); + } + + private bool TryResizeAtlas(int sliceCount) { // Create new atlas array var texture = new RenderTexture(new RenderTextureDescriptor(_size, _size) @@ -179,23 +227,26 @@ private void ResizeAtlas(int sliceCount) wrapModeV = TextureWrapMode.Clamp, filterMode = _filterMode, }; - texture.Create(); + if (!texture.Create()) + { + CoreUtils.Destroy(texture); + return false; + } if (_atlases != null) { - var previousRT = RenderTexture.active; - // Blit old atlases into new one - for (int i = 0; i < Mathf.Min(sliceCount, _atlases.volumeDepth); i++) - { - Graphics.Blit(_atlases, texture, i, i); - } - RenderTexture.active = previousRT; - // Release old atlases + int copyCount = Mathf.Min(sliceCount, _textureQuadTrees.Length); + for (int i = 0; i < copyCount; i++) + _cmd.CopyTexture(_atlases, i, texture, i); + Graphics.ExecuteCommandBuffer(_cmd); + _cmd.Clear(); + _atlases.Release(); CoreUtils.Destroy(_atlases); } _atlases = texture; + return true; } public void Dispose() diff --git a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Environment/CubemapRender.cs b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Environment/CubemapRender.cs index f465a3bceae..a615d8fff35 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Environment/CubemapRender.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Environment/CubemapRender.cs @@ -14,11 +14,13 @@ internal class CubemapRender : IDisposable internal enum Mode { Material, - Color + Color, + Texture } - private Material _material; - private Shader _lastUsedShader; + private Material _cubemapMaterial; + private Texture _texture; + private Shader _lastUsedCubemapShader; private LocalKeyword? _noSunKeyword; private Color[] _faceColors = new Color[6] { @@ -73,7 +75,13 @@ public void Dispose() public void SetMaterial(Material mat) { - _material = mat; + _cubemapMaterial = mat; + } + + public void SetTexture(Texture cubemap) + { + Debug.Assert(cubemap == null || cubemap.dimension == TextureDimension.Cube); + _texture = cubemap; } public void SetColor(Color color) @@ -94,7 +102,12 @@ public void SetMode(Mode mode) _mode = mode; } - public Material GetMaterial() => _material; + public bool HasContent() => _mode switch + { + Mode.Material => _cubemapMaterial != null, + Mode.Texture => _texture != null, + _ => true + }; Color LightColorInRenderingSpace(Light light) { @@ -107,6 +120,14 @@ public void Update(CommandBuffer cmd, Light sun, int resolution, out bool viewAn { viewAndProjectionMatricesChanged = false; + if (_mode == Mode.Texture) + { + _hash = _texture != null + ? HashCode.Combine((int)_mode + 1, _texture.GetEntityId(), _texture.updateCount) + : HashCode.Combine((int)_mode + 1); + return; + } + int newHash = ((int)_mode) + 1; if (_mode == Mode.Color) { @@ -116,13 +137,21 @@ public void Update(CommandBuffer cmd, Light sun, int resolution, out bool viewAn } if (newHash != _hash) + { + _colorMaterial ??= CoreUtils.CreateEngineMaterial(_solidColorShader); +#if UNITY_EDITOR + // The editor skips procedural draws while the shader compiles async, so keep the old hash and retry next frame + if (RequestShaderCompilationIfNeeded(_colorMaterial, 1)) + return; +#endif RenderWithColor(cmd); + } } else if (_mode == Mode.Material) { - if (_material) + if (_cubemapMaterial) { - newHash = HashCode.Combine(newHash, _material.ComputeCRC()); + newHash = HashCode.Combine(newHash, _cubemapMaterial.ComputeCRC()); if (sun != null) { var color = LightColorInRenderingSpace(sun); @@ -132,7 +161,20 @@ public void Update(CommandBuffer cmd, Light sun, int resolution, out bool viewAn } if (newHash != _hash) + { + if (_lastUsedCubemapShader != _cubemapMaterial.shader) + { + var keyword = _cubemapMaterial.shader.keywordSpace.FindKeyword("_SUNDISK_NONE"); + _noSunKeyword = keyword.isValid ? keyword : null; + _lastUsedCubemapShader = _cubemapMaterial.shader; + } +#if UNITY_EDITOR + // Drawing while the shader compiles async would bake the placeholder shader into the cubemap + if (RequestCubemapMaterialCompilationIfNeeded(_cubemapMaterial, _noSunKeyword)) + return; +#endif RenderWithMaterial(cmd, sun, resolution, out viewAndProjectionMatricesChanged); + } } else { @@ -155,6 +197,8 @@ void ReleaseCubemapIfExists() public Texture GetCubemap() { + if (_mode == Mode.Texture) + return _texture != null ? _texture : CoreUtils.blackCubeTexture; return _cubemap != null ? _cubemap : CoreUtils.blackCubeTexture; } @@ -164,7 +208,9 @@ private void RenderWithColor(CommandBuffer cmd) // Draw the color rather than ClearRenderTarget it: on some platforms a fast clear // collapses a non-{0,1} HDR clear color to ~white, while a fullscreen draw is exact. - _colorMaterial ??= CoreUtils.CreateEngineMaterial(_solidColorShader); +#if UNITY_EDITOR + Debug.Assert(ShaderUtil.IsPassCompiled(_colorMaterial, 0) || !ShaderUtil.allowAsyncCompilation, "The solid color shader is expected to be compiled before drawing the environment cubemap."); +#endif _colorProperties ??= new MaterialPropertyBlock(); for (int faceIndex = 0; faceIndex < 6; ++faceIndex) @@ -192,15 +238,8 @@ private void RenderWithMaterial(CommandBuffer cmd, Light sun, int cubemapResolut properties.SetVector(Shader.PropertyToID("_WorldSpaceLightPos0"), new Vector4(0, 0, -1, 0)); } - if (_lastUsedShader != _material.shader) - { - var keyword = _material.shader.keywordSpace.FindKeyword("_SUNDISK_NONE"); - _noSunKeyword = keyword.isValid ? keyword : null; - _lastUsedShader = _material.shader; - } - if (_noSunKeyword.HasValue) - cmd.EnableKeyword(_material, _noSunKeyword.Value); + cmd.EnableKeyword(_cubemapMaterial, _noSunKeyword.Value); for (int faceIndex = 0; faceIndex < 6; ++faceIndex) { @@ -214,29 +253,57 @@ private void RenderWithMaterial(CommandBuffer cmd, Light sun, int cubemapResolut cmd.SetViewport(new Rect(0, 0, _cubemap.width, _cubemap.height)); cmd.ClearRenderTarget(false, true, new Color(0, 0, 0, 1)); -#if UNITY_EDITOR - ShaderUtil.SetAsyncCompilation(cmd, false); -#endif - if (_material.passCount == 6) + if (_cubemapMaterial.passCount == 6) { int passIndex = _cubeFaceToSkyboxPass[faceIndex]; - cmd.DrawMesh(_sixFaceSkyboxMesh, Matrix4x4.identity, _material, passIndex, passIndex, properties); + cmd.DrawMesh(_sixFaceSkyboxMesh, Matrix4x4.identity, _cubemapMaterial, passIndex, passIndex, properties); } else { - cmd.DrawMesh(_skyboxMesh, Matrix4x4.identity, _material, 0, 0, properties); + cmd.DrawMesh(_skyboxMesh, Matrix4x4.identity, _cubemapMaterial, 0, 0, properties); } -#if UNITY_EDITOR - ShaderUtil.RestoreAsyncCompilation(cmd); -#endif } viewAndProjectionMatricesChanged = true; if (_noSunKeyword.HasValue) - cmd.DisableKeyword(_material, _noSunKeyword.Value); + cmd.DisableKeyword(_cubemapMaterial, _noSunKeyword.Value); } +#if UNITY_EDITOR + // Requests compilation of the passes that are not compiled yet and returns whether any pass is still compiling + private static bool RequestShaderCompilationIfNeeded(Material material, int passCount) + { + if (!ShaderUtil.allowAsyncCompilation) + return false; + + bool compiling = false; + for (int passIndex = 0; passIndex < passCount; ++passIndex) + { + if (ShaderUtil.IsPassCompiled(material, passIndex)) + continue; + + ShaderUtil.CompilePass(material, passIndex); + compiling = true; + } + return compiling; + } + + private static bool RequestCubemapMaterialCompilationIfNeeded(Material cubemapMaterial, LocalKeyword? noSunKeyword) + { + // Check the variant the draw uses, which has the no-sun keyword enabled + bool toggleKeyword = noSunKeyword.HasValue && !cubemapMaterial.IsKeywordEnabled(noSunKeyword.Value); + if (toggleKeyword) + cubemapMaterial.SetKeyword(noSunKeyword.Value, true); + + bool compiling = RequestShaderCompilationIfNeeded(cubemapMaterial, cubemapMaterial.passCount == 6 ? 6 : 1); + + if (toggleKeyword) + cubemapMaterial.SetKeyword(noSunKeyword.Value, false); + return compiling; + } +#endif + private void EnsureCubemapExistsWithParticularResolution(int resolution) { if (_cubemap == null || _cubemap.width != resolution) diff --git a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/MaterialPool/MaterialPool.cs b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/MaterialPool/MaterialPool.cs index 55a57bf6035..dc5c644cd69 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/MaterialPool/MaterialPool.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/MaterialPool/MaterialPool.cs @@ -91,6 +91,22 @@ public MaterialEntry(BlockAllocator.Allocation indexInBufferAlloc) public bool PointSampleEmission; }; + private struct StagedTexture + { + public readonly TextureType Type; + public readonly TextureSlotAllocator.TextureLocation Original; + public readonly bool UsesAtlasSlot; + public TextureSlotAllocator.TextureLocation Allocated; + + public StagedTexture(TextureType type, TextureSlotAllocator.TextureLocation original, bool usesAtlasSlot) + { + Type = type; + Original = original; + UsesAtlasSlot = usesAtlasSlot; + Allocated = TextureSlotAllocator.TextureLocation.Invalid; + } + } + private readonly Dictionary _materialMap = new(); private readonly Dictionary _lightCookies = new(); // this dictionary is used to keep track of which textures are inserted in the atlas and avoid duplication (important for LiveGI) private readonly Dictionary _cookieHandleToID = new(); // this dictionary is used when deleting lights with cookies attached, so we can free-up the atlas slots @@ -130,9 +146,13 @@ public MaterialEntry(BlockAllocator.Allocation indexInBufferAlloc) private readonly int _blitGrayscaleCookieKernel; private const int AtlasSize = 256; + private readonly int _maxSliceCount; - public MaterialPool(ComputeShader setAlphaChannelShader, ComputeShader blitCubemapShader, ComputeShader blitGrayscaleCookieShader) + public MaterialPool(ComputeShader setAlphaChannelShader, ComputeShader blitCubemapShader, ComputeShader blitGrayscaleCookieShader, int maxSliceCount) { + Debug.Assert(maxSliceCount > 0, "The atlas must allow at least one slice."); + _maxSliceCount = maxSliceCount; + _setAlphaChannelShader = setAlphaChannelShader; _setAlphaChannelKernel = _setAlphaChannelShader.FindKernel("SetAlphaChannel"); _setAlphaChannelShader.GetKernelThreadGroupSizes(_setAlphaChannelKernel, @@ -148,9 +168,9 @@ public MaterialPool(ComputeShader setAlphaChannelShader, ComputeShader blitCubem const int initialMaxLightCubemapTextureCount = 3; const int initialMaxMaterialCount = 100; - _albedoTextureAllocator = new TextureSlotAllocator(AtlasSize, GetTextureFormat(TextureType.Albedo), FilterMode.Bilinear); - _emissionTextureAllocator = new TextureSlotAllocator(AtlasSize, GetTextureFormat(TextureType.Emission), FilterMode.Bilinear); - _transmissionTextureAllocator = new TextureSlotAllocator(AtlasSize, GetTextureFormat(TextureType.Transmission), FilterMode.Bilinear); + _albedoTextureAllocator = new TextureSlotAllocator(AtlasSize, GetTextureFormat(TextureType.Albedo), FilterMode.Bilinear, maxSliceCount); + _emissionTextureAllocator = new TextureSlotAllocator(AtlasSize, GetTextureFormat(TextureType.Emission), FilterMode.Bilinear, maxSliceCount); + _transmissionTextureAllocator = new TextureSlotAllocator(AtlasSize, GetTextureFormat(TextureType.Transmission), FilterMode.Bilinear, maxSliceCount); _materialSlotAllocator.Initialize(initialMaxMaterialCount); MaterialBuffer = new ComputeBuffer(initialMaxMaterialCount, Marshal.SizeOf()); @@ -189,7 +209,7 @@ public void Dispose() } } - public void AddMaterial(UInt64 materialHandle, in MaterialDescriptor material, UVChannel albedoAndEmissionUVChannel) + public bool AddMaterial(UInt64 materialHandle, in MaterialDescriptor material, UVChannel albedoAndEmissionUVChannel) { MaterialEntry materialEntry; Debug.Assert(!_materialMap.ContainsKey(materialHandle), "Material was already added to the pool."); @@ -204,17 +224,30 @@ public void AddMaterial(UInt64 materialHandle, in MaterialDescriptor material, U } materialEntry = new MaterialEntry(slotAllocation); - UpdateMaterial(in material, albedoAndEmissionUVChannel, materialEntry); + if (!UpdateMaterial(in material, albedoAndEmissionUVChannel, materialEntry)) + { + _materialSlotAllocator.FreeAllocation(in slotAllocation); + return false; + } _materialMap.Add(materialHandle, materialEntry); UpdateMaterialList(materialEntry); + return true; } - public void UpdateMaterial(UInt64 materialHandle, in MaterialDescriptor material, UVChannel albedoAndEmissionUVChannel) + public bool UpdateMaterial(UInt64 materialHandle, in MaterialDescriptor material, UVChannel albedoAndEmissionUVChannel) { + Debug.Assert(_materialMap.ContainsKey(materialHandle), "Material was not added to the pool."); MaterialEntry materialEntry = _materialMap[materialHandle]; - UpdateMaterial(in material, albedoAndEmissionUVChannel, materialEntry); + return UpdateMaterial(in material, albedoAndEmissionUVChannel, materialEntry); + } + + internal void GetAtlasUsage(out AtlasUsage albedo, out AtlasUsage emission, out AtlasUsage transmission) + { + albedo = _albedoTextureAllocator.GetUsage(); + emission = _emissionTextureAllocator.GetUsage(); + transmission = _transmissionTextureAllocator.GetUsage(); } public void RemoveMaterial(UInt64 materialInstanceID) @@ -274,9 +307,38 @@ public void Build(CommandBuffer cmd) } } - private void UpdateMaterial(in MaterialDescriptor material, UVChannel albedoAndEmissionUVChannel, MaterialEntry materialEntry) +#if UNITY_INCLUDE_TESTS + internal List ReadBackEmissionColors() + { + var entries = new GpuMaterialEntry[MaterialBuffer.count]; + MaterialBuffer.GetData(entries); + + var emissionColors = new List(entries.Length); + foreach (var entry in entries) + emissionColors.Add(entry.EmissionColor); + + return emissionColors; + } +#endif + + private bool UpdateMaterial(in MaterialDescriptor material, UVChannel albedoAndEmissionUVChannel, MaterialEntry materialEntry) { - AddOrUpdateTexture(in material, TextureType.Albedo, ref materialEntry.AlbedoTextureLocation); + var albedo = new StagedTexture(TextureType.Albedo, materialEntry.AlbedoTextureLocation, true); + var emission = new StagedTexture(TextureType.Emission, materialEntry.EmissionTextureLocation, material.EmissionType == MaterialPropertyType.Texture); + var transmission = new StagedTexture(TextureType.Transmission, materialEntry.TransmissionTextureLocation, + material.TransmissionChannels == TransmissionChannels.RGB && material.Transmission != null); + + if (!TryStageTexture(in material, ref albedo) || !TryStageTexture(in material, ref emission) || !TryStageTexture(in material, ref transmission)) + { + DiscardStagedTexture(in albedo); + DiscardStagedTexture(in emission); + DiscardStagedTexture(in transmission); + return false; + } + + materialEntry.AlbedoTextureLocation = CommitStagedTexture(in material, in albedo); + materialEntry.EmissionTextureLocation = CommitStagedTexture(in material, in emission); + materialEntry.TransmissionTextureLocation = CommitStagedTexture(in material, in transmission); if (material.TransmissionChannels == TransmissionChannels.Alpha) FillAlbedoTextureAlphaWithOpacity(in material, materialEntry.AlbedoTextureLocation); @@ -288,33 +350,10 @@ private void UpdateMaterial(in MaterialDescriptor material, UVChannel albedoAndE materialEntry.PointSampleAlbedo = material.PointSampleAlbedo; materialEntry.PointSampleEmission = material.PointSampleEmission; - var emissionType = material.EmissionType; - if (emissionType == MaterialPropertyType.Texture) - { - AddOrUpdateTexture(in material, TextureType.Emission, ref materialEntry.EmissionTextureLocation); - materialEntry.EmissionColor = 0; - } - else if (emissionType == MaterialPropertyType.Color) - { - RemoveTextureIfPresent(TextureType.Emission, ref materialEntry.EmissionTextureLocation); - materialEntry.EmissionColor = material.EmissionColor; - } - else if (emissionType == MaterialPropertyType.None) - { - RemoveTextureIfPresent(TextureType.Emission, ref materialEntry.EmissionTextureLocation); - materialEntry.EmissionColor = 0; - } - - if (material.TransmissionChannels == TransmissionChannels.RGB && material.Transmission != null) - { - AddOrUpdateTexture(in material, TextureType.Transmission, ref materialEntry.TransmissionTextureLocation); - } - else - { - RemoveTextureIfPresent(TextureType.Transmission, ref materialEntry.TransmissionTextureLocation); - } + materialEntry.EmissionColor = material.EmissionType == MaterialPropertyType.Color ? material.EmissionColor : 0; UpdateMaterialList(materialEntry); + return true; } private void UpdateMaterialList(MaterialEntry entry) @@ -382,47 +421,48 @@ private static int GetCookieHandle(int slices, int handle) return 2 * handle + offset; } - public int AddCookieTexture(Texture cookie) + public bool TryAddCookieTexture(Texture cookie, out int cookieIndex) { - if (cookie != null) + cookieIndex = -1; + if (cookie == null) + return false; + + var cookieID = Util.EntityIDToUlong(cookie.GetEntityId()); + if (_lightCookies.TryGetValue(cookieID, out var allocator)) { - var cookieID = Util.EntityIDToUlong(cookie.GetEntityId()); - if (_lightCookies.TryGetValue(cookieID, out var allocator)) - { - // This cookie was already copied in the atlas in a previous frame - // Baking will never hit this path, as the lights are not updated during a bake, but it's important for LiveGI - return allocator.handle; - } + // This cookie was already copied in the atlas in a previous frame + // Baking will never hit this path, as the lights are not updated during a bake, but it's important for LiveGI + cookieIndex = allocator.handle; + return true; + } - int slices = GetCookieFaces(cookie); + int slices = GetCookieFaces(cookie); - BlockAllocator.Allocation slotAllocation; - if (slices > 1) - { - slotAllocation = _lightCubemapTexturesSlotAllocator.Allocate(1); - ExpandCookieTextureArray(true, ref _lightCubemapTexturesSlotAllocator, ref LightCubemapTextures, ref slotAllocation); - - RenderTexture prevRT = RenderTexture.active; - BlitCubemapCookie(cookie, LightCubemapTextures, slotAllocation.block.offset); - RenderTexture.active = prevRT; - } - else - { - slotAllocation = _lightCookieTexturesSlotAllocator.Allocate(1); - ExpandCookieTextureArray(false, ref _lightCookieTexturesSlotAllocator, ref LightCookieTextures, ref slotAllocation); + BlockAllocator.Allocation slotAllocation; + if (slices > 1) + { + if (!TryAllocateCookieSlot(true, ref _lightCubemapTexturesSlotAllocator, ref LightCubemapTextures, out slotAllocation)) + return false; - RenderTexture prevRT = RenderTexture.active; - Blit2DCookie(cookie, LightCookieTextures, slotAllocation.block.offset); - RenderTexture.active = prevRT; - } + RenderTexture prevRT = RenderTexture.active; + BlitCubemapCookie(cookie, LightCubemapTextures, slotAllocation.block.offset); + RenderTexture.active = prevRT; + } + else + { + if (!TryAllocateCookieSlot(false, ref _lightCookieTexturesSlotAllocator, ref LightCookieTextures, out slotAllocation)) + return false; - int handle = GetCookieHandle(slices, slotAllocation.handle); - _lightCookies.Add(cookieID, slotAllocation); - _cookieHandleToID.Add(handle, cookieID); - return slotAllocation.handle; + RenderTexture prevRT = RenderTexture.active; + Blit2DCookie(cookie, LightCookieTextures, slotAllocation.block.offset); + RenderTexture.active = prevRT; } - return -1; + int handle = GetCookieHandle(slices, slotAllocation.handle); + _lightCookies.Add(cookieID, slotAllocation); + _cookieHandleToID.Add(handle, cookieID); + cookieIndex = slotAllocation.handle; + return true; } public void RemoveCookieTexture(int cookieFaces, int cookieIndex) @@ -449,30 +489,40 @@ public void RemoveCookieTexture(int cookieFaces, int cookieIndex) } } - private void ExpandCookieTextureArray(bool isCubemapCookie, ref BlockAllocator allocator, ref RenderTexture texture, ref BlockAllocator.Allocation textureAlloc) + private bool TryAllocateCookieSlot(bool isCubemapCookie, ref BlockAllocator allocator, ref RenderTexture texture, out BlockAllocator.Allocation slot) { - if (!textureAlloc.valid) + slot = allocator.Allocate(1); + if (slot.valid) + return true; + + var oldCapacity = allocator.capacity; + int limit = isCubemapCookie ? _maxSliceCount / 6 : _maxSliceCount; + if (oldCapacity >= limit) + return false; + + int newCapacity = Mathf.Min(Mathf.Max(oldCapacity * 2, oldCapacity + 1), limit); + var newTexture = CreateTextureArray(newCapacity, isCubemapCookie ? TextureType.LightCubemap : TextureType.LightCookie); + if (!newTexture.IsCreated()) { - textureAlloc = allocator.Allocate(1); - if (!textureAlloc.valid) - { - var oldCapacity = allocator.capacity; - allocator.Grow(allocator.capacity + 1); + CoreUtils.Destroy(newTexture); + return false; + } - var newTexture = CreateTextureArray(allocator.capacity, isCubemapCookie ? TextureType.LightCubemap : TextureType.LightCookie); + allocator.Grow(newCapacity); - using var cmd = new CommandBuffer(); - for (int i = 0; i < oldCapacity; ++i) - cmd.CopyTexture(texture, i, newTexture, i); - Graphics.ExecuteCommandBuffer(cmd); + int copySliceCount = isCubemapCookie ? oldCapacity * 6 : oldCapacity; + using var cmd = new CommandBuffer(); + for (int i = 0; i < copySliceCount; ++i) + cmd.CopyTexture(texture, i, newTexture, i); + Graphics.ExecuteCommandBuffer(cmd); - texture.Release(); - texture = newTexture; + texture.Release(); + CoreUtils.Destroy(texture); + texture = newTexture; - textureAlloc = allocator.Allocate(1); - Assert.IsTrue(textureAlloc.valid); - } - } + slot = allocator.Allocate(1); + Assert.IsTrue(slot.valid); + return true; } // Blits all faces of a cubemap to a slice of a cubemap array, performing any format conversions that are necessary @@ -534,44 +584,104 @@ private void Blit2DCookie(Texture source, RenderTexture dest, int destIndex) } #endregion - private void AddOrUpdateTexture(in MaterialDescriptor material, TextureType textureType, ref TextureSlotAllocator.TextureLocation location) + private TextureSlotAllocator GetAllocator(TextureType textureType) { - // Find appropriate allocator, scale, offset and texture - var allocator = _transmissionTextureAllocator; - Vector2 scale = material.TransmissionScale; - Vector2 offset = material.TransmissionOffset; + if (textureType == TextureType.Albedo) + return _albedoTextureAllocator; + if (textureType == TextureType.Emission) + return _emissionTextureAllocator; + return _transmissionTextureAllocator; + } + + private void GetTextureSource(in MaterialDescriptor material, TextureType textureType, out TextureSlotAllocator allocator, out Texture texture, out Vector2 scale, out Vector2 offset) + { + allocator = GetAllocator(textureType); + scale = material.TransmissionScale; + offset = material.TransmissionOffset; offset.y = -offset.y; // TODO: During extraction this value is negated. This should be fixed. Tracked here: https://jira.unity3d.com/browse/GFXFEAT-802 - Texture texture = material.Transmission; + texture = material.Transmission; if (textureType == TextureType.Albedo) { - allocator = _albedoTextureAllocator; texture = material.Albedo; scale = material.AlbedoScale; offset = material.AlbedoOffset; } else if (textureType == TextureType.Emission) { - allocator = _emissionTextureAllocator; texture = material.Emission; scale = material.EmissionScale; offset = material.EmissionOffset; } + } + + // Only allocations that can fail happen here; in-place updates and shrinks are deferred to CommitStagedTexture + // so that a rejected material update leaves the entry and its atlas content untouched. + private bool TryStageTexture(in MaterialDescriptor material, ref StagedTexture staged) + { + GetTextureSource(in material, staged.Type, out var allocator, out var texture, out var scale, out var offset); + if (!staged.UsesAtlasSlot || texture == null) + return true; + + int nodeSize = allocator.GetNodeSize(Mathf.Max(texture.width, texture.height)); + if (staged.Original.IsValid && nodeSize == staged.Original.TextureNode.Size) + return true; + + staged.Allocated = allocator.AddTexture(texture, scale, offset); + if (staged.Allocated.IsValid) + { + CountTextureBlit(); + return true; + } - // Invalid texture - bail - if (texture == null) + // Without a new node, the texture goes into the node it already has: freed and re-added when smaller, + // scaled down into it when larger. + return staged.Original.IsValid; + } + + private void DiscardStagedTexture(in StagedTexture staged) + { + if (!staged.Allocated.IsValid) return; - // Update path - if (location.IsValid) + GetAllocator(staged.Type).RemoveTexture(in staged.Allocated); + } + + private TextureSlotAllocator.TextureLocation CommitStagedTexture(in MaterialDescriptor material, in StagedTexture staged) + { + GetTextureSource(in material, staged.Type, out var allocator, out var texture, out var scale, out var offset); + if (!staged.UsesAtlasSlot) { - allocator.UpdateTexture(in location, texture, scale, offset); + if (staged.Original.IsValid) + allocator.RemoveTexture(in staged.Original); + return TextureSlotAllocator.TextureLocation.Invalid; } - // Add path - else + + if (texture == null) + return staged.Original; + + if (staged.Allocated.IsValid) { - location = allocator.AddTexture(texture, scale, offset); + if (staged.Original.IsValid) + allocator.RemoveTexture(in staged.Original); + return staged.Allocated; } + if (allocator.GetNodeSize(Mathf.Max(texture.width, texture.height)) >= staged.Original.TextureNode.Size) + { + allocator.UpdateTexture(in staged.Original, texture, scale, offset); + CountTextureBlit(); + return staged.Original; + } + + allocator.RemoveTexture(in staged.Original); + var location = allocator.AddTexture(texture, scale, offset); + Debug.Assert(location.IsValid, "Shrinking a texture in the atlas should not fail."); + CountTextureBlit(); + return location; + } + + private void CountTextureBlit() + { if (++_textureBlitsSinceLastFlush >= k_TextureFlushThreshold) { GL.Flush(); @@ -621,7 +731,7 @@ private void FillAlbedoTextureAlphaWithOpacity(in MaterialDescriptor material, T } // Render out an albedo/emission texture using the meta pass - private static Texture EvaluateMetaPass(Material material, TextureType textureType) + private static Texture EvaluateMetaPass(Material material, TextureType textureType, int resolution) { if (textureType == TextureType.Transmission) { @@ -629,7 +739,7 @@ private static Texture EvaluateMetaPass(Material material, TextureType textureTy return null; } - var targetTexture = CreateTexture(textureType); + var targetTexture = CreateTexture(textureType, resolution: resolution); int metaPassIndex = material.FindPass("Meta"); @@ -667,7 +777,7 @@ private static Texture EvaluateMetaPass(Material material, TextureType textureTy } // The textures referenced by the material descriptor are owned by the material descriptor. - public static MaterialPool.MaterialDescriptor ConvertUnityMaterialToMaterialDescriptor(Material material, EmissionMode emissionMode) + public static MaterialPool.MaterialDescriptor ConvertUnityMaterialToMaterialDescriptor(Material material, EmissionMode emissionMode, int resolution = AtlasSize) { MaterialPool.MaterialDescriptor descriptor = new(); @@ -682,13 +792,13 @@ public static MaterialPool.MaterialDescriptor ConvertUnityMaterialToMaterialDesc if (emission.Type == MaterialPropertyType.Texture) { - descriptor.Emission = EvaluateMetaPass(material, TextureType.Emission); + descriptor.Emission = EvaluateMetaPass(material, TextureType.Emission, resolution); descriptor.EmissionScale = Vector2.one; // Scale and offset handled by meta pass descriptor.EmissionOffset = Vector2.zero; } // Albedo - descriptor.Albedo = EvaluateMetaPass(material, TextureType.Albedo); + descriptor.Albedo = EvaluateMetaPass(material, TextureType.Albedo, resolution); descriptor.AlbedoScale = Vector2.one; // Scale and offset handled by meta pass descriptor.AlbedoOffset = Vector2.zero; @@ -700,7 +810,7 @@ public static MaterialPool.MaterialDescriptor ConvertUnityMaterialToMaterialDesc if (transmission.Channels != TransmissionChannels.None) { RenderTexture prevRT = RenderTexture.active; - var transmissionTexture = CreateTexture(TextureType.Transmission); + var transmissionTexture = CreateTexture(TextureType.Transmission, resolution: resolution); Graphics.Blit(transmission.SourceTexture, transmissionTexture, transmission.Scale, transmission.Offset); descriptor.Transmission = transmissionTexture; RenderTexture.active = prevRT; @@ -735,11 +845,11 @@ private static RenderTexture CreateTextureArray(int sliceCount, TextureType text return CreateTexture(textureType, dimension, textureType == TextureType.LightCubemap ? sliceCount * 6 : sliceCount); } - private static RenderTexture CreateTexture(TextureType textureType, TextureDimension dimension = TextureDimension.Tex2D, int sliceCount = 1) + private static RenderTexture CreateTexture(TextureType textureType, TextureDimension dimension = TextureDimension.Tex2D, int sliceCount = 1, int resolution = AtlasSize) { var format = GetTextureFormat(textureType); - var texture = new RenderTexture(new RenderTextureDescriptor(AtlasSize, AtlasSize) + var texture = new RenderTexture(new RenderTextureDescriptor(resolution, resolution) { dimension = dimension, depthBufferBits = 0, diff --git a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/MaterialPool/MaterialPool.hlsl b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/MaterialPool/MaterialPool.hlsl index 57dc62db6b8..f99ad6d83e7 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/MaterialPool/MaterialPool.hlsl +++ b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/MaterialPool/MaterialPool.hlsl @@ -36,7 +36,7 @@ namespace MaterialPool float4 SampleAtlas(Texture2DArray atlas, SamplerState atlasSampler, float atlasTexelSize, uint index, float2 uv, float2 scale, float2 offset, bool pointFilterMode) { // Apply the scale and offset to access to desired atlas entry - float2 localUV = uv * scale + offset; + float2 localUV = frac(uv) * scale + offset; // To prevent sampling part of the neighbor due to bilinear filtering, we need to clamp the sample // position to an 'inner rectangle' of the atlas entry, which is shrunk by half a texel on each side. @@ -135,6 +135,11 @@ namespace MaterialPool return transmission; } + bool IsTransmissive(uint materialFlags) + { + return materialFlags & 1; + } + bool UsesDoubleSidedGI(uint materialFlags) { return materialFlags & 2; @@ -163,7 +168,7 @@ namespace MaterialPool material.baseColor = BoostAlbedo(albedo.rgb, albedoBoost); material.transmission = LoadTransmission(matEntry, albedo, transmissionTextures, transmissionSamplerState, atlasTexelSize, uv0); material.emission = LoadEmission(matEntry, emissionTextures, emissionSamplerState, atlasTexelSize, uv0, uv1); - material.isTransmissive = matEntry.flags & 1; + material.isTransmissive = IsTransmissive(matEntry.flags); material.doubleSidedGI = UsesDoubleSidedGI(matEntry.flags); // unused for now, we need these for specular support diff --git a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Shaders/LightmapIntegrationHelpers.hlsl b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Shaders/LightmapIntegrationHelpers.hlsl index a5a2dc21f06..50e68a0d598 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Shaders/LightmapIntegrationHelpers.hlsl +++ b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Shaders/LightmapIntegrationHelpers.hlsl @@ -86,8 +86,8 @@ bool GetExpandedSample(uint dispatchIndex, out uint localSampleOffset, out uint2 FetchGeomAttributes(hit, g_InstanceGeometryIndex, worldPosition, worldNormal, worldFaceNormal); worldPosition = mul(g_ShaderLocalToWorld, float4(worldPosition, 1)).xyz; - worldNormal = normalize(mul((float3x3)g_ShaderLocalToWorldNormals, worldNormal)); - worldFaceNormal = normalize(mul((float3x3)g_ShaderLocalToWorldNormals, worldFaceNormal)); + worldNormal = SafeNormalize(mul((float3x3)g_ShaderLocalToWorldNormals, worldNormal)); + worldFaceNormal = SafeNormalize(mul((float3x3)g_ShaderLocalToWorldNormals, worldFaceNormal)); return true; } } @@ -112,8 +112,8 @@ bool GetExpandedSample(uint dispatchIndex, inout float3 worldPosition, inout flo FetchGeomAttributes(hit, g_InstanceGeometryIndex, worldPosition, worldNormal, worldFaceNormal, uv1); worldPosition = mul(g_ShaderLocalToWorld, float4(worldPosition, 1)).xyz; - worldNormal = normalize(mul((float3x3)g_ShaderLocalToWorldNormals, worldNormal)); - worldFaceNormal = normalize(mul((float3x3)g_ShaderLocalToWorldNormals, worldFaceNormal)); + worldNormal = SafeNormalize(mul((float3x3)g_ShaderLocalToWorldNormals, worldNormal)); + worldFaceNormal = SafeNormalize(mul((float3x3)g_ShaderLocalToWorldNormals, worldFaceNormal)); return true; } } diff --git a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Shaders/PassthroughSkybox.shader b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Shaders/PassthroughSkybox.shader deleted file mode 100644 index 6b3760b1948..00000000000 --- a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Shaders/PassthroughSkybox.shader +++ /dev/null @@ -1,59 +0,0 @@ -Shader "Hidden/PassthroughSkybox" -{ - Properties - { - [NoScaleOffset] _Tex ("Cubemap", Cube) = "grey" {} - } - - SubShader - { - Tags { "Queue"="Background" "RenderType"="Background" "PreviewType"="Skybox" } - Cull Off ZWrite Off - - Pass - { - CGPROGRAM - #pragma vertex vert - #pragma fragment frag - #pragma target 5.0 - - #include "UnityCG.cginc" - - samplerCUBE _Tex; - half4 _Tex_HDR; - - struct appdata_t - { - float4 vertex : POSITION; - UNITY_VERTEX_INPUT_INSTANCE_ID - }; - - struct v2f - { - float4 vertex : SV_POSITION; - float3 texcoord : TEXCOORD0; - UNITY_VERTEX_OUTPUT_STEREO - }; - - v2f vert (appdata_t v) - { - v2f o; - UNITY_SETUP_INSTANCE_ID(v); - UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); - o.vertex = UnityObjectToClipPos(v.vertex); - o.texcoord = v.vertex.xyz; - return o; - } - - float4 frag (v2f i) : SV_Target - { - float4 tex = texCUBE (_Tex, i.texcoord); - float3 c = DecodeHDR (tex, _Tex_HDR); - return float4(c, 1); - } - ENDCG - } - } - - Fallback Off -} diff --git a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Shaders/ProbeOcclusionLightIndexMapping.compute b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Shaders/ProbeOcclusionLightIndexMapping.compute index 6ff80b1f591..bb7983dd6db 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Shaders/ProbeOcclusionLightIndexMapping.compute +++ b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Shaders/ProbeOcclusionLightIndexMapping.compute @@ -12,7 +12,7 @@ uint g_ProbeCount; [numthreads(64,1,1)] void MapIndices(uint3 id : SV_DispatchThreadID) { - if (id.x >= g_MaxLightsPerProbe * g_ProbeCount) + if (id.x >= g_ProbeCount) return; for (uint i = 0; i < g_MaxLightsPerProbe; i++) diff --git a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/World.cs b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/World.cs index 5a96d5c3b4f..76f5004a819 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/World.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/World.cs @@ -335,7 +335,12 @@ public int LightListHashCode public void Init(RayTracingContext ctx, WorldResourceSet worldResources) { - _materialPool = new MaterialPool(worldResources.SetAlphaChannelShader, worldResources.BlitCubemap, worldResources.BlitGrayScaleCookie); + Init(ctx, worldResources, SystemInfo.maxTextureArraySlices); + } + + internal void Init(RayTracingContext ctx, WorldResourceSet worldResources, int materialAtlasMaxSliceCount) + { + _materialPool = new MaterialPool(worldResources.SetAlphaChannelShader, worldResources.BlitCubemap, worldResources.BlitGrayScaleCookie, materialAtlasMaxSliceCount); var options = new AccelerationStructureOptions() { @@ -346,7 +351,7 @@ public void Init(RayTracingContext ctx, WorldResourceSet worldResources) _lightState = new LightState(); _cubemapRender = new CubemapRender(worldResources.SkyBoxMesh, worldResources.SixFaceSkyBoxMesh, worldResources.SolidColorShader); - _cubemapRender.SetMode(CubemapRender.Mode.Material); + _cubemapRender.SetMode(CubemapRender.Mode.Texture); _environmentSampling = new EnvironmentImportanceSampling(worldResources.EnvironmentImportanceSamplingBuild); _reservoirGrid = new RegirLightGrid(worldResources.BuildLightGridShader); _conservativeLightGrid = new ConservativeLightGrid(worldResources.BuildLightGridShader); @@ -357,9 +362,9 @@ private static float Luminance(Color color) return color.r * 0.2126f + color.g * 0.7152f + color.b * 0.0722f; } - public void SetEnvironmentMaterial(Material mat) + public void SetEnvironmentCubemap(Texture cubemap) { - _cubemapRender.SetMaterial(mat); + _cubemapRender.SetTexture(cubemap); } public ComputeBuffer GetMaterialListBuffer() @@ -501,27 +506,17 @@ public void RemoveMaterial(MaterialHandle materialHandle) public MaterialHandle AddMaterial(in MaterialPool.MaterialDescriptor material, UVChannel albedoAndEmissionUVChannel) { MaterialHandle handle = _materialHandleSet.Add(); - try + if (!_materialPool.AddMaterial(handle.Value, in material, albedoAndEmissionUVChannel)) { - _materialPool.AddMaterial(handle.Value, in material, albedoAndEmissionUVChannel); - } - catch (Exception e) - { - LogException("failed to add material", e, handle.Value); + _materialHandleSet.Remove(handle); + return MaterialHandle.Invalid; } return handle; } - public void UpdateMaterial(MaterialHandle materialHandle, in MaterialPool.MaterialDescriptor material, UVChannel albedoAndEmissionUVChannel) + public bool UpdateMaterial(MaterialHandle materialHandle, in MaterialPool.MaterialDescriptor material, UVChannel albedoAndEmissionUVChannel) { - try - { - _materialPool.UpdateMaterial(materialHandle.Value, in material, albedoAndEmissionUVChannel); - } - catch (Exception e) - { - LogException("failed to modify material", e, materialHandle.Value); - } + return _materialPool.UpdateMaterial(materialHandle.Value, in material, albedoAndEmissionUVChannel); } private void LogException(string message, Exception e, Object obj) @@ -554,6 +549,7 @@ public InstanceHandle AddInstance( Debug.Assert(mesh.subMeshCount == materials.Length); Debug.Assert(mesh.subMeshCount == masks.Length); + Span validMasks = stackalloc uint[mesh.subMeshCount]; Span materialIndices = stackalloc uint[mesh.subMeshCount]; Span isOpaque = stackalloc bool[mesh.subMeshCount]; for (int i = 0; i < materials.Length; ++i) @@ -561,13 +557,14 @@ public InstanceHandle AddInstance( if (materials[i] == MaterialHandle.Invalid) continue; + validMasks[i] = masks[i]; bool isTransmissive = false; _materialPool.GetMaterialInfo(materials[i].Value, out materialIndices[i], out isTransmissive); isOpaque[i] = !isTransmissive; } InstanceHandle instance = _instanceHandleSet.Add(); - _rayTracingAccelerationStructure.AddInstance(instance.Value, mesh, localToWorldMatrix, masks, materialIndices, isOpaque, renderingLayerMask); + _rayTracingAccelerationStructure.AddInstance(instance.Value, mesh, localToWorldMatrix, validMasks, materialIndices, isOpaque, renderingLayerMask); if (enableEmissiveSampling && !ProcessEmissiveMeshes(instance, mesh, bounds, materials, isStatic, _rayTracingAccelerationStructure, _materialPool, filter, _lightState.MeshLights, _subMeshIndices)) LogError($"Failed to process emissive triangles in mesh {mesh.name}."); @@ -589,6 +586,8 @@ public InstanceHandle AddTerrainInstance( uint materialIndex = 0; if (material != MaterialHandle.Invalid) _materialPool.GetMaterialInfo(material.Value, out materialIndex, out _); + else + mask = 0; InstanceHandle instance = _instanceHandleSet.Add(); _rayTracingAccelerationStructure.AddTerrainInstance( @@ -625,6 +624,9 @@ public void UpdateInstanceMaterials(InstanceHandle instance, Span materialIndices = stackalloc uint[materials.Length]; for (int i = 0; i < materials.Length; ++i) { + if (materials[i] == MaterialHandle.Invalid) + continue; + _materialPool.GetMaterialInfo(materials[i].Value, out materialIndices[i], out bool isTransmissive); } @@ -946,7 +948,7 @@ public void UpdateLights(LightHandle[] lightHandles, Span light newLight.attenuation.w = -cosSpotOuterHalfAngle * newLight.attenuation.z; } - newLight.cookieIndex = _materialPool.AddCookieTexture(light.CookieTexture); + _materialPool.TryAddCookieTexture(light.CookieTexture, out newLight.cookieIndex); _lightState.LightHandleToLightListEntry[lightHandles[i]] = newLight; } @@ -970,7 +972,7 @@ public void RemoveLights(Span lights) public void Build(Bounds sceneBounds, CommandBuffer cmdBuf, ref GraphicsBuffer scratchBuffer, Rendering.Sampling.SamplingResources samplingResources, bool emissiveSampling, int envCubemapResolution, int maxLightGridCellCount) { Debug.Assert(_rayTracingAccelerationStructure != null); - _lightState.Build(sceneBounds, cmdBuf, emissiveSampling && _cubemapRender.GetMaterial() != null); + _lightState.Build(sceneBounds, cmdBuf, emissiveSampling && _cubemapRender.HasContent()); if (_lightState.lightPickingMethod == LightPickingMethod.Regir) { diff --git a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Compiler/NativePassCompiler.cs b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Compiler/NativePassCompiler.cs index c91194c6c2e..41f960211d2 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Compiler/NativePassCompiler.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Compiler/NativePassCompiler.cs @@ -32,6 +32,10 @@ internal struct RenderGraphInputInfo RenderTargetIdentifier[][] m_TempMRTArrays = null; +#if UNITY_ENABLE_CHECKS + HashSet m_LoggedMemorylessAcrossNativePasses = new HashSet(); +#endif + internal const int k_EstimatedPassCount = 100; internal const int k_MaxSubpass = 8; // Needs to match with RenderPassSetup.h @@ -43,6 +47,12 @@ internal struct RenderGraphInputInfo [NoAutoStaticsCleanup] internal static bool s_ForceGenerateAuditsForTests = false; + internal static bool? s_SupportsMemorylessTexturesOverride; + internal static bool? s_CanStoreMemorylessTexturesOverride; + + static bool supportsMemorylessTextures => s_SupportsMemorylessTexturesOverride ?? SystemInfo.supportsMemorylessTextures; + static bool canStoreMemorylessTextures => s_CanStoreMemorylessTexturesOverride ?? SystemInfo.canStoreMemorylessTextures; + public NativePassCompiler(RenderGraphCompilationCache cache) { m_CompilationCache = cache; @@ -1174,16 +1184,36 @@ void PropagateTextureUVOrigin() // Find a texture attachment that is storing to find out the orientation for this pass. int attachmentsCount = nativePassData.attachments.size; int firstStoreAttachmentIndex = 0; + bool hasStore = false; TextureUVOriginSelection storeUVOrigin = TextureUVOriginSelection.Unknown; for (int attIdx = 0; attIdx < attachmentsCount; ++attIdx) { ref NativePassAttachment nativePassAttachment = ref nativePassData.attachments[attIdx]; + if (nativePassAttachment.handle.type != RenderGraphResourceType.Texture) // Only textures have orientation + continue; + + ref ResourceUnversionedData resData = ref contextData.UnversionedResourceData(nativePassAttachment.handle); if (nativePassAttachment.storeAction != RenderBufferStoreAction.DontCare) { - if (nativePassAttachment.handle.type == RenderGraphResourceType.Texture) // Only textures have orientation + storeUVOrigin = resData.textureUVOrigin; // Inherit the orientation of the store if we are currently storing to an unknown orientation. + firstStoreAttachmentIndex = attIdx; + hasStore = true; + break; + } + } + + if (!hasStore) + { + for (int attIdx = 0; attIdx < attachmentsCount; ++attIdx) + { + ref NativePassAttachment nativePassAttachment = ref nativePassData.attachments[attIdx]; + if (nativePassAttachment.handle.type != RenderGraphResourceType.Texture) + continue; + + ref ResourceUnversionedData resData = ref contextData.UnversionedResourceData(nativePassAttachment.handle); + if (resData.textureUVOrigin != TextureUVOriginSelection.Unknown) { - ref ResourceUnversionedData resData = ref contextData.UnversionedResourceData(nativePassAttachment.handle); - storeUVOrigin = resData.textureUVOrigin; // Inherit the orientation of the store if we are currently storing to an unknown orientation. + storeUVOrigin = resData.textureUVOrigin; firstStoreAttachmentIndex = attIdx; break; } @@ -1200,8 +1230,16 @@ void PropagateTextureUVOrigin() if (nativePassAttachment.handle.type == RenderGraphResourceType.Texture) { ref ResourceUnversionedData resData = ref contextData.UnversionedResourceData(nativePassAttachment.handle); - ValidateConflictingUVOrigins(ref nativePassData, ref nativePassAttachment, ref resData, storeUVOrigin, firstStoreAttachmentIndex); - resData.textureUVOrigin = storeUVOrigin; + if (hasStore) + { + ValidateConflictingUVOrigins(ref nativePassData, ref nativePassAttachment, ref resData, storeUVOrigin, firstStoreAttachmentIndex); + if (storeUVOrigin != TextureUVOriginSelection.Unknown) + resData.textureUVOrigin = storeUVOrigin; + } + else if (resData.textureUVOrigin == TextureUVOriginSelection.Unknown) + { + resData.textureUVOrigin = storeUVOrigin; + } } } } @@ -1221,24 +1259,21 @@ static bool IsGlobalTextureInPass(RenderGraphPass pass, in ResourceHandle handle return false; } - // An imported memoryless surface only retains its contents within a single native render pass. The graph does not - // own the surface, so it cannot make the contents survive a pass boundary - all it can do is tell the pipeline - // that it asked for something the hardware will not give it. - [Conditional("UNITY_ENABLE_CHECKS")] - void ValidateImportedMemorylessLifetimes() + // An imported memoryless surface only retains its contents within a single native render pass. Where the platform + // backs memoryless surfaces with memory on demand, the graph falls back to a regular store and load across the pass boundary. + void HandleImportedMemorylessLifetimes() { - if (!RenderGraph.enableValidityChecks) - return; + bool canStoreMemoryless = canStoreMemorylessTextures; var textureData = contextData.resources.unversionedData[(int)RenderGraphResourceType.Texture]; for (int i = 1; i < textureData.Length; ++i) { - ref readonly var resourceData = ref textureData.ElementAt(i); + ref var resourceData = ref textureData.ElementAt(i); if (!resourceData.isImported || !resourceData.memoryLess) continue; - // Unused or culled, nothing to validate. + // Unused or culled, nothing to handle. if (resourceData.firstUsePassID < 0 || resourceData.lastUsePassID < 0) continue; @@ -1248,24 +1283,44 @@ void ValidateImportedMemorylessLifetimes() if (firstNativePass == lastNativePass) continue; - var name = graph.m_ResourcesForDebugOnly.GetRenderGraphResourceName(RenderGraphResourceType.Texture, i); - Debug.LogWarning($"Imported memoryless resource '{name}' is used from pass '{contextData.GetPassName(resourceData.firstUsePassID)}' to pass '{contextData.GetPassName(resourceData.lastUsePassID)}', which span different native render passes. " - + "A memoryless surface does not retain its contents across a native render pass boundary, so the later pass reads undefined data. " - + "Either avoid the pass break, or render into a resource the render graph owns instead of importing a memoryless one."); + if (canStoreMemoryless) + resourceData.memoryLess = false; + + LogImportedMemorylessAcrossNativePasses(i, resourceData.firstUsePassID, resourceData.lastUsePassID, canStoreMemoryless); } } + [Conditional("UNITY_ENABLE_CHECKS")] + void LogImportedMemorylessAcrossNativePasses(int resourceIndex, int firstUsePassID, int lastUsePassID, bool canStoreMemoryless) + { +#if UNITY_ENABLE_CHECKS + if (!RenderGraph.enableValidityChecks) + return; + + var name = graph.m_ResourcesForDebugOnly.GetRenderGraphResourceName(RenderGraphResourceType.Texture, resourceIndex); + if (!m_LoggedMemorylessAcrossNativePasses.Add(name)) + return; + + var usage = $"Imported memoryless resource '{name}' is used from pass '{contextData.GetPassName(firstUsePassID)}' to pass '{contextData.GetPassName(lastUsePassID)}', which span different native render passes. "; + + if (canStoreMemoryless) + Debug.Log(usage + "Its contents are stored and loaded across the pass boundary, so it gets backed by regular memory, for all samples if it is multisampled, for as long as the surface exists. " + + "Avoid the pass break to keep the memory savings."); + else + Debug.LogWarning(usage + "A memoryless surface does not retain its contents across a native render pass boundary, so the later pass reads undefined data. " + + "Avoid the pass break, or don't request memoryless storage for this surface."); +#endif + } + void DetectMemoryLessResources() { using (k_DetectMemorylessResources.Auto()) { // No need to go further if we don't support memoryless textures - if (!SystemInfo.supportsMemorylessTextures) + if (!supportsMemorylessTextures) return; - // Note: memoryless on an imported resource is imposed by whoever created the surface (PlayerSettings for - // the Metal backbuffer depth, the provider for XR eye textures), so the graph cannot retract it here. - ValidateImportedMemorylessLifetimes(); + HandleImportedMemorylessLifetimes(); // Native renderpasses and create/destroy lists have now been set-up. Detect memoryless resources, i.e resources that are created/destroyed // within the scope of an nrp @@ -1400,7 +1455,7 @@ private bool ExecuteInitializeResource(InternalRenderGraphContext rgContext, Ren } else // Imported resource { - if (resInfo.clear && !resInfo.memoryLess && resources.forceManualClearOfResource) + if (resInfo.clear && !resInfo.createdMemoryless && resources.forceManualClearOfResource) { haveGfxCommandsBeenAddedToCmd |= resources.ClearResource(rgContext, res.iType, res.index); } @@ -1546,7 +1601,7 @@ void DetermineLoadStoreActions(ref NativePassData nativePass) currLoadAudit = new LoadAudit(LoadReason.ClearImported); #endif } - else if (resourceData.memoryLess) + else if (resourceData.createdMemoryless) { loadAction = RenderBufferLoadAction.DontCare; #if UNITY_ENABLE_CHECKS 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 0e918471d6c..7a76e4eecb2 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 @@ -767,12 +767,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 { @@ -1063,8 +1069,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); @@ -1271,8 +1278,16 @@ static bool CanMergeNativeSubPass(CompilerContextData contextData, ref NativePas flags = SubPassFlags.ReadOnlyDepth; } + // 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/Runtime/RenderGraph/Compiler/ResourcesData.cs b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Compiler/ResourcesData.cs index 5290b631e39..0474cb3c063 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Compiler/ResourcesData.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Compiler/ResourcesData.cs @@ -36,6 +36,7 @@ internal struct ResourceUnversionedData public readonly bool isImported; // Imported graph resource public bool memoryLess; // Never create the texture on GPU if it is allocated/freed within a renderpass + public readonly bool createdMemoryless; // Requested as memoryless, unlike memoryLess never cleared by the compiler public int lastGraphicsUsePassID; // Last non culled pass using this resource on the graphics queue, -1 if none public int lastAsyncComputeUsePassID; // Last non culled pass using this resource on the async compute queue, -1 if none public int tag; @@ -73,6 +74,7 @@ public ResourceUnversionedData(TextureResource rll, ref RenderTargetInfo info, r // Check if imported texture is memoryless memoryLess = desc.memoryless != RenderTextureMemoryless.None; + createdMemoryless = memoryLess; width = info.width; height = info.height; @@ -104,6 +106,7 @@ public ResourceUnversionedData(IRenderGraphResource rll, ref BufferDesc _, bool lastUsePassID = -1; lastWritePassID = -1; memoryLess = false; + createdMemoryless = false; lastGraphicsUsePassID = -1; lastAsyncComputeUsePassID = -1; @@ -137,6 +140,7 @@ public ResourceUnversionedData(IRenderGraphResource rll, ref RayTracingAccelerat lastUsePassID = -1; lastWritePassID = -1; memoryLess = false; + createdMemoryless = false; lastGraphicsUsePassID = -1; lastAsyncComputeUsePassID = -1; diff --git a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Debug/RenderGraphDebugSessionManager.QueryScope.ExecutionQuery.cs b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Debug/RenderGraphDebugSessionManager.QueryScope.ExecutionQuery.cs index d0f6120e796..7975db9e413 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Debug/RenderGraphDebugSessionManager.QueryScope.ExecutionQuery.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Debug/RenderGraphDebugSessionManager.QueryScope.ExecutionQuery.cs @@ -868,7 +868,7 @@ private static ResourceInfo ConvertResourceData(RenderGraph.DebugData debugData, analysis = new ResourceAnalysis { memorySizeBytes = memoryBytes, - memorySizeFormatted = FormatMemorySize(memoryBytes), + memorySizeFormatted = CoreUtils.FormatMemorySize(memoryBytes), bytesPerPixel = totalPixels > 0 ? memoryBytes / totalPixels : 0, totalPixels = totalPixels }; @@ -879,7 +879,7 @@ private static ResourceInfo ConvertResourceData(RenderGraph.DebugData debugData, analysis = new ResourceAnalysis { memorySizeBytes = memoryBytes, - memorySizeFormatted = FormatMemorySize(memoryBytes), + memorySizeFormatted = CoreUtils.FormatMemorySize(memoryBytes), stride = height, elementCount = width }; @@ -904,21 +904,6 @@ private static ResourceInfo ConvertResourceData(RenderGraph.DebugData debugData, analysis = analysis }; } - - private static string FormatMemorySize(long bytes) - { - const long KB = 1024; - const long MB = KB * 1024; - const long GB = MB * 1024; - - if (bytes >= GB) - return $"{bytes / (double)GB:F1} GB"; - if (bytes >= MB) - return $"{bytes / (double)MB:F1} MB"; - if (bytes >= KB) - return $"{bytes / (double)KB:F1} KB"; - return $"{bytes} B"; - } } } } diff --git a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraph.cs b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraph.cs index 9aeeaf10c3b..76d4c49fbf1 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraph.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraph.cs @@ -945,29 +945,23 @@ public RenderTargetInfo GetRenderTargetInfo(TextureHandle texture) return info; } - // Check if we already know at record time that the source and destination handles will have a different UV origin - // If this functions returns false you are guaranteed to always get identical uv origins at *execute* time because: - // - Both known and identical -> returns false -> identical at execute - // - Both unknown -> return false at record, compile succeeded resolving origins -> execute sees identical - // - Both unknown -> return false at record, compile failed resolving origins -> errors before execute returs - // Because of all this explanation needed, we keep this function internal it should generally not be relied on except - // in niche cases like to improve error messages etc. - internal bool UvOriginDifferAtRecordTime(in TextureHandle source, in TextureHandle destination) + // Returns true only if both UV origins are already known at record time and differ. + // False means no conflict is known at record time. Whether the origins match at *execute* time depends on the case: + // - Both known and identical -> identical at execute. + // - At least one Unknown (texture created in the graph rather than imported) -> resolved during compilation: + // - PropagateAttachmentOrientation strategy: the Unknown origin inherits the origin of the attachments it is used with. + // If that leads to a conflict, compilation fails before executing (only in builds with validity checks). + // - BottomLeft strategy: the Unknown origin resolves to BottomLeft without any validation, + // so a copy from such a texture to a known TopLeft destination is not rejected here and is not flipped. + internal bool UVOriginsKnownToDiffer(in TextureHandle source, in TextureHandle destination) { CheckNotUsedWhenExecuting(); - CheckNotUsedWhenIdle(); if (!source.IsValid() || !destination.IsValid()) throw new ArgumentException("Attempting to get uv origin of an invalid texture handle."); - // Reject if both textures have known but incompatible origins. - // If either origin is Unknown (i.e. a texture created within the graph rather than imported), the - // compiler will resolve and propagate the orientation later, so there is nothing to reject here. - // At first it may seem the compiler could decide these two textures get assigned different orientations - // and then we have a problem on execute but this will not happen as the compiler will error out and never execute. - // So theory we don't need to call this fucntion but it allows us to give slightly nicer errors at record time in some cases instead of at execute - // when the pass execute runs and relevant record-time context for debugging is lost. - // It also makes sure the blit can use copy in some cases where it is allowed as an optimization. + // Checking here gives a clearer error at record time, while the context for debugging is still available, + // and lets the blit use a copy as an optimization when the origins are known to match. if (SystemInfo.graphicsUVStartsAtTop) { var srcOrigin = m_Resources.GetTextureResource(source.handle).textureUVOrigin; @@ -1238,13 +1232,6 @@ void CheckNotUsedWhenActive() throw new InvalidOperationException(RenderGraphExceptionMessages.GetExceptionMessage(RenderGraphState.Active)); } - [Conditional("UNITY_ENABLE_CHECKS")] - void CheckNotUsedWhenIdle() - { - if (enableValidityChecks && m_RenderGraphState == RenderGraphState.Idle) - throw new InvalidOperationException(RenderGraphExceptionMessages.GetExceptionMessage(RenderGraphState.Active)); - } - /// /// Add a new Raster Render Pass to the Render Graph. Raster passes can execute rasterization workloads but cannot do other GPU work like copies or compute. /// diff --git a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphGlobalSettings.cs b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphGlobalSettings.cs index 659912db2a2..e9fe99d8f0e 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphGlobalSettings.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphGlobalSettings.cs @@ -59,10 +59,10 @@ public bool enableCompilationCaching set => this.SetValueAndNotify(ref m_EnableCompilationCaching, value); } - [RecreatePipelineOnChange , SerializeField, Tooltip("Enable validity checks of render graph in Editor and Development mode. Always disabled in Release build.")] + [RecreatePipelineOnChange , SerializeField, Tooltip("Enable validity checks of render graph in Editor and Development mode, and the Editor warnings of URP about loose-uniform writes to its constant buffers. Always disabled in Release build.")] private bool m_EnableValidityChecks = true; - /// Enable validity checks for render graph. Always disabled in Release mode. + /// Enable validity checks for render graph, and the Editor warnings of URP about loose-uniform writes to its constant buffers. Always disabled in Release mode. public bool enableValidityChecks { get => m_EnableValidityChecks; diff --git a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceRegistry.cs b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceRegistry.cs index dfdf0bdb0cb..15da4dcd278 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceRegistry.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceRegistry.cs @@ -49,10 +49,11 @@ public struct RenderTargetInfo /// Set to true if this render target should use memoryless storage. /// Mainly intended for the backbuffer depth on Metal iOS/tvOS/visionOS when PlayerSettings depth memoryless mode is /// enabled, and for XR eye textures that the provider requests as memoryless. - /// Memoryless resources can't be loaded or stored, so importing one forces discard on last use regardless of + /// Importing a memoryless resource forces discard on last use regardless of /// . Their contents only survive within a single native render - /// pass. This flag describes how the surface was created, so the graph can't compensate for it: a pass that loads - /// the contents after a native render pass boundary reads undefined data. + /// pass. On platforms that back memoryless surfaces with memory on demand, such as Vulkan, the graph stores and loads + /// the contents across a native render pass boundary instead, at the cost of the memory savings. On other platforms, + /// a pass that loads the contents after a native render pass boundary reads undefined data. /// public bool isMemoryless; } @@ -74,7 +75,7 @@ public struct ImportResourceParams /// Discard the imported texture the last time it is used by the graph. /// If MSAA enabled, only the multisampled version is discarded while the MSAA surface is always resolved. /// Fully discarding both multisampled and resolved data is not currently possible. - /// Always true for memoryless resources, whose contents can never be stored. See . + /// Always true for memoryless resources, whose contents are never kept after their last use in the graph. See . /// public bool discardOnLastUse; /// diff --git a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphUtilsBlit.cs b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphUtilsBlit.cs index 6281e6abcfa..9cc4d4a9201 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphUtilsBlit.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphUtilsBlit.cs @@ -88,10 +88,10 @@ public static bool IsFramebufferFetchSupportedOnCurrentPlatform(this RenderGraph return true; } - internal static bool UvOriginCopyCompatible(this RenderGraph graph, TextureHandle source, TextureHandle destination) + internal static bool UVOriginCopyCompatible(this RenderGraph graph, TextureHandle source, TextureHandle destination) { // Check early if copy cannot work because it would do a UV-origin flip. - return !graph.UvOriginDifferAtRecordTime(source, destination); + return !graph.UVOriginsKnownToDiffer(source, destination); } /// @@ -130,7 +130,7 @@ public static bool CanAddCopyPass(this RenderGraph graph, TextureHandle source, if ((int)sourceInfo.msaaSamples > 1 && !CanAddCopyPassMSAA(sourceInfo.bindMS)) return false; - return UvOriginCopyCompatible(graph, source, destination); + return UVOriginCopyCompatible(graph, source, destination); } class CopyPassData @@ -164,7 +164,7 @@ static void ValidateAddCopyPassParameters(RenderGraph graph, TextureHandle sourc if (isMSAA && !CanAddCopyPassMSAA(sourceInfo.bindMS)) throw new ArgumentException("Target does not support MSAA for AddCopyPass. Please use the blit alternative or use non MSAA textures."); - if (!UvOriginCopyCompatible(graph, source, destination)) + if (!UVOriginCopyCompatible(graph, source, destination)) throw new ArgumentException("AddCopyPass cannot perform a UV-origin flip. Source and destination textures have different UV origins. Use AddBlitPass instead which will automatically insert the correct flip."); } } diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Sampling/QuasiRandom.hlsl b/Packages/com.unity.render-pipelines.core/Runtime/Sampling/QuasiRandom.hlsl index fb88fe71731..36e7ea491dd 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Sampling/QuasiRandom.hlsl +++ b/Packages/com.unity.render-pipelines.core/Runtime/Sampling/QuasiRandom.hlsl @@ -168,11 +168,11 @@ struct QrngKronecker2D uint cranleyPattersonRot = cranleyPattersonSeed + 3646589397 * (dimension / 4); #ifdef QRNG_KRONECKER_ENHANCED_QUALITY // add small scale jitter as explained in paper - const float alphaJitter[] = { 2681146017, 685201898 }; + const uint alphaJitter[] = { 2681146017, 685201898 }; uint jitter = alphaJitter[dimension % 2] * shuffledSampleIndex; float amplitude = 0.05 * 0.78 / sqrt(2) * rsqrt(float(sampleIndex)); - cranleyPattersonRot += jitter * uint(amplitude); + cranleyPattersonRot += uint(jitter * amplitude); #endif // Kronecker sequence evaluation return UintToFloat01(cranleyPattersonRot + alphas[dimension % 4] * shuffledSampleIndex); diff --git a/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/AGENTS.md b/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/AGENTS.md new file mode 100644 index 00000000000..89502bbad99 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/AGENTS.md @@ -0,0 +1,4 @@ +# Unified Ray Tracing library + +- The lighting rules in `../Lighting/AGENTS.md` apply here. +- The exception is the backend support query in `RayTracingContext`, which reads the `SystemInfo` ray tracing and compute capabilities. diff --git a/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/AGENTS.md.meta b/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/AGENTS.md.meta new file mode 100644 index 00000000000..2d51a6363d6 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/AGENTS.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: de492f113030a4149a0b548b52de6963 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/CLAUDE.md b/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/CLAUDE.md new file mode 100644 index 00000000000..43c994c2d36 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/CLAUDE.md.meta b/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/CLAUDE.md.meta new file mode 100644 index 00000000000..5b18d1c0be8 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/CLAUDE.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: f728e7d4e63ab48f782214e8f3192a49 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Common/AccelStructAdapter.cs b/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Common/AccelStructAdapter.cs index 94281863801..bc6d5779695 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Common/AccelStructAdapter.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Common/AccelStructAdapter.cs @@ -148,7 +148,7 @@ public void AddInstance(UInt64 objectHandle, Component meshRendererOrTerrain, Sp } } - public void AddInstance(UInt64 objectHandle, Mesh mesh, Matrix4x4 localToWorldMatrix, Span perSubMeshMask, Span perSubMeshMaterialIDs, Span perSubMeshIsOpaque, uint renderingLayerMask) + public void AddInstance(UInt64 objectHandle, Mesh mesh, Matrix4x4 localToWorldMatrix, Span perSubMeshMask, Span perSubMeshMaterialIDs, Span perSubMeshIsOpaque, uint renderingLayerMask, int meshLod = 0) { int subMeshCount = mesh.subMeshCount; @@ -157,6 +157,7 @@ public void AddInstance(UInt64 objectHandle, Mesh mesh, Matrix4x4 localToWorldMa { var instanceDesc = new MeshInstanceDesc(mesh, i) { + meshLod = meshLod, localToWorldMatrix = localToWorldMatrix, mask = perSubMeshMask[i], opaqueGeometry = perSubMeshIsOpaque[i] diff --git a/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Common/AccelStructInstances.cs b/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Common/AccelStructInstances.cs index 560343ca95e..e27846d63f6 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Common/AccelStructInstances.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Common/AccelStructInstances.cs @@ -87,7 +87,7 @@ void AddInstance(BlockAllocator.Allocation slotAllocation, in MeshInstanceDesc m Debug.Assert(meshInstance.mesh != null, "targetRenderer.mesh is null"); GeometryPoolHandle geometryHandle; - if (!m_GeometryPool.Register(meshInstance.mesh, out geometryHandle)) + if (!m_GeometryPool.Register(meshInstance.mesh, meshInstance.meshLod, out geometryHandle)) throw new System.InvalidOperationException("Failed to allocate geometry data for instance"); m_GeometryPool.SendGpuCommands(); diff --git a/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Common/GeometryPool/GeometryPool.cs b/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Common/GeometryPool/GeometryPool.cs index 79d521cda4c..aeeeb87512f 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Common/GeometryPool/GeometryPool.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Common/GeometryPool/GeometryPool.cs @@ -90,6 +90,52 @@ internal struct GeometryPoolEntryDesc { public Mesh mesh; public GeometryPoolSubmeshData[] submeshData; + public int meshLod; + } + + // Identifies the geometry an entry stores. Caches compare the whole key, not just its hash. + internal struct GeometryPoolKey : IEquatable + { + public EntityId mesh; + public int meshLod; + + public GeometryPoolKey(in GeometryPoolEntryDesc entryDesc) + { + mesh = entryDesc.mesh.GetEntityId(); + meshLod = entryDesc.meshLod; + } + + public bool Equals(GeometryPoolKey other) => mesh.Equals(other.mesh) && meshLod == other.meshLod; + + public override bool Equals(object obj) => obj is GeometryPoolKey other && Equals(other); + + public override int GetHashCode() + { + var hash = HashFNV1A32.Create(); + hash.Append(mesh.GetHashCode()); + hash.Append(meshLod); + return hash.value; + } + } + + internal struct GeometryPoolEntryKey : IEquatable + { + public GeometryPoolKey geometry; + + // Only the materials are hashed: entries that differ only by materials store the same geometry. + public uint submeshDataHash; + + public bool Equals(GeometryPoolEntryKey other) => geometry.Equals(other.geometry) && submeshDataHash == other.submeshDataHash; + + public override bool Equals(object obj) => obj is GeometryPoolEntryKey other && Equals(other); + + public override int GetHashCode() + { + var hash = HashFNV1A32.Create(); + hash.Append(geometry.GetHashCode()); + hash.Append(submeshDataHash); + return hash.value; + } } // Geometry pool container. Contains a global set of geometry accessible from the GPU. @@ -166,7 +212,7 @@ public GeoPoolMeshChunk EncodeGPUEntry() public struct GeometrySlot { public uint refCount; - public uint hash; + public GeometryPoolKey key; public BlockAllocator.Allocation meshChunkTableAlloc; public NativeArray meshChunks; public bool hasGPUData; @@ -183,12 +229,11 @@ public struct GeometrySlot private struct GeoPoolEntrySlot { public uint refCount; - public uint hash; + public GeometryPoolEntryKey key; public int geoSlotHandle; public static readonly GeoPoolEntrySlot Invalid = new GeoPoolEntrySlot() { refCount = 0u, - hash = 0u, geoSlotHandle = InvalidHandle, }; @@ -256,11 +301,11 @@ private int GetFormatByteCount(VertexAttributeFormat format) BlockAllocator m_IndexAllocator; BlockAllocator m_MeshChunkTableAllocator; - NativeParallelHashMap m_MeshHashToGeoSlot; + NativeParallelHashMap m_GeometryKeyToGeoSlot; List m_GeoSlots; NativeList m_FreeGeoSlots; - NativeParallelHashMap m_GeoPoolEntryHashToSlot; + NativeParallelHashMap m_GeoPoolEntryKeyToSlot; NativeList m_GeoPoolEntrySlots; NativeList m_FreeGeoPoolEntrySlots; @@ -297,11 +342,11 @@ public GeometryPool(in GeometryPoolDesc desc, ComputeShader geometryPoolShader, m_DummyBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, 16, 4); var initialCapacity = 4096; - m_MeshHashToGeoSlot = new NativeParallelHashMap(initialCapacity, Allocator.Persistent); + m_GeometryKeyToGeoSlot = new NativeParallelHashMap(initialCapacity, Allocator.Persistent); m_GeoSlots = new List(); m_FreeGeoSlots = new NativeList(Allocator.Persistent); - m_GeoPoolEntryHashToSlot = new NativeParallelHashMap(initialCapacity, Allocator.Persistent); + m_GeoPoolEntryKeyToSlot = new NativeParallelHashMap(initialCapacity, Allocator.Persistent); m_GeoPoolEntrySlots = new NativeList(Allocator.Persistent); m_FreeGeoPoolEntrySlots = new NativeList(Allocator.Persistent); @@ -332,7 +377,7 @@ public void Dispose() m_MeshChunkTableAllocator.Dispose(); m_DummyBuffer.Dispose(); - m_MeshHashToGeoSlot.Dispose(); + m_GeometryKeyToGeoSlot.Dispose(); foreach (var geoSlot in m_GeoSlots) { if (geoSlot.valid) @@ -342,7 +387,7 @@ public void Dispose() m_FreeGeoSlots.Dispose(); - m_GeoPoolEntryHashToSlot.Dispose(); + m_GeoPoolEntryKeyToSlot.Dispose(); m_GeoPoolEntrySlots.Dispose(); m_FreeGeoPoolEntrySlots.Dispose(); @@ -398,7 +443,7 @@ private void DeallocateGeometrySlot(int geoSlotHandle) --geoSlot.refCount; if (geoSlot.refCount == 0) { - m_MeshHashToGeoSlot.Remove(geoSlot.hash); + m_GeometryKeyToGeoSlot.Remove(geoSlot.key); DeallocateGeometrySlot(ref geoSlot); m_FreeGeoSlots.Add(geoSlotHandle); } @@ -429,9 +474,10 @@ private void ReallocateMeshChunkTableBuffer(int newCapacity) m_MaxMeshChunkTableEntriesCount = newCapacity; } - private bool AllocateGeo(Mesh mesh, out int allocationHandle) + private bool AllocateGeo(in GeometryPoolEntryDesc entryDesc, out int allocationHandle) { - uint meshHash = (uint)mesh.GetHashCode(); + Mesh mesh = entryDesc.mesh; + var geometryKey = new GeometryPoolKey(entryDesc); int indexCount = 0; for (int submeshIndex = 0; submeshIndex < mesh.subMeshCount; ++submeshIndex) @@ -439,10 +485,10 @@ private bool AllocateGeo(Mesh mesh, out int allocationHandle) indexCount += (int)mesh.GetIndexCount(submeshIndex); } - if (m_MeshHashToGeoSlot.TryGetValue(meshHash, out allocationHandle)) + if (m_GeometryKeyToGeoSlot.TryGetValue(geometryKey, out allocationHandle)) { var geoSlot = m_GeoSlots[allocationHandle]; - Assertions.Assert.IsTrue(geoSlot.hash == meshHash); + Assertions.Assert.IsTrue(geoSlot.key.Equals(geometryKey)); Assertions.Assert.IsTrue(geoSlot.meshChunkTableAlloc.block.count == mesh.subMeshCount); ++geoSlot.refCount; @@ -453,7 +499,7 @@ private bool AllocateGeo(Mesh mesh, out int allocationHandle) allocationHandle = InvalidHandle; var newSlot = GeometrySlot.Invalid; newSlot.refCount = 1; - newSlot.hash = meshHash; + newSlot.key = geometryKey; bool allocationSuccess = true; @@ -472,13 +518,14 @@ private bool AllocateGeo(Mesh mesh, out int allocationHandle) newSlot.meshChunks = new NativeArray(mesh.subMeshCount, Allocator.Persistent); for (int submeshIndex = 0; submeshIndex < mesh.subMeshCount; ++submeshIndex) { - SubMeshDescriptor submeshDescriptor = mesh.GetSubMesh(submeshIndex); + int submeshVertexCount = mesh.GetSubMesh(submeshIndex).vertexCount; + int submeshIndexCount = (int)mesh.GetIndexCount(submeshIndex, entryDesc.meshLod); var newMeshChunk = MeshChunk.Invalid; - newMeshChunk.vertexAlloc = m_VertexAllocator.Allocate(submeshDescriptor.vertexCount); + newMeshChunk.vertexAlloc = m_VertexAllocator.Allocate(submeshVertexCount); if (!newMeshChunk.vertexAlloc.valid) { - newMeshChunk.vertexAlloc = m_VertexAllocator.GrowAndAllocate(submeshDescriptor.vertexCount, GraphicsHelpers.MaxElementCount(GetVertexByteSize()), out int oldCapacity, out int newCapacity); + newMeshChunk.vertexAlloc = m_VertexAllocator.GrowAndAllocate(submeshVertexCount, GraphicsHelpers.MaxElementCount(GetVertexByteSize()), out int oldCapacity, out int newCapacity); if (!newMeshChunk.vertexAlloc.valid) throw new UnifiedRayTracingException($"Can't allocate a GraphicsBuffer bigger than {GraphicsHelpers.MaxGraphicsBufferSizeInGigaBytes:F1}GB", UnifiedRayTracingError.GraphicsBufferAllocationFailed); @@ -487,10 +534,10 @@ private bool AllocateGeo(Mesh mesh, out int allocationHandle) m_MaxVertCounts = newCapacity; } - newMeshChunk.indexAlloc = m_IndexAllocator.Allocate(submeshDescriptor.indexCount); + newMeshChunk.indexAlloc = m_IndexAllocator.Allocate(submeshIndexCount); if (!newMeshChunk.indexAlloc.valid) { - newMeshChunk.indexAlloc = m_IndexAllocator.GrowAndAllocate(submeshDescriptor.indexCount, GraphicsHelpers.MaxElementCount(sizeof(int)), out int oldCapacity, out int newCapacity); + newMeshChunk.indexAlloc = m_IndexAllocator.GrowAndAllocate(submeshIndexCount, GraphicsHelpers.MaxElementCount(sizeof(int)), out int oldCapacity, out int newCapacity); if (!newMeshChunk.indexAlloc.valid) throw new UnifiedRayTracingException($"Can't allocate a GraphicsBuffer bigger than {GraphicsHelpers.MaxGraphicsBufferSizeInGigaBytes:F1}GB", UnifiedRayTracingError.GraphicsBufferAllocationFailed); @@ -522,7 +569,7 @@ private bool AllocateGeo(Mesh mesh, out int allocationHandle) m_GeoSlots[allocationHandle] = newSlot; } - m_MeshHashToGeoSlot.Add(newSlot.hash, allocationHandle); + m_GeometryKeyToGeoSlot.Add(newSlot.key, allocationHandle); return true; } @@ -533,7 +580,7 @@ private void DeallocateGeoPoolEntrySlot(GeometryPoolHandle handle) --slot.refCount; if (slot.refCount == 0) { - m_GeoPoolEntryHashToSlot.Remove(slot.hash); + m_GeoPoolEntryKeyToSlot.Remove(slot.key); DeallocateGeoPoolEntrySlot(ref slot); m_FreeGeoPoolEntrySlots.Add(handle); } @@ -581,8 +628,9 @@ public int GetInstanceGeometryIndex(Mesh mesh) return GetEntryGeomAllocation(GetHandle(mesh)).meshChunkTableAlloc.block.offset; } - private void UpdateGeoGpuState(Mesh mesh, GeometryPoolHandle handle) + private void UpdateGeoGpuState(in GeometryPoolEntryDesc entryDesc, GeometryPoolHandle handle) { + Mesh mesh = entryDesc.mesh; var entrySlot = m_GeoPoolEntrySlots[handle.index]; var geoSlot = m_GeoSlots[entrySlot.geoSlotHandle]; @@ -623,7 +671,7 @@ private void UpdateGeoGpuState(Mesh mesh, GeometryPoolHandle handle) AddIndexUpdateCommand( cmdBuffer, mesh.indexFormat, buffer, targetMeshChunk.indexAlloc, submeshDescriptor.firstVertex, - submeshDescriptor.indexStart, submeshDescriptor.indexCount, 0, + (int)mesh.GetIndexStart(submeshIndex, entryDesc.meshLod), (int)mesh.GetIndexCount(submeshIndex, entryDesc.meshLod), 0, m_GlobalIndexBuffer); meshChunkAllocationTable[submeshIndex] = targetMeshChunk.EncodeGPUEntry(); @@ -637,38 +685,30 @@ private void UpdateGeoGpuState(Mesh mesh, GeometryPoolHandle handle) } } - private uint FNVHash(uint prevHash, uint dword) - { - //https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function - const uint fnvPrime = 0x811C9DC5; - for (int i = 0; i < 4; ++i) - { - prevHash ^= ((dword >> (i * 8)) & 0xFF); - prevHash *= fnvPrime; - } - return prevHash; - } - - private uint CalculateClusterHash(Mesh mesh, GeometryPoolSubmeshData[] submeshData) + private static GeometryPoolEntryKey CreateEntryKey(in GeometryPoolEntryDesc entryDesc) { - uint meshHash = (uint)mesh.GetHashCode(); - uint clusterHash = meshHash; - if (submeshData != null) + var submeshDataHash = HashFNV1A32.Create(); + if (entryDesc.submeshData != null) { - foreach (var data in submeshData) + foreach (var data in entryDesc.submeshData) { - clusterHash = FNVHash(clusterHash, (uint)data.submeshIndex); - clusterHash = FNVHash(clusterHash, (uint)(data.material == null ? 0 : data.material.GetHashCode())); + submeshDataHash.Append(data.submeshIndex); + submeshDataHash.Append(data.material == null ? 0 : data.material.GetHashCode()); } } - return clusterHash; + + return new GeometryPoolEntryKey() + { + geometry = new GeometryPoolKey(entryDesc), + submeshDataHash = (uint)submeshDataHash.value + }; } public GeometryPoolHandle GetHandle(Mesh mesh) { - uint geoPoolEntryHash = CalculateClusterHash(mesh, null); + var entryKey = CreateEntryKey(new GeometryPoolEntryDesc() { mesh = mesh }); - if (m_GeoPoolEntryHashToSlot.TryGetValue(geoPoolEntryHash, out GeometryPoolHandle outHandle)) + if (m_GeoPoolEntryKeyToSlot.TryGetValue(entryKey, out GeometryPoolHandle outHandle)) return outHandle; else return GeometryPoolHandle.Invalid; @@ -697,6 +737,16 @@ public bool Register(Mesh mesh, out GeometryPoolHandle outHandle) }, out outHandle); } + public bool Register(Mesh mesh, int meshLod, out GeometryPoolHandle outHandle) + { + return Register(new GeometryPoolEntryDesc() + { + mesh = mesh, + submeshData = null, + meshLod = meshLod + }, out outHandle); + } + public bool Register(in GeometryPoolEntryDesc entryDesc, out GeometryPoolHandle outHandle) { outHandle = GeometryPoolHandle.Invalid; @@ -706,15 +756,15 @@ public bool Register(in GeometryPoolEntryDesc entryDesc, out GeometryPoolHandle } Mesh mesh = entryDesc.mesh; - uint geoPoolEntryHash = CalculateClusterHash(entryDesc.mesh, entryDesc.submeshData); + var entryKey = CreateEntryKey(entryDesc); - if (m_GeoPoolEntryHashToSlot.TryGetValue(geoPoolEntryHash, out outHandle)) + if (m_GeoPoolEntryKeyToSlot.TryGetValue(entryKey, out outHandle)) { GeoPoolEntrySlot geoPoolEntrySlot = m_GeoPoolEntrySlots[outHandle.index]; - Assertions.Assert.IsTrue(geoPoolEntrySlot.hash == geoPoolEntryHash); + Assertions.Assert.IsTrue(geoPoolEntrySlot.key.Equals(entryKey)); GeometrySlot geoSlot = m_GeoSlots[geoPoolEntrySlot.geoSlotHandle]; - Assertions.Assert.IsTrue(geoSlot.hash == (uint)mesh.GetHashCode()); + Assertions.Assert.IsTrue(geoSlot.key.Equals(entryKey.geometry)); ++geoPoolEntrySlot.refCount; m_GeoPoolEntrySlots[outHandle.index] = geoPoolEntrySlot; @@ -723,7 +773,7 @@ public bool Register(in GeometryPoolEntryDesc entryDesc, out GeometryPoolHandle var newSlot = GeoPoolEntrySlot.Invalid; newSlot.refCount = 1; - newSlot.hash = geoPoolEntryHash; + newSlot.key = entryKey; // Validate submesh information var validSubmeshData = new List(mesh.subMeshCount); @@ -741,7 +791,7 @@ public bool Register(in GeometryPoolEntryDesc entryDesc, out GeometryPoolHandle } } - if (!AllocateGeo(mesh, out newSlot.geoSlotHandle)) + if (!AllocateGeo(entryDesc, out newSlot.geoSlotHandle)) { DeallocateGeoPoolEntrySlot(ref newSlot); return false; @@ -761,8 +811,8 @@ public bool Register(in GeometryPoolEntryDesc entryDesc, out GeometryPoolHandle m_GeoPoolEntrySlots[outHandle.index] = newSlot; } - m_GeoPoolEntryHashToSlot.Add(newSlot.hash, outHandle); - UpdateGeoGpuState(mesh, outHandle); + m_GeoPoolEntryKeyToSlot.Add(newSlot.key, outHandle); + UpdateGeoGpuState(entryDesc, outHandle); return true; } diff --git a/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Common/Utilities/Utils.cs b/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Common/Utilities/Utils.cs index ea9c7f66f42..b0c01947ac8 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Common/Utilities/Utils.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Common/Utilities/Utils.cs @@ -32,6 +32,12 @@ public static void EnsureMeshHasRawBufferTarget(Mesh mesh) } #endif + [Conditional("UNITY_ASSERTIONS")] + public static void CheckMeshLod(in MeshInstanceDesc meshInstance) + { + CheckArgRange(meshInstance.meshLod, 0, Math.Max(1, meshInstance.mesh.lodCount), "meshInstance.meshLod"); + } + [Conditional("UNITY_ASSERTIONS")] public static void CheckArgIsNotNull(System.Object obj, string argName) { diff --git a/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Compute/ComputeRayTracingAccelStruct.cs b/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Compute/ComputeRayTracingAccelStruct.cs index a3e736fa712..a4a7c37acda 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Compute/ComputeRayTracingAccelStruct.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Compute/ComputeRayTracingAccelStruct.cs @@ -77,8 +77,9 @@ public int AddInstance(MeshInstanceDesc meshInstance) Utils.CheckArgIsNotNull(meshInstance.mesh, "meshInstance.mesh"); Utils.CheckArg(meshInstance.mesh.HasVertexAttribute(VertexAttribute.Position), "Cant use a mesh buffer that has no positions."); Utils.CheckArgRange(meshInstance.subMeshIndex, 0, meshInstance.mesh.subMeshCount, "meshInstance.subMeshIndex"); + Utils.CheckMeshLod(meshInstance); - var blas = GetOrAllocateMeshBlas(meshInstance.mesh, meshInstance.subMeshIndex); + var blas = GetOrAllocateMeshBlas(meshInstance.mesh, meshInstance.subMeshIndex, meshInstance.meshLod); blas.IncRef(); FreeTopLevelAccelStruct(); @@ -228,16 +229,17 @@ void FreeTopLevelAccelStruct() m_TopLevelAccelStruct = null; } - MeshBlas GetOrAllocateMeshBlas(Mesh mesh, int subMeshIndex) + MeshBlas GetOrAllocateMeshBlas(Mesh mesh, int subMeshIndex, int meshLod) { - MeshBlas blas; - if (m_MeshBlases.TryGetValue((mesh.GetHashCode(), subMeshIndex), out blas)) + var geomKey = (mesh.GetEntityId(), subMeshIndex, meshLod); + if (m_MeshBlases.TryGetValue(geomKey, out MeshBlas blas)) return blas; blas = new MeshBlas(); - AllocateMeshBlas(mesh, subMeshIndex, blas); + blas.geomKey = geomKey; + AllocateMeshBlas(mesh, subMeshIndex, meshLod, blas); - m_MeshBlases[(mesh.GetHashCode(), subMeshIndex)] = blas; + m_MeshBlases[geomKey] = blas; return blas; } @@ -289,12 +291,11 @@ ProceduralBlas AllocateProceduralBlas(GraphicsBuffer aabbBuffer, uint aabbCount) } // throws UnifiedRayTracingException - void AllocateMeshBlas(Mesh mesh, int submeshIndex, MeshBlas blas) + void AllocateMeshBlas(Mesh mesh, int submeshIndex, int meshLod, MeshBlas blas) { blas.blasVertices = BlockAllocator.Allocation.Invalid; blas.bvhInternalNodesAlloc = BlockAllocator.Allocation.Invalid; blas.bvhLeafNodesAlloc = BlockAllocator.Allocation.Invalid; - blas.geomKey = (mesh.GetHashCode(), submeshIndex); var bvhNodeSizeInDwords = RadeonRaysAPI.BvhInternalNodeSizeInDwords(); @@ -323,18 +324,26 @@ void AllocateMeshBlas(Mesh mesh, int submeshIndex, MeshBlas blas) meshBuildInfo.baseVertex = 0; meshBuildInfo.triangleIndices = indexBuffer; meshBuildInfo.vertexCount = (uint)blas.blasVertices.block.count; - meshBuildInfo.triangleCount = (uint)submeshDescriptor.indexCount / 3; - meshBuildInfo.indicesStartOffset = submeshDescriptor.indexStart; + meshBuildInfo.triangleCount = mesh.GetIndexCount(submeshIndex, meshLod) / 3; + meshBuildInfo.indicesStartOffset = (int)mesh.GetIndexStart(submeshIndex, meshLod); meshBuildInfo.baseIndex = -submeshDescriptor.firstVertex; meshBuildInfo.indexFormat = mesh.indexFormat == IndexFormat.UInt32 ? RadeonRays.IndexFormat.Int32 : RadeonRays.IndexFormat.Int16; meshBuildInfo.vertexStride = 3; blas.buildInfo = meshBuildInfo; + if (IsEmpty(blas)) + { + blas.bvhInternalNodesAlloc = AllocateBlasInternalNodes(0); + blas.bvhLeafNodesAlloc = AllocateBlasLeafNodes(0); + blas.bvhBuilt = true; + return; + } + #if UNITY_EDITOR if (m_UseCpuBuild) { blas.indicesForCpuBuild = new List(); - mesh.GetTriangles(blas.indicesForCpuBuild, submeshIndex, false); + mesh.GetTriangles(blas.indicesForCpuBuild, submeshIndex, meshLod, false); blas.baseIndexForCpuBuild = -submeshDescriptor.firstVertex; blas.verticesForCpuBuild = new List(); mesh.GetVertices(blas.verticesForCpuBuild); @@ -393,7 +402,12 @@ GraphicsBuffer LoadPositionBuffer(Mesh mesh, out int stride, out int offset) return buffer; } - void DeleteMeshBlas((int mesh, int subMeshIndex) geomKey, MeshBlas blas) + static bool IsEmpty(Blas blas) + { + return blas is MeshBlas { buildInfo: { triangleCount: 0 } }; + } + + void DeleteMeshBlas((EntityId mesh, int subMeshIndex, int meshLod) geomKey, MeshBlas blas) { m_BlasInternalNodesAllocator.FreeAllocation(blas.bvhInternalNodesAlloc); blas.bvhInternalNodesAlloc = BlockAllocator.Allocation.Invalid; @@ -559,9 +573,16 @@ void CheckProceduralBlasConsistency(CommandBuffer cmd, ProceduralBlas procedural void BuildTopLevelAccelStruct(CommandBuffer cmd, GraphicsBuffer scratchBuffer) { - var radeonRaysInstances = new RadeonRays.Instance[m_RadeonInstances.Count]; - int i = 0; + var nonEmptyInstances = new List(m_RadeonInstances.Count); foreach (var instance in m_RadeonInstances.Values) + { + if (!IsEmpty(instance.blas)) + nonEmptyInstances.Add(instance); + } + + var radeonRaysInstances = new RadeonRays.Instance[nonEmptyInstances.Count]; + int i = 0; + foreach (var instance in nonEmptyInstances) { if (instance.blas is MeshBlas meshBlas) { @@ -587,7 +608,7 @@ void BuildTopLevelAccelStruct(CommandBuffer cmd, GraphicsBuffer scratchBuffer) #if UNITY_EDITOR if (m_UseCpuBuild) - m_TopLevelAccelStruct = CpuBuildForTopLevelAccelStruct(cmd, radeonRaysInstances); + m_TopLevelAccelStruct = CpuBuildForTopLevelAccelStruct(cmd, nonEmptyInstances, radeonRaysInstances); else #endif m_TopLevelAccelStruct = m_RadeonRaysAPI.BuildSceneAccelStruct(cmd, m_BlasInternalNodesBuffer, radeonRaysInstances, scratchBuffer); @@ -704,11 +725,11 @@ void CpuBuildForBottomLevelAccelStruct(CommandBuffer cmd, Blas blas) } - TopLevelAccelStruct CpuBuildForTopLevelAccelStruct(CommandBuffer cmd, RadeonRays.Instance[] radeonRaysInstances) + TopLevelAccelStruct CpuBuildForTopLevelAccelStruct(CommandBuffer cmd, List instances, RadeonRays.Instance[] radeonRaysInstances) { - var prims = new GpuBvhPrimitiveDescriptor[m_RadeonInstances.Count]; + var prims = new GpuBvhPrimitiveDescriptor[instances.Count]; int i = 0; - foreach (var instance in m_RadeonInstances.Values) + foreach (var instance in instances) { Blas blas = instance.blas; AABB aabb = blas.aabbForCpuBuild; @@ -732,7 +753,7 @@ TopLevelAccelStruct CpuBuildForTopLevelAccelStruct(CommandBuffer cmd, RadeonRays i++; } - if (m_RadeonInstances.Count != 0) + if (instances.Count != 0) { var options = ConvertFlagsToCpuBuild(m_BuildFlags, true); @@ -910,7 +931,7 @@ void CheckInstanceHandleIsValid(int instanceHandle) #endif readonly ReferenceCounter m_Counter; - readonly Dictionary<(int mesh, int subMeshIndex), MeshBlas> m_MeshBlases; + readonly Dictionary<(EntityId mesh, int subMeshIndex, int meshLod), MeshBlas> m_MeshBlases; readonly Dictionary m_ProceduralBlases; internal BlockAllocator m_BlasInternalNodesAllocator; GraphicsBuffer m_BlasInternalNodesBuffer; @@ -954,7 +975,7 @@ sealed class ProceduralBlas : Blas sealed class MeshBlas : Blas { - public (int meshHash, int subMeshIndex) geomKey; + public (EntityId mesh, int subMeshIndex, int meshLod) geomKey; public MeshBuildInfo buildInfo; public BlockAllocator.Allocation blasVertices; #if UNITY_EDITOR diff --git a/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Hardware/HardwareRayTracingAccelStruct.cs b/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Hardware/HardwareRayTracingAccelStruct.cs index 9cf830ec312..37352fcb911 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Hardware/HardwareRayTracingAccelStruct.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Hardware/HardwareRayTracingAccelStruct.cs @@ -48,8 +48,10 @@ public int AddInstance(MeshInstanceDesc meshInstance) Utils.CheckArgIsNotNull(meshInstance.mesh, "meshInstance.mesh"); Utils.CheckArg(meshInstance.mesh.HasVertexAttribute(VertexAttribute.Position), "Cant use a mesh buffer that has no positions."); Utils.CheckArgRange(meshInstance.subMeshIndex, 0, meshInstance.mesh.subMeshCount, "meshInstance.subMeshIndex"); + Utils.CheckMeshLod(meshInstance); var instanceDesc = new RayTracingMeshInstanceConfig(meshInstance.mesh, (uint)meshInstance.subMeshIndex, null); + instanceDesc.meshLod = meshInstance.meshLod; instanceDesc.mask = meshInstance.mask; instanceDesc.enableTriangleCulling = meshInstance.enableTriangleCulling; instanceDesc.frontTriangleCounterClockwise = meshInstance.frontTriangleCounterClockwise; diff --git a/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/IRayTracingAccelStruct.cs b/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/IRayTracingAccelStruct.cs index 36c97720724..903b2d8b7a7 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/IRayTracingAccelStruct.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/IRayTracingAccelStruct.cs @@ -20,6 +20,14 @@ public struct MeshInstanceDesc /// public int subMeshIndex; + /// + /// The Mesh LOD level used to build this instance's geometry. Default value: 0. + /// + /// + /// The value must be less than . For a Mesh without Mesh LODs, use 0. + /// + public int meshLod; + /// /// The transformation matrix of the instance. /// @@ -70,6 +78,7 @@ public MeshInstanceDesc(Mesh mesh, int subMeshIndex = 0) { this.mesh = mesh; this.subMeshIndex = subMeshIndex; + meshLod = 0; localToWorldMatrix = Matrix4x4.identity; mask = 0xFFFFFFFF; instanceID = 0xFFFFFFFF; diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Unity.RenderPipelines.Core.Runtime.asmdef b/Packages/com.unity.render-pipelines.core/Runtime/Unity.RenderPipelines.Core.Runtime.asmdef index 0f25ae46bfe..3869746a278 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Unity.RenderPipelines.Core.Runtime.asmdef +++ b/Packages/com.unity.render-pipelines.core/Runtime/Unity.RenderPipelines.Core.Runtime.asmdef @@ -50,6 +50,11 @@ "expression": "1.0.0", "define": "ENABLE_METALFX_MODULE" }, + { + "name": "com.unity.modules.intelxess", + "expression": "1.0.0", + "define": "ENABLE_INTELXESS_MODULE" + }, { "name": "com.unity.modules.physics", "expression": "1.0.0", diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/Upscaling.cs b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/Upscaling.cs index a8778b18bb9..55d73d8252b 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/Upscaling.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/Upscaling.cs @@ -294,7 +294,7 @@ public Upscaling( UpscalerOptions? options = optionsNotFound ? null: upscalerOptions[optionsIndex]; // construct upscaler (always parameterless; options are owned by the framework, not the instance) - IUpscaler upscaler = (IUpscaler)Activator.CreateInstance(upscalerType); + IUpscaler upscaler = (IUpscaler)Activator.CreateInstance(upscalerType)!; // The registered ID is what assets serialize, so an upscaler disagreeing with it would never resolve. if (upscaler.upscalerId != upscalerId) diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/XeSSIUpscaler.cs b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/XeSSIUpscaler.cs new file mode 100644 index 00000000000..6e1cb3f9143 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/XeSSIUpscaler.cs @@ -0,0 +1,338 @@ +using UnityEngine; +using UnityEngine.Experimental.Rendering; +using UnityEngine.Rendering; +using UnityEngine.Rendering.RenderGraphModule; +#if ENABLE_XESS && ENABLE_INTELXESS_MODULE +using UnityEngine.Intel; +#endif + +#if UNITY_EDITOR +using UnityEditor; +#endif + +#if ENABLE_XESS && ENABLE_INTELXESS_MODULE + +#if UNITY_EDITOR +[InitializeOnLoad] +#endif +internal static class RegisterXeSS +{ + static RegisterXeSS() => UpscalerRegistry.Register(XeSSIUpscaler.registeredId, XeSSIUpscaler.registeredName); + + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] + static void InitRuntime() => UpscalerRegistry.Register(XeSSIUpscaler.registeredId, XeSSIUpscaler.registeredName); +} + +internal class XeSSIUpscalerContext : PluginUpscalerContext +{ + public XeSSQuality createdWithQuality { get; } + + public Vector2Int createdWithMaxRenderSize { get; private set; } + + // Note that this flag contains e.g., validity of responsive mask and exposure mask parameters + // so we don't need separate fields for them. + public XeSSInitializationFlags createdWithFlags { get; private set; } + + public XeSSIUpscalerContext(XeSSOptions options, Vector2Int displayResolution) + : base(displayResolution) + { + createdWithQuality = options.xessQualityMode; + } + + public XeSSNativeContext EnsureNativeContext(CommandBuffer cmd, XeSSUpscalerCommandInitializationData settings) + { + var requestedMaxRenderSize = new Vector2Int((int)settings.maxRenderSizeWidth, (int)settings.maxRenderSizeHeight); + bool recreate = createdWithMaxRenderSize != requestedMaxRenderSize || createdWithFlags != settings.xessFlags; + if (m_NativeContext != null && recreate) + { + DestroyNativeContext(cmd, m_NativeContext); + m_NativeContext = null; + } + if (m_NativeContext == null) + { + m_NativeContext = GraphicsDevice.device.CreateNativeContext(cmd, settings); + createdWithMaxRenderSize = requestedMaxRenderSize; + createdWithFlags = settings.xessFlags; + } + return m_NativeContext; + } + + protected override void DestroyNativeContext(CommandBuffer cmd, XeSSNativeContext context) + { + GraphicsDevice.device.DestroyNativeContext(cmd, context); + } + + protected override bool ValidateOptions(XeSSOptions options) + { + // Checks state changes that require context recreation. + return options.xessQualityMode == createdWithQuality; + } +} + +#if UNITY_EDITOR +[UpscalerSupportedBuildTarget(BuildTarget.StandaloneWindows, graphicsDeviceTypes = new[] { GraphicsDeviceType.Direct3D11, GraphicsDeviceType.Direct3D12, GraphicsDeviceType.Vulkan })] +#endif +internal class XeSSIUpscaler : AbstractUpscaler +{ + public static readonly string registeredId = "intel.xess"; + public static readonly string registeredName = "XeSS Super Resolution"; + +#region XESS_UTILITIES + static bool CheckXeSSFeatureAvailable() + { + if (!XeSSUnityPlugin.Load()) + { + Debug.LogWarning("Failed to load XeSSUnityPlugin."); + return false; + } + + var device = GraphicsDevice.CreateGraphicsDevice(); + if (device == null) + { + Debug.LogWarning("XeSSUnityPlugin failed to create its internal device."); + return false; + } + + return device.IsFeatureAvailable(GraphicsDeviceFeature.XeSSUpscale); + } + + private bool IsSupportedOnDevice() + { + if (Debug.isDebugBuild && !m_XeSSReady && !m_WarnedUnsupportedDevice) + { + Debug.LogWarning("XeSS Super Resolution is not supported on current device."); + m_WarnedUnsupportedDevice = true; + return false; + } + if (Debug.isDebugBuild) + m_WarnedUnsupportedDevice = false; + return m_XeSSReady; + } +#endregion // XESS_UTILITIES + +#region RENDERGRAPH_INTERFACE_DATA + class XeSSGraphData + { + public XeSSIUpscalerContext upscalerContext; + public XeSSUpscalerCommandInitializationData initSettings; + public XeSSUpscalerCommandExecutionData execData; + public Vector2 motionVectorScale; + public TextureHandle colorInput; + public TextureHandle depth; + public TextureHandle motionVectors; + public TextureHandle exposure; + public TextureHandle responsiveMask; + public TextureHandle colorOutput; + }; +#endregion + +#region IUPSCALER_INTERFACE + public XeSSIUpscaler() + { + m_XeSSReady = CheckXeSSFeatureAvailable(); + } + + public override string upscalerId => registeredId; + public override string name => registeredName; + public override bool isSupportedOnDevice => IsSupportedOnDevice(); + public override bool isTemporal => true; + public override bool supportsSharpening => false; + public override bool hasQualityMode => true; + public override ReactiveMaskSource reactiveMaskSource => ReactiveMaskSource.Color; + + public override IUpscalerContext CreateContext(UpscalerOptions options, Vector2Int displayResolution) + { + if (!m_XeSSReady || options is not XeSSOptions xessOptions) + return null; + + return new XeSSIUpscalerContext(xessOptions, displayResolution); + } + + public override void CalculateJitter(int frameIndex, float upscaleRatio, out Vector2 jitter, out bool allowScaling) + { + if (m_XeSSReady) + { + const float k_BasePhaseCount = 8.0f; + int numPhases = Mathf.FloorToInt(k_BasePhaseCount * upscaleRatio * upscaleRatio + 0.5f); + + int haltonIndex = (frameIndex % numPhases) + 1; + float x = HaltonSequence.Get(haltonIndex, 2) - 0.5f; + float y = HaltonSequence.Get(haltonIndex, 3) - 0.5f; + + jitter = new Vector2(x, y); + } + else + { + jitter = Vector2.zero; + } + allowScaling = false; + } + + public override UpscalerResolutionInfo GetResolutionInfo(Vector2Int displayResolution, UpscalerOptions options) + { + var xessOptions = options as XeSSOptions; + if (!m_XeSSReady || xessOptions == null) + return UpscalerResolutionInfo.Fixed(displayResolution); + + UpscalerResolutionInfo info; + if (xessOptions.resolutionMode == UpscalerResolutionMode.CustomScaling) + { + info = base.GetResolutionInfo(displayResolution, options); + } + else + { + info = GraphicsDevice.device.GetRenderResolutionFromQualityMode(xessOptions.xessQualityMode, + (uint)displayResolution.x, (uint)displayResolution.y, + out uint renderWidth, out uint renderHeight) + ? UpscalerResolutionInfo.Fixed(new Vector2Int((int)renderWidth, (int)renderHeight)) + : UpscalerResolutionInfo.Fixed(displayResolution); // SDK/device not ready + } + + return info; + } + + public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) + { + if (!m_XeSSReady) + return; + + UpscalingIO io = frameData.Get(); + + var xessOptions = io.options as XeSSOptions; + + var upscalerContext = io.context as XeSSIUpscalerContext; + if (upscalerContext == null) + { + Debug.LogWarning("XeSSIUpscaler: No valid context provided via io.context. Skipping upscaling."); + return; + } + + TextureHandle outputColor; + { + TextureDesc inputDesc = io.cameraColor.GetDescriptor(renderGraph); + TextureDesc outputDesc = inputDesc; + outputDesc.width = io.postUpscaleResolution.x; + outputDesc.height = io.postUpscaleResolution.y; + outputDesc.format = GraphicsFormatUtility.GetLinearFormat(inputDesc.format); + outputDesc.msaaSamples = MSAASamples.None; + outputDesc.useMipMap = false; + outputDesc.autoGenerateMips = false; + outputDesc.useDynamicScale = false; + outputDesc.anisoLevel = 0; + outputDesc.discardBuffer = false; + outputDesc.enableRandomWrite = true; // compute shader resource + outputDesc.name = "_XeSSOutputTarget"; + outputDesc.clearBuffer = false; + outputDesc.filterMode = FilterMode.Bilinear; + + outputColor = renderGraph.CreateTexture(outputDesc); + } + + using (var builder = renderGraph.AddUnsafePass("XeSS", out XeSSGraphData passData, new ProfilingSampler("XeSS"))) + { + bool useNdcVelocity = io.motionVectorDomain == UpscalingIO.MotionVectorDomain.NDC; + // Note: Don't use exposure texture. URP does not provide it and how HDRP uses it does not play well with how XeSS samples it. + const bool useExposureTexture = false;// io.exposureTexture.IsValid(); + bool hasResponsiveMaskTexture = io.reactiveMask.IsValid(); + float motionVectorSign = io.motionVectorDirection == UpscalingIO.MotionVectorDirection.PreviousFrameToCurrentFrame ? -1.0f : 1.0f; + float motionVectorScaleX = useNdcVelocity ? io.motionVectorTextureSize.x : 1.0f; + float motionVectorScaleY = useNdcVelocity ? io.motionVectorTextureSize.y : 1.0f; + + passData.upscalerContext = upscalerContext; + + // Fill init data always, but EnsureNativeContext rarely recreates the native context + // therefore it won't cause reallocation of native context every frame. + { + bool displayResolutionMotionVectors = io.motionVectorTextureSize.x == io.postUpscaleResolution.x && + io.motionVectorTextureSize.y == io.postUpscaleResolution.y; + passData.initSettings = new XeSSUpscalerCommandInitializationData(); + passData.initSettings.SetFlag(XeSSInitializationFlags.HighResolutionMotionVector, displayResolutionMotionVectors); + passData.initSettings.SetFlag(XeSSInitializationFlags.InvertedDepth, io.invertedDepth); + passData.initSettings.SetFlag(XeSSInitializationFlags.ExposureScaleTexture, useExposureTexture); + passData.initSettings.SetFlag(XeSSInitializationFlags.ResponsivePixelMask, hasResponsiveMaskTexture); + passData.initSettings.SetFlag(XeSSInitializationFlags.UseNdcVelcoity, false); // motionVectorScale is used instead. + passData.initSettings.SetFlag(XeSSInitializationFlags.ExternalDescriptorHeap, false); + passData.initSettings.SetFlag(XeSSInitializationFlags.LdrInputColor, !io.hdrInput); + passData.initSettings.SetFlag(XeSSInitializationFlags.JitteredMotionVector, io.jitteredMotionVectors); + passData.initSettings.SetFlag(XeSSInitializationFlags.EnableAutoExposure, !useExposureTexture); + passData.initSettings.maxRenderSizeWidth = (uint)io.maxPreUpscaleResolution.x; + passData.initSettings.maxRenderSizeHeight = (uint)io.maxPreUpscaleResolution.y; + passData.initSettings.displaySizeWidth = (uint)io.postUpscaleResolution.x; + passData.initSettings.displaySizeHeight = (uint)io.postUpscaleResolution.y; + passData.initSettings.qualitySetting = xessOptions.xessQualityMode; + } + + // Per-frame execution data read from io.options, so live changes (e.g. jitter offset) apply without recreating the context. + passData.execData.jitterOffsetX = io.subpixelJitter.x; + passData.execData.jitterOffsetY = io.subpixelJitter.y; + passData.execData.exposureScale = (io.preExposureValue == 0.0f) ? 1.0f : io.preExposureValue; + passData.execData.resetHistory = io.resetHistory ? 1u : 0u; + passData.execData.inputWidth = (uint)io.preUpscaleResolution.x; + passData.execData.inputHeight = (uint)io.preUpscaleResolution.y; + passData.execData.inputColorBaseX = 0; + passData.execData.inputColorBaseY = 0; + passData.execData.inputMotionVectorBaseX = 0; + passData.execData.inputMotionVectorBaseY = 0; + passData.execData.inputDepthBaseX = 0; + passData.execData.inputDepthBaseY = 0; + passData.execData.inputResponsiveMaskBaseX = 0; + passData.execData.inputResponsiveMaskBaseY = 0; + passData.execData.outputColorBaseX = 0; + passData.execData.outputColorBaseY = 0; + + // In XeSS SDK, motion vector scale is not a part of execution parameter structs, so follow its design. + passData.motionVectorScale = new Vector2(motionVectorSign * motionVectorScaleX, motionVectorSign * motionVectorScaleY); + + // Texture handles + passData.colorInput = io.cameraColor; + passData.depth = io.cameraDepth; + passData.motionVectors = io.motionVectorColor; + passData.exposure = useExposureTexture ? io.exposureTexture : TextureHandle.nullHandle; + passData.responsiveMask = io.reactiveMask; + passData.colorOutput = outputColor; + + builder.UseTexture(passData.colorInput); + builder.UseTexture(passData.depth); + builder.UseTexture(passData.motionVectors); + if (passData.exposure.IsValid()) + builder.UseTexture(passData.exposure); + if (passData.responsiveMask.IsValid()) + builder.UseTexture(passData.responsiveMask); + builder.UseTexture(outputColor, AccessFlags.Write); + + builder.SetRenderFunc((XeSSGraphData data, UnsafeGraphContext ctx) => + { + CommandBuffer cmd = CommandBufferHelpers.GetNativeCommandBuffer(ctx.cmd); + + Debug.Assert(data.initSettings.displaySizeWidth > 0, "XeSS init settings must be populated"); + + XeSSNativeContext nativeContext = data.upscalerContext.EnsureNativeContext(cmd, data.initSettings); + Debug.Assert(nativeContext != null); + + nativeContext.executeData = data.execData; + XeSSTextureTable textureTable = new() + { + colorInput = data.colorInput, + depth = data.depth, + motionVectors = data.motionVectors, + exposureTexture = data.exposure, + responsiveMask = data.responsiveMask, + colorOutput = data.colorOutput, + }; + + GraphicsDevice.device.SetMotionVectorScale(nativeContext, data.motionVectorScale); + GraphicsDevice.device.ExecuteUpscale(cmd, nativeContext, textureTable); + }); + } + + io.cameraColor = outputColor; + } +#endregion + +#region DATA + private bool m_XeSSReady = false; + private bool m_WarnedUnsupportedDevice = false; +#endregion +} + +#endif // ENABLE_XESS && ENABLE_INTELXESS_MODULE diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/XeSSIUpscaler.cs.meta b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/XeSSIUpscaler.cs.meta new file mode 100644 index 00000000000..39915b22df5 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/XeSSIUpscaler.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 059ee8e4963101f449476dc12c4c62b6 diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/XeSSOptions.cs b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/XeSSOptions.cs new file mode 100644 index 00000000000..ff2dbd84583 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/XeSSOptions.cs @@ -0,0 +1,50 @@ +using UnityEngine; +using UnityEngine.Experimental.Rendering; +using UnityEngine.Rendering; +using UnityEngine.Rendering.RenderGraphModule; +#if ENABLE_XESS && ENABLE_INTELXESS_MODULE +using UnityEngine.Intel; +#endif +using System; + + +#if UNITY_EDITOR +using UnityEditor; +#endif + +#if ENABLE_XESS && ENABLE_INTELXESS_MODULE + +[Serializable] +public class XeSSOptions : UpscalerOptions +{ + #region BACKING_FIELDS + [SerializeField] + [Tooltip("Selects a performance quality setting for Intel XeSS.")] + private XeSSQuality m_XeSSQualityMode = XeSSQuality.Quality; + #endregion + + #region PROPERTIES + /// + /// Gets or sets the performance quality setting for Intel XeSS. + /// + public XeSSQuality xessQualityMode + { + get { return m_XeSSQualityMode; } + set { m_XeSSQualityMode = value; } + } + #endregion + + /// + /// Shallow copies values from another XeSSOptions instance into this one. + /// + public void CopyFrom(XeSSOptions other) + { + if (other == null) + return; + + resolutionMode = other.resolutionMode; + m_XeSSQualityMode = other.m_XeSSQualityMode; + } +} + +#endif // ENABLE_XESS && ENABLE_INTELXESS_MODULE diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/XeSSOptions.cs.meta b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/XeSSOptions.cs.meta new file mode 100644 index 00000000000..05c76ecd65d --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/XeSSOptions.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: ab2d20bb478ced74bae1d3740bdc3673 diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Utilities/.buginfo b/Packages/com.unity.render-pipelines.core/Runtime/Utilities/.buginfo index 5ff71313356..88374a311d0 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Utilities/.buginfo +++ b/Packages/com.unity.render-pipelines.core/Runtime/Utilities/.buginfo @@ -27,4 +27,10 @@ tools: when: path: - ^.*MeshGizmo?.*$ - area: Graphics Tools \ No newline at end of file + area: Graphics Tools + +postprocessing: + when: + path: + - ^.*hlsl.*$ + area: Post-processing and Compositing diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Utilities/ArrayExtensions.cs b/Packages/com.unity.render-pipelines.core/Runtime/Utilities/ArrayExtensions.cs index d4831178a5e..1d0becb7e53 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Utilities/ArrayExtensions.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/Utilities/ArrayExtensions.cs @@ -23,7 +23,7 @@ public static void ResizeArray(this ref NativeArray array, int capacity) w var newArray = new NativeArray(capacity, Allocator.Persistent, NativeArrayOptions.UninitializedMemory); if (array.IsCreated) { - NativeArray.Copy(array, newArray, array.Length); + NativeArray.Copy(array, newArray, Math.Min(array.Length, capacity)); array.Dispose(); } array = newArray; @@ -39,7 +39,7 @@ public static void ResizeArray(this ref TransformAccessArray array, int capacity var newArray = new TransformAccessArray(capacity); if (array.isCreated) { - for (int i = 0; i < array.length; ++i) + for (int i = 0, count = Math.Min(array.length, capacity); i < count; ++i) newArray.Add(array[i]); array.Dispose(); diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Utilities/CoreUtils.cs b/Packages/com.unity.render-pipelines.core/Runtime/Utilities/CoreUtils.cs index 4d91dcd10dc..e270042f3c1 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Utilities/CoreUtils.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/Utilities/CoreUtils.cs @@ -23,6 +23,21 @@ namespace UnityEngine.Rendering /// public static class CoreUtils { + internal static string FormatMemorySize(long bytes) + { + const long KB = 1024; + const long MB = KB * 1024; + const long GB = MB * 1024; + + if (bytes >= GB) + return $"{bytes / (double)GB:F1} GB"; + if (bytes >= MB) + return $"{bytes / (double)MB:F1} MB"; + if (bytes >= KB) + return $"{bytes / (double)KB:F1} KB"; + return $"{bytes} B"; + } + #if UNITY_EDITOR static CoreUtils() { diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Utilities/TextureCurve.cs b/Packages/com.unity.render-pipelines.core/Runtime/Utilities/TextureCurve.cs index d27ddd1b077..ff0e34d672a 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Utilities/TextureCurve.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/Utilities/TextureCurve.cs @@ -15,7 +15,7 @@ namespace UnityEngine.Rendering /// A wrapper around AnimationCurve to automatically bake it into a texture. /// [Serializable] - public class TextureCurve : IDisposable + public class TextureCurve : IDisposable, ISerializationCallbackReceiver { const int k_Precision = 128; // Edit LutBuilder3D if you change this value const float k_Step = 1f / k_Precision; @@ -110,6 +110,10 @@ public void SetDirty() m_IsTextureDirty = true; } + void ISerializationCallbackReceiver.OnBeforeSerialize() { } + + void ISerializationCallbackReceiver.OnAfterDeserialize() => SetDirty(); + static GraphicsFormat GetTextureFormat() { // UUM-41070: We require `Sample | SetPixels` but with the deprecated FormatUsage this was checking `SetPixels` diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Volume/VolumeManager.cs b/Packages/com.unity.render-pipelines.core/Runtime/Volume/VolumeManager.cs index fd4ece5a72d..1a21f3315f3 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Volume/VolumeManager.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/Volume/VolumeManager.cs @@ -628,12 +628,8 @@ internal void UpdateVolumeLayer(Volume volume, int prevLayer, int newLayer) m_VolumeCollection.ChangeLayer(volume, prevLayer, newLayer); } -#if UNITY_ENABLE_CHECKS - internal bool renderingDebuggerAttached { get; set; } - internal event Action beginVolumeStackUpdate; - internal event Action endVolumeStackUpdate; - internal event Action overrideVolumeStackData; -#endif + // Enabled by the Rendering Debugger to inspect which volumes were blended into a stack + internal bool recordVolumeContributions { get; set; } // Go through all listed components and lerp overridden values in the global state void OverrideData(VolumeStack stack, Volume volume, float interpFactor) @@ -661,11 +657,8 @@ void OverrideData(VolumeStack stack, Volume volume, float interpFactor) } } -#if UNITY_ENABLE_CHECKS - if (renderingDebuggerAttached) - overrideVolumeStackData?.Invoke(stack, volume, interpFactor); -#endif - + if (recordVolumeContributions) + stack.AddContribution(volume, interpFactor); } // Faster version of OverrideData to force replace values in the global state. @@ -677,6 +670,7 @@ internal void ReplaceData(VolumeStack stack) // Rebuilt every frame as volumes are re-applied; never holds stale/destroyed Volume references. stack.ClearOverridingVolumes(); + stack.ClearContributions(); var stackParams = stack.parameters; bool resetAllParameters = stack.requiresResetForAllProperties; @@ -800,14 +794,11 @@ public void Update(VolumeStack stack, Transform trigger, LayerMask layerMask) // Sort the cached volume list(s) for the given layer mask if needed and return it var volumes = GrabVolumes(layerMask); +#if UNITY_EDITOR Camera camera = null; // Behavior should be fine even if camera is null if (!onlyGlobal) trigger.TryGetComponent(out camera); - -#if UNITY_ENABLE_CHECKS - if (renderingDebuggerAttached) - beginVolumeStackUpdate?.Invoke(stack, camera); #endif #if ENABLE_PHYSICS_MODULE @@ -887,11 +878,6 @@ public void Update(VolumeStack stack, Transform trigger, LayerMask layerMask) OverrideData(stack, volume, interpFactor * Mathf.Clamp01(volume.weight)); #endif } - -#if UNITY_ENABLE_CHECKS - if (renderingDebuggerAttached) - endVolumeStackUpdate?.Invoke(stack, camera); -#endif } /// diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Volume/VolumeParameter.cs b/Packages/com.unity.render-pipelines.core/Runtime/Volume/VolumeParameter.cs index 8b0e73f5b37..b5695ac015a 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Volume/VolumeParameter.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/Volume/VolumeParameter.cs @@ -1901,7 +1901,9 @@ public override void SetValue(VolumeParameter parameter) /// public override object Clone() { - return new AnimationCurveParameter(new AnimationCurve(GetValue().keys), overrideState); + var curve = new AnimationCurve(); + curve.CopyFrom(GetValue()); + return new AnimationCurveParameter(curve, overrideState); } /// diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Volume/VolumeStack.cs b/Packages/com.unity.render-pipelines.core/Runtime/Volume/VolumeStack.cs index f0bcda034d2..ab2e84c4995 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Volume/VolumeStack.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/Volume/VolumeStack.cs @@ -58,6 +58,8 @@ internal void Clear() CoreUtils.Destroy(component.Value); components.Clear(); + m_OverridingVolumes.Clear(); + m_Contributions.Clear(); parameters = null; } @@ -122,6 +124,16 @@ internal GameObject GetSceneObjectReference() internal void ClearOverridingVolumes() => m_OverridingVolumes.Clear(); + // Volumes blended into this stack by the last Update, in blend order, with their interpolation factor. + // Only filled when VolumeManager.recordVolumeContributions is enabled. + readonly List<(Volume volume, float weight)> m_Contributions = new(); + + internal IReadOnlyList<(Volume volume, float weight)> contributions => m_Contributions; + + internal void AddContribution(Volume volume, float weight) => m_Contributions.Add((volume, weight)); + + internal void ClearContributions() => m_Contributions.Clear(); + /// /// Cleans up the content of this stack. Once a VolumeStack is disposed, it shouldn't /// be used anymore. diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Vrs/Vrs.cs b/Packages/com.unity.render-pipelines.core/Runtime/Vrs/Vrs.cs index eedf0f88f34..2bdf8b8d9a3 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Vrs/Vrs.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/Vrs/Vrs.cs @@ -32,7 +32,6 @@ class VisualizationPassData public Vector4 visualizationParams; } - [NoAutoStaticsCleanup] internal static readonly int shadingRateFragmentSizeCount = Enum.GetNames(typeof(ShadingRateFragmentSize)).Length; [OnCodeInitializing] diff --git a/Packages/com.unity.render-pipelines.core/Runtime/XR/XRBuiltinShaderConstants.cs b/Packages/com.unity.render-pipelines.core/Runtime/XR/XRBuiltinShaderConstants.cs index 22f30ceaa2a..68cded47135 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/XR/XRBuiltinShaderConstants.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/XR/XRBuiltinShaderConstants.cs @@ -11,55 +11,46 @@ public static partial class XRBuiltinShaderConstants /// /// Cached unique id for unity_StereoCameraProjection /// - [NoAutoStaticsCleanup] static public readonly int unity_StereoCameraProjection = Shader.PropertyToID("unity_StereoCameraProjection"); /// /// Cached unique id for unity_StereoCameraInvProjection /// - [NoAutoStaticsCleanup] static public readonly int unity_StereoCameraInvProjection = Shader.PropertyToID("unity_StereoCameraInvProjection"); /// /// Cached unique id for unity_StereoMatrixV /// - [NoAutoStaticsCleanup] static public readonly int unity_StereoMatrixV = Shader.PropertyToID("unity_StereoMatrixV"); /// /// Cached unique id for unity_StereoMatrixInvV /// - [NoAutoStaticsCleanup] static public readonly int unity_StereoMatrixInvV = Shader.PropertyToID("unity_StereoMatrixInvV"); /// /// Cached unique id for unity_StereoMatrixP /// - [NoAutoStaticsCleanup] static public readonly int unity_StereoMatrixP = Shader.PropertyToID("unity_StereoMatrixP"); /// /// Cached unique id for unity_StereoMatrixInvP /// - [NoAutoStaticsCleanup] static public readonly int unity_StereoMatrixInvP = Shader.PropertyToID("unity_StereoMatrixInvP"); /// /// Cached unique id for unity_StereoMatrixVP /// - [NoAutoStaticsCleanup] static public readonly int unity_StereoMatrixVP = Shader.PropertyToID("unity_StereoMatrixVP"); /// /// Cached unique id for unity_StereoMatrixInvVP /// - [NoAutoStaticsCleanup] static public readonly int unity_StereoMatrixInvVP = Shader.PropertyToID("unity_StereoMatrixInvVP"); /// /// Cached unique id for unity_StereoWorldSpaceCameraPos /// - [NoAutoStaticsCleanup] static public readonly int unity_StereoWorldSpaceCameraPos = Shader.PropertyToID("unity_StereoWorldSpaceCameraPos"); /// diff --git a/Packages/com.unity.render-pipelines.core/Runtime/XR/XRPass.cs b/Packages/com.unity.render-pipelines.core/Runtime/XR/XRPass.cs index a491fd28265..0882d1abaff 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/XR/XRPass.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/XR/XRPass.cs @@ -296,6 +296,10 @@ public int totalCameraPasses /// public IntPtr foveatedRenderingInfo { get; private set; } +#if ENABLE_VR && ENABLE_XR_MODULE + internal UnityEngine.XR.XRDisplaySubsystem.XRRenderPass xrSdkRenderPass { get; private set; } +#endif + /// /// Returns true when the active display has HDR enabled. /// @@ -664,6 +668,9 @@ public void InitBase(XRPassCreateInfo createInfo) xrLayoutType = createInfo.xrLayoutType; uvScales = createInfo.uvScales; uvOffsets = createInfo.uvOffsets; +#if ENABLE_VR && ENABLE_XR_MODULE + xrSdkRenderPass = createInfo.xrSdkRenderPass; +#endif } internal void AddView(XRView xrView) diff --git a/Packages/com.unity.render-pipelines.core/Runtime/XR/XRSystem.cs b/Packages/com.unity.render-pipelines.core/Runtime/XR/XRSystem.cs index 8b6c3e55778..2613111ff59 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/XR/XRSystem.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/XR/XRSystem.cs @@ -85,6 +85,7 @@ static void ResetStaticsOnLoad() #if ENABLE_VR && ENABLE_XR_MODULE s_OcclusionMeshScaling = 1.0f; #endif + s_RenderTargetToCamera.Clear(); } // Keep track of only one XR layout — manually drained in ResetStaticsOnLoad() @@ -134,6 +135,74 @@ static public XRDisplaySubsystem GetActiveDisplay() [AutoStaticsCleanup] static Action s_LayoutOverride = null; + const ulong k_DefaultRenderTargetId = 0; + + // Manually cleared in ResetStaticsOnLoad() + [NoAutoStaticsCleanup] + static readonly Dictionary s_RenderTargetToCamera = new Dictionary(); + + /// + /// Associates a camera with a specific XR render target. + /// Called by the spatial container system at container creation. + /// + /// Stable identity for the logical render target. Must not be 0, which is reserved for the default single-target path. + /// The camera to render this target. + /// is null. + /// is 0. + /// The render target is already associated with a different camera, or the camera is already associated with a different render target. + public static void SetCameraRenderTarget(ulong renderTargetId, Camera camera) + { + if (camera == null) + throw new ArgumentNullException(nameof(camera)); + + if (renderTargetId == k_DefaultRenderTargetId) + throw new ArgumentException("Render target ID 0 is reserved for the default single-target path.", nameof(renderTargetId)); + + if (s_RenderTargetToCamera.TryGetValue(renderTargetId, out var existingCamera)) + { + if (existingCamera == camera) + return; + + if (existingCamera != null) + throw new InvalidOperationException($"Render target {renderTargetId} is already associated with camera '{existingCamera.name}'."); + } + + if (TryGetRenderTarget(camera, out var existingTarget)) + throw new InvalidOperationException($"Camera '{camera.name}' is already associated with render target {existingTarget}."); + + s_RenderTargetToCamera[renderTargetId] = camera; + } + + /// + /// Clears all camera-to-render-target associations. + /// + public static void ClearCameraRenderTargets() + => s_RenderTargetToCamera.Clear(); + + /// + /// Removes a single camera-to-render-target association. + /// + /// The render target identity to remove. + public static void ClearCameraRenderTarget(ulong renderTargetId) + => s_RenderTargetToCamera.Remove(renderTargetId); + + internal static bool TryGetCameraForTarget(ulong renderTargetId, out Camera camera) + => s_RenderTargetToCamera.TryGetValue(renderTargetId, out camera); + + internal static bool TryGetRenderTarget(Camera camera, out ulong renderTargetId) + { + foreach (var kvp in s_RenderTargetToCamera) + { + if (kvp.Value == camera) + { + renderTargetId = kvp.Key; + return true; + } + } + renderTargetId = k_DefaultRenderTargetId; + return false; + } + /// Per-frame Temporal Pixel Synthesis configuration override. public struct TemporalPixelSynthesisConfig { @@ -523,55 +592,52 @@ static void RefreshDeviceInfo() #endif } - // Setup the layout to use multi-pass or single-pass based on the runtime caps + // Setup the layout to use multi-pass or single-pass based on the runtime caps. + // Resolves the camera's render target (if any) via the render-target registry, + // filters passes by renderTargetId, and classifies XRLayoutType within that set. internal static void CreateDefaultLayout(Camera camera, XRLayout layout) { #if ENABLE_VR && ENABLE_XR_MODULE if (s_Display == null) throw new NullReferenceException(nameof(s_Display)); - // early return when there's no render pass. - if (s_Display.GetRenderPassCount() == 0) + int displayPassCount = s_Display.GetRenderPassCount(); + if (displayPassCount == 0) return; - // infer XRLayout from number of render passes and number of views in each pass - XRLayoutType layoutType = XRLayoutType.Unknown; - switch (s_Display.GetRenderPassCount()) + // Select the display render passes this camera renders. + // passIndices[i] is the display render pass index of this camera's i-th pass. + // Unregistered cameras get the default render target (0), so they only render passes not claimed by a render target. + // Matching passes are not required to be contiguous. + Span passIndices = stackalloc int[displayPassCount]; + bool hasRenderTarget = TryGetRenderTarget(camera, out var renderTargetId); + Span passTargetIds = stackalloc ulong[displayPassCount]; + for (int i = 0; i < displayPassCount; ++i) { - case 1: - s_Display.GetRenderPass(0, out var renderPass); - if (renderPass.GetRenderParameterCount() == 2) - { - // If the runtime can use single-pass instancing, keep SinglePassStereo. - // Otherwise the loop below will split the two views into separate passes, - // so the effective layout is TwoPassStereo. - layoutType = CanUseSinglePass(camera, renderPass) - ? XRLayoutType.SinglePassStereo - : XRLayoutType.TwoPassStereo; - } - else if (renderPass.GetRenderParameterCount() == 1) - { - layoutType = XRLayoutType.OnePassOneView; - } - break; - case 2: - s_Display.GetRenderPass(0, out var renderPass0); - s_Display.GetRenderPass(1, out var renderPass1); - - // Two passes, each with one view, is TwoPassStereo - if (renderPass0.GetRenderParameterCount() == 1 && renderPass1.GetRenderParameterCount() == 1) - layoutType = XRLayoutType.TwoPassStereo; - // Two passes, each with two views, is TwoPassQuadViews — but only - // if single-pass instancing is supported. Without it the loop would - // split each 2-view pass into separate passes, producing 4 total - // passes which is not a supported layout. - else if (renderPass0.GetRenderParameterCount() == 2 && renderPass1.GetRenderParameterCount() == 2 - && CanUseSinglePass(camera, renderPass0) && CanUseSinglePass(camera, renderPass1)) - layoutType = XRLayoutType.TwoPassQuadViews; - break; + s_Display.GetRenderPass(i, out var renderPass); + passTargetIds[i] = renderPass.renderTargetId; + } + + int renderPassCount = CollectTargetPasses(passTargetIds, renderTargetId, passIndices); + if (renderPassCount == 0) + return; + + // Classify XRLayoutType on the matching passes, not the global pass count. + Span viewCountsPerPass = stackalloc int[renderPassCount]; + bool canUseSinglePass = true; + for (int i = 0; i < renderPassCount; ++i) + { + s_Display.GetRenderPass(passIndices[i], out var renderPass); + viewCountsPerPass[i] = renderPass.GetRenderParameterCount(); + canUseSinglePass &= CanUseSinglePass(camera, renderPass); } + XRLayoutType layoutType = ClassifyLayout(viewCountsPerPass, canUseSinglePass, hasRenderTarget); if (layoutType == XRLayoutType.Unknown) - throw new NotImplementedException($"Unsupported XR layout: {s_Display.GetRenderPassCount()} render passes"); + { + if (hasRenderTarget && ClassifyLayout(viewCountsPerPass, canUseSinglePass, false) == XRLayoutType.TwoPassQuadViews) + throw new NotImplementedException($"Quad views are not supported for cameras with an XR render target (render target {renderTargetId})."); + throw new NotImplementedException($"Unsupported XR layout: {renderPassCount} render passes"); + } void AddViewToPass(XRPass xrPass, XRDisplaySubsystem.XRRenderPass renderPass, int renderParamIndex) { @@ -598,16 +664,14 @@ Vector4 ExtractViewBounds(XRDisplaySubsystem.XRRenderPass renderPass, int render return ExtractFrustumBoundsFromProjection(proj); } - int renderPassCount = s_Display.GetRenderPassCount(); - // Pre-calculate view bounds for quad view (2 passes × 2 views) using fixed-size stack variables // This avoids List allocations that would cause GC pressure every frame Vector4 pass0View0Bounds = default, pass0View1Bounds = default; Vector4 pass1View0Bounds = default, pass1View1Bounds = default; if (layoutType == XRLayoutType.TwoPassQuadViews) { - s_Display.GetRenderPass(0, out var pass0); - s_Display.GetRenderPass(1, out var pass1); + s_Display.GetRenderPass(passIndices[0], out var pass0); + s_Display.GetRenderPass(passIndices[1], out var pass1); pass0View0Bounds = ExtractViewBounds(pass0, 0); pass0View1Bounds = ExtractViewBounds(pass0, 1); pass1View0Bounds = ExtractViewBounds(pass1, 0); @@ -616,7 +680,7 @@ Vector4 ExtractViewBounds(XRDisplaySubsystem.XRRenderPass renderPass, int render for (int renderPassIndex = 0; renderPassIndex < renderPassCount; ++renderPassIndex) { - s_Display.GetRenderPass(renderPassIndex, out var renderPass); + s_Display.GetRenderPass(passIndices[renderPassIndex], out var renderPass); int renderParameterCount = renderPass.GetRenderParameterCount(); s_Display.GetCullingParameters(camera, renderPass.cullingPassIndex, out var cullingParams); @@ -629,7 +693,7 @@ Vector4 ExtractViewBounds(XRDisplaySubsystem.XRRenderPass renderPass, int render Vector4 uvOffsets = Vector4.zero; if (isQuadViewFirstPass) { - s_Display.GetRenderPass(renderPassIndex + 1, out var innerRenderPass); + s_Display.GetRenderPass(passIndices[renderPassIndex + 1], out var innerRenderPass); SetSplitCullingPlanes(camera, innerRenderPass.cullingPassIndex, ref cullingParams); } @@ -713,7 +777,11 @@ internal static void ReconfigurePass(XRPass xrPass, Camera camera) #if ENABLE_VR && ENABLE_XR_MODULE if (xrPass.enabled && s_Display != null) { - s_Display.GetRenderPass(xrPass.multipassId, out var renderPass); + // Use the render pass stored at layout-build time rather than looking up by + // multipassId. multipassId is a per-camera local index and does not match the + // global display render pass index when multiple spatial container cameras + // each build their own layout. + var renderPass = xrPass.xrSdkRenderPass; Debug.Assert(xrPass.singlePassEnabled || renderPass.GetRenderParameterCount() == 1); s_Display.GetCullingParameters(camera, renderPass.cullingPassIndex, out var cullingParams); @@ -722,7 +790,7 @@ internal static void ReconfigurePass(XRPass xrPass, Camera camera) // This must happen after BeginCameraRendering, which may have moved the camera. if (xrPass.xrLayoutType == XRLayoutType.TwoPassQuadViews && !xrPass.isQuadViewInnerPass) { - s_Display.GetRenderPass(xrPass.multipassId + 1, out var innerRenderPass); + s_Display.GetRenderPass(xrPass.xrSdkRenderPass.renderPassIndex + 1, out var innerRenderPass); SetSplitCullingPlanes(camera, innerRenderPass.cullingPassIndex, ref cullingParams); } @@ -739,6 +807,43 @@ internal static void ReconfigurePass(XRPass xrPass, Camera camera) #endif } + // Matching passes are not required to be contiguous. + internal static int CollectTargetPasses(ReadOnlySpan passTargetIds, ulong target, Span matchedPasses) + { + int matchCount = 0; + for (int i = 0; i < passTargetIds.Length; ++i) + { + if (passTargetIds[i] == target) + matchedPasses[matchCount++] = i; + } + return matchCount; + } + + internal static XRLayoutType ClassifyLayout(ReadOnlySpan viewCountsPerPass, bool canUseSinglePass, bool hasRenderTarget) + { + switch (viewCountsPerPass.Length) + { + case 1: + // Without single-pass instancing the two views are split into separate passes + if (viewCountsPerPass[0] == 2) + return canUseSinglePass ? XRLayoutType.SinglePassStereo : XRLayoutType.TwoPassStereo; + else if (viewCountsPerPass[0] == 1) + return XRLayoutType.OnePassOneView; + break; + + case 2: + if (viewCountsPerPass[0] == 1 && viewCountsPerPass[1] == 1) + return XRLayoutType.TwoPassStereo; + + // Without single-pass instancing each 2-view pass would be split, giving 4 passes, which is unsupported + // Quad views are not supported with XR render targets yet + if (viewCountsPerPass[0] == 2 && viewCountsPerPass[1] == 2 && canUseSinglePass && !hasRenderTarget) + return XRLayoutType.TwoPassQuadViews; + break; + } + return XRLayoutType.Unknown; + } + #if ENABLE_VR && ENABLE_XR_MODULE static void SetSplitCullingPlanes(Camera camera, int innerCullingPassIndex, ref ScriptableCullingParameters cullingParams) { diff --git a/Packages/com.unity.render-pipelines.core/Samples~/Common/Scripts/RequiredSettings/RequiredSettingBase.cs b/Packages/com.unity.render-pipelines.core/Samples~/Common/Scripts/RequiredSettings/RequiredSettingBase.cs index 11a868e0800..acf810f66ae 100644 --- a/Packages/com.unity.render-pipelines.core/Samples~/Common/Scripts/RequiredSettings/RequiredSettingBase.cs +++ b/Packages/com.unity.render-pipelines.core/Samples~/Common/Scripts/RequiredSettings/RequiredSettingBase.cs @@ -79,10 +79,10 @@ public virtual bool state if (!string.IsNullOrEmpty(globalSettingsType)) { var type = Type.GetType(globalSettingsType); - var field = type.GetField(propertyPath, BindingFlags.NonPublic | BindingFlags.Instance); + var fieldInfo = type.GetField(propertyPath, BindingFlags.NonPublic | BindingFlags.Instance); var getSettings = typeof(GraphicsSettings).GetMethod("GetRenderPipelineSettings").MakeGenericMethod(type); object settings = getSettings.Invoke(null, null); - return (bool)field.GetValue(settings); + return (bool)fieldInfo.GetValue(settings); } if (property == null) diff --git a/Packages/com.unity.render-pipelines.core/ShaderLibrary/API/FoveatedRendering_Metal.hlsl b/Packages/com.unity.render-pipelines.core/ShaderLibrary/API/FoveatedRendering_Metal.hlsl index dbb0296d54e..35f468812bf 100644 --- a/Packages/com.unity.render-pipelines.core/ShaderLibrary/API/FoveatedRendering_Metal.hlsl +++ b/Packages/com.unity.render-pipelines.core/ShaderLibrary/API/FoveatedRendering_Metal.hlsl @@ -33,8 +33,8 @@ float2 RemapFoveatedRenderingDensity(float2 uv, bool yFlip = false) { - // TODO: Implement density look up - return uv; + // TODO: Implement density look up, default value is not the uv passed through but 1,1 for density is normal. + return float2(1.0f, 1.0f); } float2 RemapFoveatedRenderingPrevFrameDensity(float2 uv, bool yFlip = false) diff --git a/Packages/com.unity.render-pipelines.core/ShaderLibrary/API/Vulkan.hlsl b/Packages/com.unity.render-pipelines.core/ShaderLibrary/API/Vulkan.hlsl index 07cf884cb80..c134f70f7ca 100644 --- a/Packages/com.unity.render-pipelines.core/ShaderLibrary/API/Vulkan.hlsl +++ b/Packages/com.unity.render-pipelines.core/ShaderLibrary/API/Vulkan.hlsl @@ -15,6 +15,14 @@ #define CBUFFER_START(name) cbuffer name { #define CBUFFER_END }; +#if defined(UNITY_COMPILER_DXC) && !defined(UNITY_DECLARE_SPIRV_VIEW_INDEX) +// Enum values from the Khronos SPIR-V specification. DXC inline SPIR-V attributes only accept the numeric values. +#define UNITY_SPIRV_CAPABILITY_MULTIVIEW 4439 +#define UNITY_SPIRV_BUILTIN_VIEW_INDEX 4440 +// SV_ViewID is only valid on vertex inputs, so the view index is a global builtin rather than a member of the shader's input struct +#define UNITY_DECLARE_SPIRV_VIEW_INDEX(name) [[vk::ext_extension("SPV_KHR_multiview")]] [[vk::ext_capability(UNITY_SPIRV_CAPABILITY_MULTIVIEW)]] [[vk::ext_builtin_input(UNITY_SPIRV_BUILTIN_VIEW_INDEX)]] static const uint name +#endif + #define PLATFORM_SUPPORTS_EXPLICIT_BINDING #define PLATFORM_NEEDS_UNORM_UAV_SPECIFIER #define PLATFORM_SUPPORTS_BUFFER_ATOMICS_IN_PIXEL_SHADER diff --git a/Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl b/Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl index f0f4b05adf9..5efbc90a996 100644 --- a/Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl +++ b/Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl @@ -1026,7 +1026,7 @@ float ComputeTextureLOD(float3 duvw_dx, float3 duvw_dy, float3 duvw_dz, float sc return max(0.5f * log2(d * (scale * scale)) - bias, 0.0); } -#if defined(SHADER_API_D3D11) || defined(SHADER_API_D3D12) || defined(SHADER_API_D3D11_9X) || defined(SHADER_API_XBOXONE) || defined(SHADER_API_PSSL) || defined(SHADER_API_METAL) +#if defined(SHADER_API_D3D11) || defined(SHADER_API_DX12) || defined(SHADER_API_D3D11_9X) || defined(SHADER_API_XBOXONE) || defined(SHADER_API_PSSL) || defined(SHADER_API_METAL) #define MIP_COUNT_SUPPORTED 1 #endif // TODO: Bug workaround, switch defines GLCORE when it shouldn't diff --git a/Packages/com.unity.render-pipelines.core/ShaderLibrary/EntityLighting.hlsl b/Packages/com.unity.render-pipelines.core/ShaderLibrary/EntityLighting.hlsl index fee97a62604..00f1a0021bb 100644 --- a/Packages/com.unity.render-pipelines.core/ShaderLibrary/EntityLighting.hlsl +++ b/Packages/com.unity.render-pipelines.core/ShaderLibrary/EntityLighting.hlsl @@ -134,10 +134,7 @@ float4 SampleProbeOcclusion(TEXTURE3D_PARAM(SHVolumeTexture, SHVolumeSampler), f return SAMPLE_TEXTURE3D(SHVolumeTexture, SHVolumeSampler, texCoord); } -// Following functions are to sample enlighten lightmaps (or lightmaps encoded the same way as our -// enlighten implementation). They assume use of RGB9E5 for dynamic illuminance map and RGBM for baked ones. -// It is required for other platform that aren't supporting this format to implement variant of these functions -// (But these kind of platform should use regular render loop and not news shaders). +// Following functions sample baked lightmaps and decode them with DecodeLightmap(). // TODO: This is the max value allowed for emissive (bad name - but keep for now to retrieve it) (It is 8^2.2 (gamma) and 8 is the limit of punctual light slider...), comme from UnityCg.cginc. Fix it! // Ask Jesper if this can be change for HDRenderPipeline @@ -262,7 +259,6 @@ float4 SampleLightmapBicubic(TEXTURE2D_LIGHTMAP_PARAM(tex, smp), LIGHTMAP_EXTRA_ weights[1].x * SAMPLE_TEXTURE2D_LIGHTMAP(tex, smp, (ic + float2(offsets[1].x, offsets[1].y) - 0.5) * texSize.zw LIGHTMAP_SLICE_ARG_USE).rgba); } -// isStaticLightmap mean it is not an Enlighten map real3 SampleSingleLightmap(TEXTURE2D_LIGHTMAP_PARAM(lightmapTex, lightmapSampler), LIGHTMAP_EXTRA_ARGS, float4 transform, bool isStaticLightmap) { real4 decodeInstructions = real4(LIGHTMAP_HDR_MULTIPLIER, LIGHTMAP_HDR_EXPONENT, 0.0, 0.0); @@ -274,7 +270,9 @@ real3 SampleSingleLightmap(TEXTURE2D_LIGHTMAP_PARAM(lightmapTex, lightmapSampler #else real4 encodedIlluminance = SAMPLE_TEXTURE2D_LIGHTMAP(lightmapTex, lightmapSampler, LIGHTMAP_EXTRA_ARGS_USE).rgba; #endif - // Remark: static lightmap is RGBM for now, dynamic lightmap is RGB9E5 + // Remark: static lightmaps are encoded as RGBM, dLDR or full HDR, + // selected by the Lightmap Encoding player setting and platform support (UNITY_LIGHTMAP_*_ENCODING). + // isStaticLightmap = false skips decoding; it was the Enlighten realtime lightmap path and is kept only for API compatibility. real3 illuminance = isStaticLightmap ? DecodeLightmap(encodedIlluminance, decodeInstructions) : encodedIlluminance.rgb; return illuminance; @@ -289,7 +287,7 @@ real3 SampleSingleLightmap(TEXTURE2D_LIGHTMAP_PARAM(lightmapTex, lightmapSampler void SampleDirectionalLightmap(TEXTURE2D_LIGHTMAP_PARAM(lightmapTex, lightmapSampler), TEXTURE2D_LIGHTMAP_PARAM(lightmapDirTex, lightmapDirSampler), LIGHTMAP_EXTRA_ARGS, float4 transform, float3 normalWS, float3 backNormalWS, bool isStaticLightmap, inout real3 bakeDiffuseLighting, inout real3 backBakeDiffuseLighting) { - // In directional mode Enlighten bakes dominant light direction + // In directional mode the lightmapper bakes dominant light direction // in a way, that using it for half Lambert and then dividing by a "rebalancing coefficient" // gives a result close to plain diffuse response lightmaps, but normalmapped. diff --git a/Packages/com.unity.render-pipelines.core/ShaderLibrary/FoveatedRendering.hlsl b/Packages/com.unity.render-pipelines.core/ShaderLibrary/FoveatedRendering.hlsl index 812418c84f0..e5e942707bb 100644 --- a/Packages/com.unity.render-pipelines.core/ShaderLibrary/FoveatedRendering.hlsl +++ b/Packages/com.unity.render-pipelines.core/ShaderLibrary/FoveatedRendering.hlsl @@ -41,24 +41,24 @@ float2 FoveatedRemapPrevFrameLinearToNonUniform(float2 uv) float2 FoveatedRemapDensity(float2 uv) { + float2 density = float2(1.0f, 1.0f); UNITY_BRANCH if(_FOVEATED_RENDERING_NON_UNIFORM_RASTER) { FOVEATED_FLIP_Y(uv); - uv = RemapFoveatedRenderingDensity(uv); - FOVEATED_FLIP_Y(uv); + density = RemapFoveatedRenderingDensity(uv); } - return uv; + return density; } float2 FoveatedRemapPrevFrameDensity(float2 uv) { + float2 density = float2(1.0f, 1.0f); UNITY_BRANCH if(_FOVEATED_RENDERING_NON_UNIFORM_RASTER) { FOVEATED_FLIP_Y(uv); - uv = RemapFoveatedRenderingPrevFrameDensity(uv); - FOVEATED_FLIP_Y(uv); + density = RemapFoveatedRenderingPrevFrameDensity(uv); } - return uv; + return density; } float2 FoveatedRemapNonUniformToLinear(float2 uv) @@ -101,8 +101,8 @@ float2 FoveatedRemapNonUniformToLinearCS(float2 positionCS) // dummy coordinate remapping functions for non-foveated rendering float2 FoveatedRemapLinearToNonUniform(float2 uv) {return uv;} float2 FoveatedRemapPrevFrameLinearToNonUniform(float2 uv) {return uv;} -float2 FoveatedRemapDensity(float2 uv) {return uv;} -float2 FoveatedRemapPrevFrameDensity(float2 uv) {return uv;} +float2 FoveatedRemapDensity(float2 uv) {return float2(1.0f, 1.0f);} +float2 FoveatedRemapPrevFrameDensity(float2 uv) {return float2(1.0f, 1.0f);} float2 FoveatedRemapNonUniformToLinear(float2 uv) {return uv;} float2 FoveatedRemapPrevFrameNonUniformToLinear(float2 uv) {return uv;} float2 FoveatedRemapLinearToNonUniformCS(float2 positionCS) {return positionCS;} diff --git a/Packages/com.unity.render-pipelines.core/ShaderLibrary/MetaPass.hlsl b/Packages/com.unity.render-pipelines.core/ShaderLibrary/MetaPass.hlsl index f2771f1374c..b9a2b16a339 100644 --- a/Packages/com.unity.render-pipelines.core/ShaderLibrary/MetaPass.hlsl +++ b/Packages/com.unity.render-pipelines.core/ShaderLibrary/MetaPass.hlsl @@ -78,13 +78,10 @@ void UnityEditorVizData(float3 positionOS, float2 uv0, float2 uv1, float2 uv2, f void UnityEditorVizData(float3 positionOS, float2 uv0, float2 uv1, float2 uv2, out float2 VizUV, out float4 LightCoord) { - float4 st = unity_LightmapST; - if (unity_MetaVertexControl.y) - st = unity_DynamicLightmapST; - UnityEditorVizData(positionOS, uv0, uv1, uv2, st, VizUV, LightCoord); + UnityEditorVizData(positionOS, uv0, uv1, uv2, unity_LightmapST, VizUV, LightCoord); } -float4 UnityMetaVertexPosition(float3 vertex, float2 uv1, float2 uv2, float4 lightmapST, float4 dynlightmapST) +float4 UnityMetaVertexPosition(float3 vertex, float2 uv1, float2 uv2, float4 lightmapST) { #ifndef EDITOR_VISUALIZATION if (unity_MetaVertexControl.x) @@ -94,22 +91,21 @@ float4 UnityMetaVertexPosition(float3 vertex, float2 uv1, float2 uv2, float4 lig // so use it in a very dummy way vertex.z = vertex.z > 0 ? REAL_MIN : 0.0f; } - if (unity_MetaVertexControl.y) - { - vertex.xy = uv2 * dynlightmapST.xy + dynlightmapST.zw; - // OpenGL right now needs to actually use incoming vertex position, - // so use it in a very dummy way - vertex.z = vertex.z > 0 ? REAL_MIN : 0.0f; - } return TransformWorldToHClip(vertex); #else return TransformObjectToHClip(vertex); #endif } +// Deprecated: Enlighten realtime GI was removed, so dynlightmapST is ignored. +float4 UnityMetaVertexPosition(float3 vertex, float2 uv1, float2 uv2, float4 lightmapST, float4 dynlightmapST) +{ + return UnityMetaVertexPosition(vertex, uv1, uv2, lightmapST); +} + float4 UnityMetaVertexPosition(float3 vertex, float2 uv1, float2 uv2) { - return UnityMetaVertexPosition(vertex, uv1, uv2, unity_LightmapST, unity_DynamicLightmapST); + return UnityMetaVertexPosition(vertex, uv1, uv2, unity_LightmapST); } float unity_OneOverOutputBoost; diff --git a/Packages/com.unity.render-pipelines.core/ShaderLibrary/Shadow/PCSS.hlsl b/Packages/com.unity.render-pipelines.core/ShaderLibrary/Shadow/PCSS.hlsl index d8d274254f1..3b706107814 100644 --- a/Packages/com.unity.render-pipelines.core/ShaderLibrary/Shadow/PCSS.hlsl +++ b/Packages/com.unity.render-pipelines.core/ShaderLibrary/Shadow/PCSS.hlsl @@ -22,6 +22,12 @@ // res += "float2 (" + Math.cos(theta) + ", " + Math.sin(theta) + "),\n"; // } +// Indexing the table hangs some mobile GPUs, so they compute the directions instead +#if defined(SHADER_API_MOBILE) +#define PCSS_COMPUTE_SPIRAL_DIRECTIONS +#endif + +#if !defined(PCSS_COMPUTE_SPIRAL_DIRECTIONS) static const float2 fibonacciSpiralDirection[PCSS_DISK_SAMPLE_COUNT] = { float2 (1, 0), @@ -89,13 +95,25 @@ static const float2 fibonacciSpiralDirection[PCSS_DISK_SAMPLE_COUNT] = float2 (-0.4149890815356195, -0.9098263912451776), float2 (0.9205789302157817, 0.3905565685566777) }; +#endif + +real2 GetFibonacciSpiralDirection(int sampleIndex) +{ +#if defined(PCSS_COMPUTE_SPIRAL_DIRECTIONS) + // Same angle as the generator above, (3 - sqrt(5)) / 2 of a turn per sample + float theta = frac(sampleIndex * 0.381966011250105) * TWO_PI; + return real2(cos(theta), sin(theta)); +#else + return fibonacciSpiralDirection[sampleIndex]; +#endif +} // Samples uniformly spread across the disk kernel, radius baked in. // The radius is in texels so the disk stays circular on a non-square atlas. real2 ComputeFibonacciSpiralDiskSample_Punctual(const in int sampleIndex, const in real diskRadiusTexels, const in real sampleCountInverse, const in real sampleCountBias) { real sampleRadius = diskRadiusTexels * sqrt((real)sampleIndex * sampleCountInverse + sampleCountBias); - return fibonacciSpiralDirection[sampleIndex] * sampleRadius; + return GetFibonacciSpiralDirection(sampleIndex) * sampleRadius; } real PenumbraSizePunctual(real receiver, real blocker) @@ -239,7 +257,7 @@ real2 ComputeFibonacciSpiralDiskSampleClumped(const in int sampleIndex, const in // Third power chosen arbitrarily - center area is really that much more important sampleDistNorm = sampleDistNorm * sampleDistNorm * sampleDistNorm; - return fibonacciSpiralDirection[sampleIndex] * sampleDistNorm; + return GetFibonacciSpiralDirection(sampleIndex) * sampleDistNorm; } // Samples uniformly spread across the disk kernel @@ -251,7 +269,7 @@ real2 ComputeFibonacciSpiralDiskSampleUniform(const in int sampleIndex, const in // sqrt results in uniform distribution sampleDistNorm = sqrt(sampleDistNorm); - return fibonacciSpiralDirection[sampleIndex] * sampleDistNorm; + return GetFibonacciSpiralDirection(sampleIndex) * sampleDistNorm; } void FilterScaleOffset(real3 coord, real maxSampleZDistance, real shadowmapSamplingScale, out real2 filterScalePos, out real2 filterScaleNeg, out real2 filterOffset) @@ -353,7 +371,7 @@ real2 ComputeFibonacciSpiralDiskSampleClumped_Directional(const in int sampleInd // More samples in the middle sampleDistNorm = PositivePow(sampleDistNorm, clumpExponent); - return fibonacciSpiralDirection[sampleIndex] * sampleDistNorm; + return GetFibonacciSpiralDirection(sampleIndex) * sampleDistNorm; } bool BlockerSearch_Directional(inout real averageBlocker, real filterSize, real3 posTCAtlas, float2 shadowmapInAtlasScale, float2 shadowmapInAtlasOffset, real2 sampleJitter, Texture2D shadowMap, SamplerState pointSampler, int sampleCount, float radial2DepthScale, real minFilterRadius, real minFilterRadial2DepthScale, real blockerClumpSampleExponent) diff --git a/Packages/com.unity.render-pipelines.core/ShaderLibrary/UnityDOTSInstancing.hlsl b/Packages/com.unity.render-pipelines.core/ShaderLibrary/UnityDOTSInstancing.hlsl index 30a2e389ec2..48aa8f17b3a 100644 --- a/Packages/com.unity.render-pipelines.core/ShaderLibrary/UnityDOTSInstancing.hlsl +++ b/Packages/com.unity.render-pipelines.core/ShaderLibrary/UnityDOTSInstancing.hlsl @@ -317,9 +317,12 @@ void SetupDOTSVisibleInstancingData() uint crossFadeValuePacked = unity_DOTSVisibleInstances[0].VisibleData.w & kDOTSInstancingFlagLODCrossFadeValuePacked; unity_SampledDOTSIndirectVisibleIndex = (packedIndirectVisibleOffset & ~kIndirectVisibleOffsetEnabledBit) + unity_InstanceID; + // WebGL 2 has no indirect draws, so BRG never sets an indirect visible offset there. +#if !(defined(UNITY_PLATFORM_WEBGL) && defined(SHADER_API_GLES3)) if (packedIndirectVisibleOffset != 0) unity_SampledDOTSInstanceIndex = LoadDOTSIndirectInstanceIndex(unity_SampledDOTSIndirectVisibleIndex); else +#endif unity_SampledDOTSInstanceIndex = unity_DOTSVisibleInstances[unity_InstanceID].VisibleData.x; if(crossFadeValuePacked != 0) diff --git a/Packages/com.unity.render-pipelines.core/ShaderLibrary/UnityInstancing.hlsl b/Packages/com.unity.render-pipelines.core/ShaderLibrary/UnityInstancing.hlsl index ec70ed956d2..4cd90fb843b 100644 --- a/Packages/com.unity.render-pipelines.core/ShaderLibrary/UnityInstancing.hlsl +++ b/Packages/com.unity.render-pipelines.core/ShaderLibrary/UnityInstancing.hlsl @@ -333,9 +333,6 @@ #ifdef LIGHTMAP_ON #define UNITY_USE_LIGHTMAPST_ARRAY #endif - #ifdef DYNAMICLIGHTMAP_ON - #define UNITY_USE_DYNAMICLIGHTMAPST_ARRAY - #endif #endif #if defined(UNITY_INSTANCED_RENDERER_BOUNDS) @@ -343,9 +340,7 @@ #endif #if defined(UNITY_INSTANCED_SH) && !defined(LIGHTMAP_ON) - #if !defined(DYNAMICLIGHTMAP_ON) - #define UNITY_USE_SHCOEFFS_ARRAYS - #endif + #define UNITY_USE_SHCOEFFS_ARRAYS #if (SHADOWS_SHADOWMASK_KEYWORD_DECLARED & KEYWORD_TYPE_FLAG_RUNTIME_BRANCHING) #define UNITY_USE_PROBESOCCLUSION_ARRAY #elif !defined(SHADOWS_SHADOWMASK_KEYWORD_DECLARED) || (SHADOWS_SHADOWMASK_KEYWORD_DECLARED & KEYWORD_TYPE_FLAG_SPECIALIZED_VARIANTS) @@ -407,10 +402,6 @@ UNITY_DEFINE_INSTANCED_PROP(float4, unity_LightmapIndexArray) #define unity_LightmapST UNITY_ACCESS_INSTANCED_PROP(unity_Builtins2, unity_LightmapSTArray) #endif - #ifdef UNITY_USE_DYNAMICLIGHTMAPST_ARRAY - UNITY_DEFINE_INSTANCED_PROP(float4, unity_DynamicLightmapSTArray) - #define unity_DynamicLightmapST UNITY_ACCESS_INSTANCED_PROP(unity_Builtins2, unity_DynamicLightmapSTArray) - #endif #ifdef UNITY_USE_SHCOEFFS_ARRAYS UNITY_DEFINE_INSTANCED_PROP(half4, unity_SHArArray) UNITY_DEFINE_INSTANCED_PROP(half4, unity_SHAgArray) diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/ArrayExtensionsTests.cs b/Packages/com.unity.render-pipelines.core/Tests/Editor/ArrayExtensionsTests.cs new file mode 100644 index 00000000000..9c106fd504a --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/ArrayExtensionsTests.cs @@ -0,0 +1,99 @@ +using NUnit.Framework; +using Unity.Collections; +using UnityEngine.Jobs; + +namespace UnityEngine.Rendering.Tests +{ + class ArrayExtensionsTests + { + static NativeArray CreateSequentialNativeArray(int length) + { + var array = new NativeArray(length, Allocator.Persistent); + for (int i = 0; i < length; ++i) + array[i] = i + 1; + return array; + } + + [TestCase(5, 8)] + [TestCase(10, 5)] + [TestCase(10, 10)] + [TestCase(10, 0)] + public void ResizeNativeArray_KeepsLeadingElements(int initialLength, int newLength) + { + var array = CreateSequentialNativeArray(initialLength); + try + { + array.ResizeArray(newLength); + + Assert.IsTrue(array.IsCreated); + Assert.AreEqual(newLength, array.Length); + int keptLength = Mathf.Min(initialLength, newLength); + for (int i = 0; i < keptLength; ++i) + Assert.AreEqual(i + 1, array[i]); + } + finally + { + if (array.IsCreated) + array.Dispose(); + } + } + + [Test] + public void ResizeNativeArray_WhenNotCreated_AllocatesNewArray() + { + var array = default(NativeArray); + try + { + array.ResizeArray(4); + + Assert.IsTrue(array.IsCreated); + Assert.AreEqual(4, array.Length); + } + finally + { + if (array.IsCreated) + array.Dispose(); + } + } + + [TestCase(3, 5)] + [TestCase(5, 3)] + public void ResizeTransformAccessArray_KeepsLeadingTransforms(int initialLength, int newCapacity) + { + var gameObjects = new GameObject[initialLength]; + var array = new TransformAccessArray(initialLength); + try + { + for (int i = 0; i < initialLength; ++i) + { + gameObjects[i] = new GameObject($"ResizeTransformAccessArray_{i}"); + array.Add(gameObjects[i].transform); + } + + array.ResizeArray(newCapacity); + + int expectedLength = Mathf.Min(initialLength, newCapacity); + Assert.AreEqual(expectedLength, array.length); + for (int i = 0; i < expectedLength; ++i) + Assert.AreEqual(gameObjects[i].transform, array[i]); + } + finally + { + if (array.isCreated) + array.Dispose(); + foreach (var go in gameObjects) + UnityEngine.Object.DestroyImmediate(go); + } + } + + [Test] + public void ResizeManagedArray_KeepsLeadingElements() + { + var array = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + + ArrayExtensions.ResizeArray(ref array, 5); + + CollectionAssert.AreEqual(new[] { 1, 2, 3, 4, 5 }, array); + } + } +} diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/ArrayExtensionsTests.cs.meta b/Packages/com.unity.render-pipelines.core/Tests/Editor/ArrayExtensionsTests.cs.meta new file mode 100644 index 00000000000..d52e1481ec8 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/ArrayExtensionsTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e4e68764db27491babb8cdd823474c94 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/AssetLinkUtilsTests.cs b/Packages/com.unity.render-pipelines.core/Tests/Editor/AssetLinkUtilsTests.cs new file mode 100644 index 00000000000..c756c205425 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/AssetLinkUtilsTests.cs @@ -0,0 +1,48 @@ +using System.Collections.Generic; +using NUnit.Framework; +using Unity.RenderPipelines.Core.Runtime.Shared; +using UnityEditor; + +namespace UnityEngine.Rendering.Tests +{ + class AssetLinkUtilsTests + { + const string k_Folder = "Assets/AssetLinkUtilsTests"; + const string k_AssetPath = k_Folder + "/Linked.asset"; + + Object m_PreviousSelection; + + [SetUp] + public void SetUp() + { + m_PreviousSelection = Selection.activeObject; + CoreUtils.EnsureFolderTreeInAssetFilePath(k_AssetPath); + } + + [TearDown] + public void TearDown() + { + Selection.activeObject = m_PreviousSelection; + AssetDatabase.DeleteAsset(k_Folder); + } + + [Test] + [Description("An asset link holds the GUID of the asset, and clicking it selects that asset.")] + public void AssetLinkSelectsTheLinkedAsset() + { + var profile = ScriptableObject.CreateInstance(); + AssetDatabase.CreateAsset(profile, k_AssetPath); + string guid = AssetDatabase.AssetPathToGUID(k_AssetPath); + + string color = EditorGUIUtility.isProSkin ? "#40a0ff" : "#0000FF"; + Assert.AreEqual($"Linked", AssetLinkUtils.AssetLink(profile)); + + Selection.activeObject = null; + AssetLinkUtils.SelectLinkedAsset(new Dictionary { { "href", k_AssetPath } }); + Assert.IsNull(Selection.activeObject, "A link of another kind must not select anything"); + + AssetLinkUtils.SelectLinkedAsset(new Dictionary { { "srpasset", guid } }); + Assert.AreSame(profile, Selection.activeObject, "The link must select the linked asset"); + } + } +} diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/AssetLinkUtilsTests.cs.meta b/Packages/com.unity.render-pipelines.core/Tests/Editor/AssetLinkUtilsTests.cs.meta new file mode 100644 index 00000000000..0b8ee4e69fb --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/AssetLinkUtilsTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: b90a77bf46ba47ad8806ea514d23f7b4 diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/BuildLightGridShaderTests.cs b/Packages/com.unity.render-pipelines.core/Tests/Editor/BuildLightGridShaderTests.cs new file mode 100644 index 00000000000..46bae6964be --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/BuildLightGridShaderTests.cs @@ -0,0 +1,37 @@ +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework; +using UnityEngine; +using UnityEngine.Rendering; + +namespace UnityEditor.Rendering.Tests +{ + class BuildLightGridShaderTests + { + const string k_ShaderPath = "Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Shaders/BuildLightGrid.compute"; + + [Test] + public void BuildLightGridShader_CompilesWithoutWarnings() + { + var shader = AssetDatabase.LoadAssetAtPath(k_ShaderPath); + Assert.IsNotNull(shader, $"Could not load compute shader at {k_ShaderPath}."); + + var deviceType = SystemInfo.graphicsDeviceType; + if (deviceType == GraphicsDeviceType.Null || !ShaderUtil.IsGraphicsAPISupported(shader, deviceType)) + Assert.Ignore($"{k_ShaderPath} has no kernels for the {deviceType} graphics API."); + + var messages = new List(); + foreach (var kernel in new[] { "BuildConservativeLightGrid", "BuildRegirLightGrid" }) + { + int kernelIndex = shader.FindKernel(kernel); + foreach (var keywords in new[] { new string[0], new[] { "SPARSE_GRID" } }) + { + var result = ShaderUtil.CompileComputeShaderVariant(shader, kernelIndex, keywords, deviceType, EditorUserBuildSettings.activeBuildTarget); + messages.AddRange(result.Messages); + } + } + + Assert.IsEmpty(messages, $"{k_ShaderPath} has compiler messages:\n" + string.Join("\n", messages.Select(m => $"{m.severity}: {m.message} ({m.file}:{m.line})"))); + } + } +} diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/BuildLightGridShaderTests.cs.meta b/Packages/com.unity.render-pipelines.core/Tests/Editor/BuildLightGridShaderTests.cs.meta new file mode 100644 index 00000000000..91ab91298a6 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/BuildLightGridShaderTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bd18582c987b41b6804572f7d46dbef3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/Debugging/DebugUITests.cs b/Packages/com.unity.render-pipelines.core/Tests/Editor/Debugging/DebugUITests.cs index bb87bff1bee..d182a190c1e 100644 --- a/Packages/com.unity.render-pipelines.core/Tests/Editor/Debugging/DebugUITests.cs +++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/Debugging/DebugUITests.cs @@ -1,3 +1,6 @@ +#if ENABLE_UIELEMENTS_MODULE && UNITY_ENABLE_CHECKS +#define ENABLE_RENDERING_DEBUGGER_UI +#endif #if ENABLE_RENDERING_DEBUGGER_UI using NUnit.Framework; using UnityEngine.Rendering; @@ -63,6 +66,51 @@ public void RoundToPrecision_WithLargeValueAndRefValue_HandlesCorrectly() float result = DebugUI.DebugUIStepperHelper.RoundToPrecision(12345.0f, 100.0f); Assert.AreEqual(12345.0f, result, 0.01f); } + + [TestCase(-5, ExpectedResult = 10)] + [TestCase(15, ExpectedResult = 15)] + [TestCase(25, ExpectedResult = 20)] + public int IntField_ValidateValue_ClampsToMinMax(int value) + { + var field = new DebugUI.IntField { min = () => 10, max = () => 20 }; + return field.ValidateValue(value); + } + + [TestCase(int.MinValue, ExpectedResult = int.MinValue)] + [TestCase(int.MaxValue, ExpectedResult = int.MaxValue)] + [TestCase(123456789, ExpectedResult = 123456789)] + public int IntField_ValidateValue_PreservesValueWithinFullRange(int value) + { + var field = new DebugUI.IntField { min = () => int.MinValue, max = () => int.MaxValue }; + return field.ValidateValue(value); + } + + [TestCase(5u, ExpectedResult = 10u)] + [TestCase(15u, ExpectedResult = 15u)] + [TestCase(25u, ExpectedResult = 20u)] + public uint UIntField_ValidateValue_ClampsToMinMax(uint value) + { + var field = new DebugUI.UIntField { min = () => 10u, max = () => 20u }; + return field.ValidateValue(value); + } + + [TestCase(0u, ExpectedResult = 0u)] + [TestCase(uint.MaxValue, ExpectedResult = uint.MaxValue)] + [TestCase(123456789u, ExpectedResult = 123456789u)] + public uint UIntField_ValidateValue_PreservesValueWithinFullRange(uint value) + { + var field = new DebugUI.UIntField { min = () => 0u, max = () => uint.MaxValue }; + return field.ValidateValue(value); + } + + [TestCase(-5f, ExpectedResult = 10f)] + [TestCase(15.5f, ExpectedResult = 15.5f)] + [TestCase(25f, ExpectedResult = 20f)] + public float FloatField_ValidateValue_ClampsToMinMax(float value) + { + var field = new DebugUI.FloatField { min = () => 10f, max = () => 20f }; + return field.ValidateValue(value); + } } } #endif diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/DynamicArrayTests.cs b/Packages/com.unity.render-pipelines.core/Tests/Editor/DynamicArrayTests.cs index 5468c2dcb10..b600f48f208 100644 --- a/Packages/com.unity.render-pipelines.core/Tests/Editor/DynamicArrayTests.cs +++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/DynamicArrayTests.cs @@ -1,6 +1,7 @@ using System; using NUnit.Framework; -using UnityEngine.Profiling; +using UnityEngine.TestTools.Constraints; +using Is = UnityEngine.TestTools.Constraints.Is; namespace UnityEngine.Rendering.Tests { @@ -78,6 +79,60 @@ public void TestAddRangeOutOfSpaceKeepPreviousElements() Assert.AreEqual(4, smallDynamicArray.size); } + [TestCase(0, 9, new[] { 9, 1, 2, 3 })] + [TestCase(1, 9, new[] { 1, 9, 2, 3 })] + [TestCase(2, 9, new[] { 1, 2, 9, 3 })] + [TestCase(3, 9, new[] { 1, 2, 3, 9 })] + public void TestInsertIntoFullArrayKeepOrder(int index, int item, int[] expected) + { + var fullDynamicArray = new DynamicArray(3); + fullDynamicArray[0] = 1; + fullDynamicArray[1] = 2; + fullDynamicArray[2] = 3; + + fullDynamicArray.Insert(index, item); + + Assert.AreEqual(expected.Length, fullDynamicArray.size); + for (int i = 0; i < expected.Length; ++i) + { + Assert.AreEqual(expected[i], fullDynamicArray[i]); + } + } + + [Test] + public void TestInsertWithOneFreeSlotKeepOrder() + { + var dynamicArray = new DynamicArray(4); + dynamicArray.Resize(3); + dynamicArray[0] = 1; + dynamicArray[1] = 2; + dynamicArray[2] = 3; + + dynamicArray.Insert(1, 9); + + Assert.AreEqual(4, dynamicArray.size); + Assert.AreEqual(1, dynamicArray[0]); + Assert.AreEqual(9, dynamicArray[1]); + Assert.AreEqual(2, dynamicArray[2]); + Assert.AreEqual(3, dynamicArray[3]); + } + + [Test] + public void TestInsertWithFreeCapacityKeepOrder() + { + m_DynamicArray.Add(1); + m_DynamicArray.Add(2); + m_DynamicArray.Add(3); + + m_DynamicArray.Insert(0, 9); + + Assert.AreEqual(4, m_DynamicArray.size); + Assert.AreEqual(9, m_DynamicArray[0]); + Assert.AreEqual(1, m_DynamicArray[1]); + Assert.AreEqual(2, m_DynamicArray[2]); + Assert.AreEqual(3, m_DynamicArray[3]); + } + [Test] public void TestRemoveElementCorrectSize() { @@ -516,28 +571,14 @@ public void Foreach_TestNoModificationsAllowed() }); } - static Recorder gcAllocRecorder = Recorder.Get("GC.Alloc"); - static int CountGCAllocs(Action action) - { - gcAllocRecorder.FilterToCurrentThread(); - gcAllocRecorder.enabled = false; - gcAllocRecorder.enabled = true; - - action(); - - gcAllocRecorder.enabled = false; - return gcAllocRecorder.sampleBlockCount; - } static void ValidateNoGCAllocs(Action action) { // warmup // this will catch static c'tors etc - CountGCAllocs(action); + action(); // actual test - var count = CountGCAllocs(action); - if (count != 0) - throw new AssertionException($"Expected 0 GC allocations but there were {count}"); + Assert.That(() => action(), Is.Not.AllocatingGCMemory()); } [Test] diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/GPUDriven/GPUDrivenRenderingTests.cs b/Packages/com.unity.render-pipelines.core/Tests/Editor/GPUDriven/GPUDrivenRenderingTests.cs index 29a57bfeed9..3eaeb31082d 100644 --- a/Packages/com.unity.render-pipelines.core/Tests/Editor/GPUDriven/GPUDrivenRenderingTests.cs +++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/GPUDriven/GPUDrivenRenderingTests.cs @@ -594,8 +594,10 @@ public void TestGpuDrivenSmallMeshShadowCulling() var lastLodBias = QualitySettings.lodBias; QualitySettings.lodBias = 1.0f; +#pragma warning disable CS0618 // Type or member is obsolete var lastShadowCascades = QualitySettings.shadowCascades; QualitySettings.shadowCascades = 4; +#pragma warning restore CS0618 OnCullingCompleteCallback onCompleteCallback = (JobHandle jobHandle, in BatchCullingContext cc, in BatchCullingOutput cullingOutput) => { @@ -674,7 +676,9 @@ public void TestGpuDrivenSmallMeshShadowCulling() m_MeshRendererProcessor.DestroyInstances(instanceIDs.AsArray()); QualitySettings.lodBias = lastLodBias; +#pragma warning disable CS0618 // Type or member is obsolete QualitySettings.shadowCascades = lastShadowCascades; +#pragma warning restore CS0618 mainCamera = null; GameObject.DestroyImmediate(cameraObject); @@ -1133,6 +1137,72 @@ public void TestForceRenderingOff() ShutdownGPUResidentDrawer(); } + static LODGroup CreateAnimatedCrossFadeLODGroup(out MeshRenderer renderer) + { + var lodGroup = new GameObject("LODGroup").AddComponent(); + var child = GameObject.CreatePrimitive(PrimitiveType.Cube); + child.transform.parent = lodGroup.transform; + renderer = child.GetComponent(); + lodGroup.SetLODs(new[] { new LOD(0.5f, new Renderer[] { renderer }) }); + lodGroup.fadeMode = LODFadeMode.CrossFade; + lodGroup.animateCrossFading = true; + return lodGroup; + } + + [Test, ConditionalIgnore("IgnoreGfxAPI", "Graphics API Not Supported.")] + public void TestAnimateCrossFadingIsIgnoredWhenFadeModeIsNone() + { + InitializeGPUResidentDrawer(); + + var simpleDotsMat = new Material(Shader.Find("Unlit/SimpleDots")); + var lodGroup = CreateAnimatedCrossFadeLODGroup(out var renderer); + renderer.sharedMaterial = simpleDotsMat; + + (int validRenderers, int invalidLODGroups) Dispatch() + { + int validRenderers = -1, invalidLODGroups = -1; + var rendererIDs = new NativeArray(1, Allocator.Temp) { [0] = renderer.GetEntityId() }; + var lodGroupIDs = new NativeArray(1, Allocator.Temp) { [0] = lodGroup.GetEntityId() }; + m_GPUDrivenProcessor.EnableGPUDrivenRenderingAndDispatchRendererData(rendererIDs, (in GPUDrivenMeshRendererData data) => validRenderers = data.renderer.Length); + m_GPUDrivenProcessor.DispatchLODGroupData(lodGroupIDs, false, (in GPUDrivenLODGroupData data) => invalidLODGroups = data.invalidLODGroup.Length); + return (validRenderers, invalidLODGroups); + } + + Assert.AreEqual((0, 1), Dispatch()); + + lodGroup.fadeMode = LODFadeMode.None; + Assert.AreEqual((1, 0), Dispatch(), "The animate flag has no effect without a fade mode, so it must not exclude the renderer or the LOD group."); + + Object.DestroyImmediate(simpleDotsMat); + Object.DestroyImmediate(lodGroup.gameObject); + + ShutdownGPUResidentDrawer(); + } + + [Test] + public void TestChangingFadeModeOfAnimatedCrossFadeLODGroupReportsRendererChange() + { + var lodGroup = CreateAnimatedCrossFadeLODGroup(out var renderer); + + using var dispatcher = new ObjectDispatcher(); + dispatcher.EnableTypeTracking(ObjectDispatcher.TypeTrackingFlags.SceneObjects); + dispatcher.ClearTypeChanges(); + + bool RendererReported() + { + using var changes = dispatcher.GetTypeChangesAndClear(Allocator.Temp, noScriptingArray: true); + return changes.changedID.Contains(renderer.GetEntityId()); + } + + lodGroup.fadeMode = LODFadeMode.None; + Assert.IsTrue(RendererReported(), "Turning the fade mode off disables animated cross-fade, so GRD must re-evaluate the renderer."); + + lodGroup.fadeMode = LODFadeMode.CrossFade; + Assert.IsTrue(RendererReported(), "Turning the fade mode back on re-enables animated cross-fade, so GRD must re-evaluate the renderer."); + + Object.DestroyImmediate(lodGroup.gameObject); + } + class OnWillRenderObjectBehaviour : MonoBehaviour { void OnWillRenderObject() { } } class OnBecameInvisibleBehaviour : MonoBehaviour { void OnBecameInvisible() { } } class OnBecameVisibleBehaviour : MonoBehaviour { void OnBecameVisible() { } } @@ -1223,6 +1293,56 @@ SpeedTreeWindAsset CreateDummySpeedTreeWindAsset(params object[] args) dummyWindAsset = null; } + [Test, ConditionalIgnore("IgnoreGfxAPI", "Graphics API Not Supported.")] + public void TestRendererReparentedUnderInactiveParentIsRemovedAndRestored() + { + InitializeGPUResidentDrawer(); + + var simpleDotsMat = new Material(Shader.Find("Unlit/SimpleDots")); + var activeParent = new GameObject("ActiveParent"); + var inactiveParent = new GameObject("InactiveParent"); + inactiveParent.SetActive(false); + + var cube = GameObject.CreatePrimitive(PrimitiveType.Cube); + var renderer = cube.GetComponent(); + renderer.material = simpleDotsMat; + cube.transform.SetParent(activeParent.transform); + + var instanceIDs = new NativeArray(1, Allocator.TempJob); + instanceIDs[0] = renderer.GetEntityId(); + var instances = new NativeArray(1, Allocator.TempJob); + instances[0] = InstanceHandle.Invalid; + + m_GPUResidentDrawer.m_WorldProcessor.Update(); + m_InstanceDataSystem.QueryRendererInstances(instanceIDs, instances); + Assert.IsTrue(instances[0].isValid, "Renderer under an active parent should be registered in GRD."); + + cube.transform.SetParent(inactiveParent.transform); + Assert.IsTrue(cube.activeSelf); + Assert.IsFalse(cube.activeInHierarchy); + instances[0] = InstanceHandle.Invalid; + + m_GPUResidentDrawer.m_WorldProcessor.Update(); + m_InstanceDataSystem.QueryRendererInstances(instanceIDs, instances); + Assert.IsFalse(instances[0].isValid, "Renderer reparented under an inactive parent should be removed from GRD."); + + cube.transform.SetParent(activeParent.transform); + instances[0] = InstanceHandle.Invalid; + + m_GPUResidentDrawer.m_WorldProcessor.Update(); + m_InstanceDataSystem.QueryRendererInstances(instanceIDs, instances); + + Assert.IsTrue(instances[0].isValid, "Renderer reparented back under an active parent should be registered again."); + + instances.Dispose(); + instanceIDs.Dispose(); + GameObject.DestroyImmediate(cube); + GameObject.DestroyImmediate(activeParent); + GameObject.DestroyImmediate(inactiveParent); + Object.DestroyImmediate(simpleDotsMat); + ShutdownGPUResidentDrawer(); + } + [Test, ConditionalIgnore("IgnoreGfxAPI", "Graphics API Not Supported.")] public void TestLocalBoundsGPUDataUpload() { 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 2cb32e351c8..91343362580 100644 --- a/Packages/com.unity.render-pipelines.core/Tests/Editor/NativePassCompilerRenderGraphTests.cs +++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/NativePassCompilerRenderGraphTests.cs @@ -1,8 +1,10 @@ using NUnit.Framework; using System; using System.Collections.Generic; +using System.Text.RegularExpressions; using UnityEngine.Experimental.Rendering; -using UnityEngine.Profiling; +using UnityEngine.TestTools.Constraints; +using Is = UnityEngine.TestTools.Constraints.Is; using UnityEngine.Rendering.RenderGraphModule; using UnityEngine.Rendering.RenderGraphModule.NativeRenderPassCompiler; using UnityEngine.TestTools; @@ -11,8 +13,6 @@ namespace UnityEngine.Rendering.Tests { class NativePassCompilerRenderGraphTests { - static Recorder gcAllocRecorder = Recorder.Get("GC.Alloc"); - class RenderGraphTestPassData { public TextureHandle[] textures = new TextureHandle[8]; @@ -907,6 +907,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.extraTextureDepth, 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.extraTextureDepth, 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.extraTextureDepth, 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.extraTextureDepth, 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() { @@ -980,6 +1081,106 @@ public void AllocateFreeInMergedPassesWorks() Assert.AreEqual(renderTargets.extraTextures[1].handle.index, lastUsed[0].index); } + void ImportMemorylessDepthAndSplitAcrossNativePasses(RenderGraph renderGraph) + { + var renderTargets = ImportAndCreateRenderTargets(renderGraph); + + var depthHandle = RTHandles.Alloc(BuiltinRenderTextureType.Depth, "Memoryless Depth"); + var importInfo = new RenderTargetInfo + { + width = 1024, + height = 768, + volumeDepth = 1, + msaaSamples = 1, + format = GraphicsFormat.D32_SFloat_S8_UInt, + isMemoryless = true, + }; + var memorylessDepth = renderGraph.ImportTexture(depthHandle, importInfo, new ImportResourceParams()); + + using (var builder = renderGraph.AddRasterRenderPass("Opaques", out var passData)) + { + builder.SetRenderAttachmentDepth(memorylessDepth, AccessFlags.Write); + builder.SetRenderAttachment(renderTargets.backBuffer, 0, AccessFlags.Write); + builder.SetRenderFunc((RenderGraphTestPassData data, RasterGraphContext context) => { }); + builder.AllowPassCulling(false); + } + + // Breaks the native render pass between the two raster passes + using (var builder = renderGraph.AddComputePass("Compute", out var passData)) + { + builder.UseTexture(renderTargets.extraTextures[0], AccessFlags.ReadWrite); + builder.SetRenderFunc((RenderGraphTestPassData data, ComputeGraphContext context) => { }); + builder.AllowPassCulling(false); + } + + using (var builder = renderGraph.AddRasterRenderPass("Transparents", out var passData)) + { + builder.SetRenderAttachmentDepth(memorylessDepth, AccessFlags.ReadWrite); + builder.SetRenderAttachment(renderTargets.backBuffer, 0, AccessFlags.ReadWrite); + builder.SetRenderFunc((RenderGraphTestPassData data, RasterGraphContext context) => { }); + builder.AllowPassCulling(false); + } + } + + [Test] + public void ImportedMemorylessAcrossNativePasses_StaysMemoryless_WhenMemorylessCannotBeStored() + { + NativePassCompiler.s_SupportsMemorylessTexturesOverride = true; + NativePassCompiler.s_CanStoreMemorylessTexturesOverride = false; + try + { + var renderGraph = AllocateRenderGraph(); + ImportMemorylessDepthAndSplitAcrossNativePasses(renderGraph); + + if (RenderGraph.enableValidityChecks) + LogAssert.Expect(LogType.Warning, new Regex("Imported memoryless resource 'Memoryless Depth'.*does not retain its contents")); + var exception = Assert.Throws(() => renderGraph.CompileNativeRenderGraph(renderGraph.ComputeGraphHash())); + Assert.AreEqual(RenderGraph.RenderGraphExceptionMessages.k_ResolvignMemorylessResource, exception.Message); + } + finally + { + NativePassCompiler.s_SupportsMemorylessTexturesOverride = null; + NativePassCompiler.s_CanStoreMemorylessTexturesOverride = null; + } + } + + [Test] + public void ImportedMemorylessAcrossNativePasses_IsStoredAndLoaded_WhenMemorylessCanBeStored() + { + NativePassCompiler.s_SupportsMemorylessTexturesOverride = true; + NativePassCompiler.s_CanStoreMemorylessTexturesOverride = true; + try + { + var renderGraph = AllocateRenderGraph(); + ImportMemorylessDepthAndSplitAcrossNativePasses(renderGraph); + + if (RenderGraph.enableValidityChecks) + LogAssert.Expect(LogType.Log, new Regex("Imported memoryless resource 'Memoryless Depth'.*stored and loaded across the pass boundary")); + var result = renderGraph.CompileNativeRenderGraph(renderGraph.ComputeGraphHash()); + var passes = result.contextData.GetNativePasses(); + + Assert.AreEqual(2, passes.Count); + Assert.IsTrue(passes[0].hasDepth); + Assert.IsTrue(passes[1].hasDepth); + + // Depth is attachment 0 + var firstUse = passes[0].attachments[0]; + Assert.AreEqual(RenderBufferLoadAction.DontCare, firstUse.loadAction); + Assert.AreEqual(RenderBufferStoreAction.Store, firstUse.storeAction); + Assert.IsFalse(firstUse.memoryless); + + var lastUse = passes[1].attachments[0]; + Assert.AreEqual(RenderBufferLoadAction.Load, lastUse.loadAction); + Assert.AreEqual(RenderBufferStoreAction.DontCare, lastUse.storeAction); + Assert.IsFalse(lastUse.memoryless); + } + finally + { + NativePassCompiler.s_SupportsMemorylessTexturesOverride = null; + NativePassCompiler.s_CanStoreMemorylessTexturesOverride = null; + } + } + [Test] public void MemorylessWorks() { @@ -1753,27 +1954,12 @@ public void GraphPassesDoesNotAlloc() passes[0].GraphPasses(result.contextData); }); - // From RenderPassCullingTests.cs void ValidateNoGCAllocs(Action action) { // Warmup - this will catch static c'tors etc. - CountGCAllocs(action); - - // Actual test. - var count = CountGCAllocs(action); - if (count != 0) - throw new AssertionException($"Expected 0 GC allocations but there were {count}"); - } - - int CountGCAllocs(Action action) - { - gcAllocRecorder.FilterToCurrentThread(); - gcAllocRecorder.enabled = true; - action(); - gcAllocRecorder.enabled = false; - return gcAllocRecorder.sampleBlockCount; + Assert.That(() => action(), Is.Not.AllocatingGCMemory()); } } @@ -2735,13 +2921,8 @@ void AddPass(int i) AddPass(2); var hash = g.ComputeGraphHash(); - gcAllocRecorder.FilterToCurrentThread(); - gcAllocRecorder.enabled = false; // flush allocations accumulated outside the measured window - gcAllocRecorder.enabled = true; - g.CompileNativeRenderGraph(hash); - gcAllocRecorder.enabled = false; - - Assert.AreEqual(0, gcAllocRecorder.sampleBlockCount, "Compiling on a fresh compilation-cache entry allocated GC memory."); + Assert.That(() => { g.CompileNativeRenderGraph(hash); }, Is.Not.AllocatingGCMemory(), + "Compiling on a fresh compilation-cache entry allocated GC memory."); } finally { diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/PathTracing/MaterialPoolTests.cs b/Packages/com.unity.render-pipelines.core/Tests/Editor/PathTracing/MaterialPoolTests.cs new file mode 100644 index 00000000000..60881b6d737 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/PathTracing/MaterialPoolTests.cs @@ -0,0 +1,91 @@ +using System.Collections.Generic; +using NUnit.Framework; +using UnityEngine.Experimental.Rendering; +using UnityEngine.PathTracing.Core; +using UnityEngine.TestTools; + +namespace UnityEngine.PathTracing.Tests +{ + internal class MaterialPoolTests + { + private MaterialPool _pool; + private readonly List _objects = new(); + + [SetUp] + public void Setup() + { + var worldResources = new WorldResourceSet(); + worldResources.LoadFromAssetDatabase(); + _pool = new MaterialPool(worldResources.SetAlphaChannelShader, worldResources.BlitCubemap, worldResources.BlitGrayScaleCookie, maxSliceCount: 1); + } + + [TearDown] + public void TearDown() + { + _pool?.Dispose(); + foreach (var obj in _objects) + Object.DestroyImmediate(obj); + _objects.Clear(); + } + + private RenderTexture CreateRenderTexture(int size) + { + var texture = new RenderTexture(size, size, 0, GraphicsFormat.R8G8B8A8_UNorm); + texture.Create(); + _objects.Add(texture); + return texture; + } + + private MaterialPool.MaterialDescriptor CreateDescriptor(int albedoSize) + { + return new MaterialPool.MaterialDescriptor + { + Albedo = CreateRenderTexture(albedoSize), + AlbedoScale = Vector2.one, + EmissionType = Core.MaterialPropertyType.None, + TransmissionChannels = TransmissionChannels.None, + Alpha = 1.0f, + }; + } + + [Test] + public void AddMaterial_AtlasFull_IsRejected() + { + Assert.IsTrue(_pool.AddMaterial(1, CreateDescriptor(256), UVChannel.UV0)); + Assert.IsFalse(_pool.AddMaterial(2, CreateDescriptor(256), UVChannel.UV0)); + Assert.AreEqual(1, _pool.MaterialCount); + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void UpdateMaterial_ShrinkAtLimit_FreesSpaceForMoreMaterials() + { + Assert.IsTrue(_pool.AddMaterial(1, CreateDescriptor(256), UVChannel.UV0)); + Assert.IsTrue(_pool.UpdateMaterial(1, CreateDescriptor(64), UVChannel.UV0)); + + _pool.GetAtlasUsage(out var albedo, out _, out _); + Assert.AreEqual(1, albedo.UsedSliceCount); + + Assert.IsTrue(_pool.AddMaterial(2, CreateDescriptor(64), UVChannel.UV0)); + Assert.AreEqual(2, _pool.MaterialCount); + } + + [Test] + public void UpdateMaterial_GrowAtLimit_UpdatesInPlace() + { + Assert.IsTrue(_pool.AddMaterial(1, CreateDescriptor(64), UVChannel.UV0)); + Assert.IsTrue(_pool.AddMaterial(2, CreateDescriptor(128), UVChannel.UV0)); + Assert.IsTrue(_pool.AddMaterial(3, CreateDescriptor(64), UVChannel.UV0)); + + var grown = CreateDescriptor(256); + grown.EmissionType = Core.MaterialPropertyType.Color; + grown.EmissionColor = Vector3.one; + Assert.IsTrue(_pool.UpdateMaterial(1, grown, UVChannel.UV0), "Without room for a bigger node, the texture should be scaled into the existing one."); + Assert.IsTrue(_pool.IsEmissive(1, out _), "The rest of the material update should be applied."); + + _pool.GetAtlasUsage(out var albedo, out _, out _); + Assert.AreEqual(1, albedo.UsedSliceCount); + Assert.AreEqual(3, _pool.MaterialCount); + } + } +} diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/PathTracing/MaterialPoolTests.cs.meta b/Packages/com.unity.render-pipelines.core/Tests/Editor/PathTracing/MaterialPoolTests.cs.meta new file mode 100644 index 00000000000..5da30ea1f49 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/PathTracing/MaterialPoolTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 09a42346a0fc4d64b6c2fd0b86d69009 diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/PathTracing/TextureSlotAllocatorTests.cs b/Packages/com.unity.render-pipelines.core/Tests/Editor/PathTracing/TextureSlotAllocatorTests.cs new file mode 100644 index 00000000000..69ced113d6a --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/PathTracing/TextureSlotAllocatorTests.cs @@ -0,0 +1,155 @@ +using System.Collections.Generic; +using NUnit.Framework; +using UnityEngine.Experimental.Rendering; +using UnityEngine.PathTracing.Core; +using UnityEngine.Rendering; +using UnityEngine.TestTools; + +namespace UnityEngine.PathTracing.Tests +{ + internal class TextureSlotAllocatorTests + { + private TextureSlotAllocator _allocator; + private readonly List _sources = new(); + + [SetUp] + public void Setup() + { + _allocator = new TextureSlotAllocator(256, GraphicsFormat.R8G8B8A8_UNorm, FilterMode.Bilinear, maxSliceCount: 4); + } + + [TearDown] + public void TearDown() + { + _allocator?.Dispose(); + foreach (var source in _sources) + { + source.Release(); + Object.DestroyImmediate(source); + } + _sources.Clear(); + } + + private RenderTexture CreateSource(int size, Color color) + { + var texture = new RenderTexture(size, size, 0, GraphicsFormat.R8G8B8A8_UNorm); + texture.Create(); + var previous = RenderTexture.active; + RenderTexture.active = texture; + GL.Clear(false, true, color); + RenderTexture.active = previous; + _sources.Add(texture); + return texture; + } + + private TextureSlotAllocator.TextureLocation Add(RenderTexture source) + { + return _allocator.AddTexture(source, Vector2.one, Vector2.zero); + } + + [Test] + public void AddTexture_BeyondSliceLimit_ReturnsInvalidWithoutErrors() + { + var source = CreateSource(256, Color.red); + int[] expectedCapacities = { 1, 2, 4, 4 }; + for (int i = 0; i < 4; ++i) + { + Assert.IsTrue(Add(source).IsValid, $"Add {i} should succeed."); + Assert.AreEqual(expectedCapacities[i], _allocator.GetUsage().CapacitySliceCount, $"Capacity after add {i}."); + } + + Assert.IsFalse(Add(source).IsValid, "Adding past the slice limit should fail."); + Assert.AreEqual(4, _allocator.GetUsage().UsedSliceCount); + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void AddTexture_AfterRemoveAtLimit_SucceedsWithoutGrowing() + { + var source = CreateSource(256, Color.red); + var locations = new TextureSlotAllocator.TextureLocation[4]; + for (int i = 0; i < 4; ++i) + locations[i] = Add(source); + + _allocator.RemoveTexture(locations[2]); + + Assert.IsTrue(Add(source).IsValid); + Assert.AreEqual(4, _allocator.GetUsage().CapacitySliceCount); + } + + [Test] + public void GetUsage_EmptiedSlice_IsNotCountedAsUsed() + { + var source = CreateSource(256, Color.red); + var first = Add(source); + Add(source); + + _allocator.RemoveTexture(first); + + var usage = _allocator.GetUsage(); + Assert.AreEqual(1, usage.UsedSliceCount); + Assert.AreEqual(2, usage.CapacitySliceCount); + + Add(CreateSource(64, Color.green)); + Assert.AreEqual(2, _allocator.GetUsage().UsedSliceCount, "The emptied slice should be reused."); + } + + [Test] + public void AddTexture_TextureLargerThanSlice_ReusesFreedSlice() + { + var source = CreateSource(512, Color.red); + var location = Add(source); + for (int i = 1; i < 4; ++i) + Add(CreateSource(256, Color.green)); + _allocator.RemoveTexture(location); + + Assert.IsTrue(Add(source).IsValid, "A texture larger than a slice should fit in a freed slice."); + Assert.AreEqual(4, _allocator.GetUsage().UsedSliceCount); + } + + [Test] + public void AddTexture_SixteenQuarterSizeTextures_FitInOneSlice() + { + var source = CreateSource(64, Color.red); + for (int i = 0; i < 16; ++i) + Assert.IsTrue(Add(source).IsValid); + + var usage = _allocator.GetUsage(); + Assert.AreEqual(1, usage.UsedSliceCount); + Assert.AreEqual(1, usage.CapacitySliceCount); + } + + [Test] + public void GetUsage_ReportsAllocatedBytes() + { + Add(CreateSource(256, Color.red)); + Add(CreateSource(256, Color.red)); + + Assert.AreEqual(2L * 256 * 256 * 4, _allocator.GetUsage().AllocatedBytes); + Assert.AreEqual(4, _allocator.GetUsage().MaxSliceCount); + } + + [Test] + public void AddTexture_ResizeAtlas_PreservesExistingSliceContent() + { + Add(CreateSource(256, Color.green)); + Add(CreateSource(256, Color.blue)); + Assert.AreEqual(2, _allocator.GetUsage().CapacitySliceCount); + + Add(CreateSource(256, Color.red)); + Assert.AreEqual(4, _allocator.GetUsage().CapacitySliceCount, "The third add should have resized the atlas."); + + var request = AsyncGPUReadback.Request(_allocator.Texture, 0, 0, 1, 0, 1, 0, 1); + request.WaitForCompletion(); + Assert.IsFalse(request.hasError); + Color32 pixel = request.GetData()[0]; + Assert.AreEqual(new Color32(0, 255, 0, 255), pixel); + + request = AsyncGPUReadback.Request(_allocator.Texture, 0, 0, 1, 0, 1, 1, 1); + request.WaitForCompletion(); + Assert.IsFalse(request.hasError); + pixel = request.GetData()[0]; + Assert.AreEqual(new Color32(0, 0, 255, 255), pixel); + } + } +} diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/PathTracing/TextureSlotAllocatorTests.cs.meta b/Packages/com.unity.render-pipelines.core/Tests/Editor/PathTracing/TextureSlotAllocatorTests.cs.meta new file mode 100644 index 00000000000..5d85025720f --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/PathTracing/TextureSlotAllocatorTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 887af2b87e69495e96bbf7ed62ad9ed4 diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/PathTracing/WorldTests.cs b/Packages/com.unity.render-pipelines.core/Tests/Editor/PathTracing/WorldTests.cs index 8da7d9dc92a..68d8f94536a 100644 --- a/Packages/com.unity.render-pipelines.core/Tests/Editor/PathTracing/WorldTests.cs +++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/PathTracing/WorldTests.cs @@ -326,5 +326,78 @@ public void World_UpdateInstanceTransform_UploadsCorrectData() var m = math.transpose(instancesArray[0].localToWorld); Assert.AreEqual((float4x4)newLocalToWorld, new float4x4(new float3x3(m.c0, m.c1, m.c2), m.c3)); } + + static MaterialPool.MaterialDescriptor CreateAlbedoOnlyDescriptor(Texture albedo) + { + return new MaterialPool.MaterialDescriptor + { + Albedo = albedo, + AlbedoScale = Vector2.one, + EmissionType = Core.MaterialPropertyType.None, + TransmissionChannels = TransmissionChannels.None, + Alpha = 1.0f, + }; + } + + // The baker (BakeInputToWorldConversion) passes the handle from World.AddMaterial straight to AddInstance. A + // sub-mesh whose material was rejected because the atlas is full is masked out of the bake. + [Test] + public void AddInstance_MaterialRejectedByFullAtlas_SubMeshIsMaskedOut() + { + var world = new World(); + var worldResources = new WorldResourceSet(); + worldResources.LoadFromAssetDatabase(); + world.Init(_rayTracingContext, worldResources, materialAtlasMaxSliceCount: 1); + var albedo = new RenderTexture(256, 256, 0, RenderTextureFormat.ARGB32); + albedo.Create(); + try + { + var descriptor = CreateAlbedoOnlyDescriptor(albedo); + Assert.IsTrue(world.AddMaterial(descriptor, UVChannel.UV1) != MaterialHandle.Invalid, "Precondition: the first material should fill the atlas."); + var rejected = world.AddMaterial(descriptor, UVChannel.UV1); + Assert.IsTrue(rejected == MaterialHandle.Invalid, "Precondition: the second material should be rejected."); + + var mesh = Resources.GetBuiltinResource("Cube.fbx"); + const bool isStatic = true; + uint mask = World.GetInstanceMask(ShadowCastingMode.On, isStatic, RenderedGameObjectsFilter.OnlyStatic); + world.AddInstance(mesh, new MaterialHandle[] { rejected }, new uint[] { mask }, 1u, Matrix4x4.identity, CalculateBounds(mesh, Matrix4x4.identity), isStatic, RenderedGameObjectsFilter.OnlyStatic, true); + + var instances = GetAccelStructInstancesFromWorld(world); + Assert.AreEqual(1, instances.instances.Count, "Precondition: the cube should be the only ray tracing instance."); + foreach (var entry in instances.instances) + Assert.AreEqual(0u, instances.instanceBuffer.Get(entry.indexInInstanceBuffer).instanceMask); + } + finally + { + world.Dispose(); + Object.DestroyImmediate(albedo); + } + } + + [Test] + public void UpdateInstanceMaterials_RejectedMaterial_DoesNotThrow() + { + var world = new World(); + var worldResources = new WorldResourceSet(); + worldResources.LoadFromAssetDatabase(); + world.Init(_rayTracingContext, worldResources, materialAtlasMaxSliceCount: 1); + var albedo = new RenderTexture(256, 256, 0, RenderTextureFormat.ARGB32); + albedo.Create(); + try + { + var accepted = world.AddMaterial(CreateAlbedoOnlyDescriptor(albedo), UVChannel.UV1); + var mesh = Resources.GetBuiltinResource("Cube.fbx"); + const bool isStatic = true; + uint mask = World.GetInstanceMask(ShadowCastingMode.On, isStatic, RenderedGameObjectsFilter.OnlyStatic); + var instance = world.AddInstance(mesh, new MaterialHandle[] { accepted }, new uint[] { mask }, 1u, Matrix4x4.identity, CalculateBounds(mesh, Matrix4x4.identity), isStatic, RenderedGameObjectsFilter.OnlyStatic, false); + + Assert.DoesNotThrow(() => world.UpdateInstanceMaterials(instance, new MaterialHandle[] { MaterialHandle.Invalid })); + } + finally + { + world.Dispose(); + Object.DestroyImmediate(albedo); + } + } } } diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/RenderGraphMultiDrawIndirectTests.cs b/Packages/com.unity.render-pipelines.core/Tests/Editor/RenderGraphMultiDrawIndirectTests.cs index 88f30a54dfa..771e2a80191 100644 --- a/Packages/com.unity.render-pipelines.core/Tests/Editor/RenderGraphMultiDrawIndirectTests.cs +++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/RenderGraphMultiDrawIndirectTests.cs @@ -73,6 +73,7 @@ public void DrawProceduralIndirect_SingleDraw_RendersOneSubDraw([Values] PassKin [Test, ConditionalIgnore("IgnoreNoMultiDrawIndirect", "Multi draw indirect is not supported by this device.")] public void DrawProceduralIndirect_MultiDraw_RendersAllSubDraws([Values] PassKind passKind, [Values] IndexMode indexMode) { + IgnoreNonIndexedMultiDrawOnUgkD3D12(indexMode); var pixels = RenderAndReadback(passKind, indexMode, kDrawCount, null); using (pixels) AssertSubDrawsRendered(pixels, kDrawCount); @@ -81,6 +82,7 @@ public void DrawProceduralIndirect_MultiDraw_RendersAllSubDraws([Values] PassKin [Test, ConditionalIgnore("IgnoreNoMultiDrawIndirectCountBuffer", "Multi draw indirect count buffers are not supported by this device.")] public void DrawProceduralIndirect_MultiDrawWithCountBuffer_ClampsToCount([Values] PassKind passKind, [Values] IndexMode indexMode) { + IgnoreNonIndexedMultiDrawOnUgkD3D12(indexMode); var pixels = RenderAndReadback(passKind, indexMode, kDrawCount, kLiveDrawCount); using (pixels) AssertSubDrawsRendered(pixels, kLiveDrawCount); @@ -344,6 +346,12 @@ TextureHandle CreateTarget() }); } + static void IgnoreNonIndexedMultiDrawOnUgkD3D12(IndexMode indexMode) + { + if (indexMode == IndexMode.NonIndexed && UnityGraphicsKernelTestUtils.IsForcedUGK() && SystemInfo.graphicsDeviceType == GraphicsDeviceType.Direct3D12) + Assert.Ignore("https://jira.unity3d.com/browse/UGK-3349"); + } + static Material LoadTestMaterial() { var shader = AssetDatabase.LoadAssetAtPath("Packages/com.unity.render-pipelines.core/Tests/Editor/MultiDrawIndirectProcedural.shader"); diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/RenderGraphTests.UtilityPasses.cs b/Packages/com.unity.render-pipelines.core/Tests/Editor/RenderGraphTests.UtilityPasses.cs index b6abd41a3df..7947c8f323d 100644 --- a/Packages/com.unity.render-pipelines.core/Tests/Editor/RenderGraphTests.UtilityPasses.cs +++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/RenderGraphTests.UtilityPasses.cs @@ -87,6 +87,43 @@ public void RenderPassAddBlitSetGlobal() } + [TestCase(TextureUVOrigin.BottomLeft)] + [TestCase(TextureUVOrigin.TopLeft)] + public void CanAddCopyPass_OnIdleGraphWithImportedTextures_DoesNotThrow(TextureUVOrigin destinationUVOrigin) + { + var sourceTexture = new RenderTexture(64, 64, 0, GraphicsFormat.R8G8B8A8_UNorm); + var destinationTexture = new RenderTexture(64, 64, 0, GraphicsFormat.R8G8B8A8_UNorm); + var sourceHandle = RTHandles.Alloc(sourceTexture); + var destinationHandle = RTHandles.Alloc(destinationTexture); + + try + { + var info = new RenderTargetInfo + { + width = 64, + height = 64, + volumeDepth = 1, + msaaSamples = 1, + format = GraphicsFormat.R8G8B8A8_UNorm, + }; + var source = m_RenderGraph.ImportTexture(sourceHandle, info, new ImportResourceParams { textureUVOrigin = TextureUVOrigin.BottomLeft }); + var destination = m_RenderGraph.ImportTexture(destinationHandle, info, new ImportResourceParams { textureUVOrigin = destinationUVOrigin }); + + bool canAddCopyPass = false; + Assert.DoesNotThrow(() => canAddCopyPass = m_RenderGraph.CanAddCopyPass(source, destination)); + + bool originsDiffer = SystemInfo.graphicsUVStartsAtTop && destinationUVOrigin != TextureUVOrigin.BottomLeft; + Assert.AreEqual(!originsDiffer, canAddCopyPass); + } + finally + { + sourceHandle.Release(); + destinationHandle.Release(); + UnityEngine.Object.DestroyImmediate(sourceTexture); + UnityEngine.Object.DestroyImmediate(destinationTexture); + } + } + [Test] public void RenderPassAddBlitUseTexture() { diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/RenderGraphTests.cs b/Packages/com.unity.render-pipelines.core/Tests/Editor/RenderGraphTests.cs index 5ba44598188..be1ad6c2164 100644 --- a/Packages/com.unity.render-pipelines.core/Tests/Editor/RenderGraphTests.cs +++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/RenderGraphTests.cs @@ -1415,6 +1415,64 @@ public void ExceptionsOnExecuteAreHandledAsExpected() m_Camera.Render(); } + struct GlobalStateTestConstants + { + public Vector4 value; + } + + static readonly int k_GlobalStateTestConstantsID = Shader.PropertyToID("_GlobalStateTestConstants"); + + void RecordPassBindingAGlobalConstantBuffer(ConstantBuffer constantBuffer, bool allowGlobalStateModification) + { + m_RenderGraphTestPipeline.recordRenderGraphBody = (context, camera, cmd) => + { + TextureHandle texture = m_RenderGraph.CreateTexture(new TextureDesc(4, 4) { format = GraphicsFormat.R8G8B8A8_UNorm }); + + using (var builder = m_RenderGraph.AddRasterRenderPass("GlobalConstantBufferPass", out var passData)) + { + builder.AllowPassCulling(false); + builder.AllowGlobalStateModification(allowGlobalStateModification); + builder.SetRenderAttachment(texture, 0); + builder.SetRenderFunc((RenderGraphTestPassData data, RasterGraphContext ctx) => constantBuffer.SetGlobal(ctx.cmd, k_GlobalStateTestConstantsID)); + } + }; + } + + [Test] + public void BindingAGlobalConstantBufferInAPassThatAllowsGlobalStateModificationWorks() + { + var constantBuffer = new ConstantBuffer(); + try + { + RecordPassBindingAGlobalConstantBuffer(constantBuffer, true); + m_Camera.Render(); + } + finally + { + constantBuffer.Release(); + } + } + +#if UNITY_ENABLE_CHECKS + [Test] + [TestMustExpectAllLogs] + public void BindingAGlobalConstantBufferInAPassThatDoesNotAllowGlobalStateModificationThrows() + { + var constantBuffer = new ConstantBuffer(); + try + { + RecordPassBindingAGlobalConstantBuffer(constantBuffer, false); + LogAssert.Expect(LogType.Error, "Render Graph Execution error"); + LogAssert.Expect(LogType.Exception, "InvalidOperationException: GlobalConstantBufferPass: Modifying global state from this command buffer is not allowed. Please ensure your render graph pass allows modifying global state."); + m_Camera.Render(); + } + finally + { + constantBuffer.Release(); + } + } +#endif + class TestBufferTextureComputeData { public BufferHandle bufferHandle; @@ -3068,6 +3126,172 @@ public void TextureUVOrigin_CheckTextureReadBreaksBackbufferUVOriginInherited() m_RenderGraph.Cleanup(); } + // Same as TextureUVOrigin_CheckBackbufferUVOriginInherited, but the backbuffer is memoryless, like an XR eye texture with MSAA, + // so nothing in the native pass is stored. + [Test] + public void TextureUVOrigin_CheckBackbufferUVOriginInherited_WhenBackbufferIsMemoryless() + { + // We don't send the list of graphics commands to execute to avoid mistmatch attachment size errors in the native render pass layer due to the backbuffer usage + m_RenderGraphTestPipeline.invalidContextForTesting = true; + m_RenderGraphTestPipeline.renderTextureUVOriginStrategy = RenderTextureUVOriginStrategy.PropagateAttachmentOrientation; + m_RenderGraphTestPipeline.recordRenderGraphBody = (context, camera, cmd) => + { + // On !SystemInfo.graphicsUVStartsAtTop APIs everything simplifies as that matches Unity's texture reads so we can't test a TopLeft system there. + var backBufferUVOrigin = SystemInfo.graphicsUVStartsAtTop ? TextureUVOrigin.TopLeft : TextureUVOrigin.BottomLeft; + + var importParams = new ImportResourceParams + { + textureUVOrigin = backBufferUVOrigin, + }; + var importInfo = new RenderTargetInfo + { + width = 1024, + height = 768, + volumeDepth = 1, + msaaSamples = 1, + format = GraphicsFormat.R16G16B16A16_SFloat, + isMemoryless = true, + }; + var backBuffer = m_RenderGraph.ImportTexture(RTHandles.Alloc(BuiltinRenderTextureType.CameraTarget, "Backbuffer Color"), importInfo, importParams); + + importInfo.format = GraphicsFormat.D32_SFloat_S8_UInt; + var depthBuffer = m_RenderGraph.ImportTexture(RTHandles.Alloc(BuiltinRenderTextureType.Depth, "Backbuffer Depth"), importInfo, importParams); + + var intermediateTexture = m_RenderGraph.CreateTexture(SimpleTextureDesc("IntermediateTexture", 1024, 768, 1, GraphicsFormat.R8G8B8A8_UNorm)); + + using (var builder = m_RenderGraph.AddRasterRenderPass("TestPass0", out var passData)) + { + passData.backBufferUVOrigin = backBufferUVOrigin; + passData.renderAttachment = intermediateTexture; + + builder.SetRenderAttachmentDepth(depthBuffer, AccessFlags.Write); + builder.SetRenderAttachment(intermediateTexture, 0, AccessFlags.Write); + builder.SetRenderFunc(static (UVOriginPassData data, RasterGraphContext context) => + { + Assert.AreEqual(data.backBufferUVOrigin, context.GetTextureUVOrigin(data.renderAttachment)); + }); + } + + using (var builder = m_RenderGraph.AddRasterRenderPass("TestPass1", out var passData)) + { + passData.backBufferUVOrigin = backBufferUVOrigin; + passData.inputAttachment = intermediateTexture; + passData.renderAttachment = backBuffer; + + builder.SetRenderAttachment(backBuffer, 0, AccessFlags.Write); + builder.SetInputAttachment(intermediateTexture, 0, AccessFlags.Read); + builder.SetRenderFunc(static (UVOriginPassData data, RasterGraphContext context) => + { + Assert.AreEqual(data.backBufferUVOrigin, context.GetTextureUVOrigin(data.renderAttachment)); + Assert.AreEqual(data.backBufferUVOrigin, context.GetTextureUVOrigin(data.inputAttachment)); + }); + } + + var result = m_RenderGraph.CompileNativeRenderGraph(m_RenderGraph.ComputeGraphHash()); + var passes = result.contextData.GetNativePasses(); + + // Nothing to test here, since the passes are not merged because of the "back buffer in multiple render targets" API limitation (e.g OpenGL) + if (passes.Count > 1 && passes[0].breakAudit.reason == PassBreakReason.BackbufferInMultipleRenderTargetsNotSupported) + return; + + Assert.AreEqual(1, passes.Count); + for (int attachmentIndex = 0; attachmentIndex < passes[0].attachments.size; ++attachmentIndex) + Assert.AreEqual(RenderBufferStoreAction.DontCare, passes[0].attachments[attachmentIndex].storeAction); + }; + + m_Camera.Render(); + + m_RenderGraph.Cleanup(); + } + + // Same as TextureUVOrigin_CheckBackbufferUVOriginInherited_WhenBackbufferIsMemoryless, but the memoryless backbuffer spans two + // native passes, so it is stored in the first one and nothing is stored in the last one. + [Test] + public void TextureUVOrigin_CheckBackbufferUVOriginInherited_WhenMemorylessBackbufferSpansNativePasses() + { + NativePassCompiler.s_SupportsMemorylessTexturesOverride = true; + NativePassCompiler.s_CanStoreMemorylessTexturesOverride = true; + try + { + // We don't send the list of graphics commands to execute to avoid mistmatch attachment size errors in the native render pass layer due to the backbuffer usage + m_RenderGraphTestPipeline.invalidContextForTesting = true; + m_RenderGraphTestPipeline.renderTextureUVOriginStrategy = RenderTextureUVOriginStrategy.PropagateAttachmentOrientation; + m_RenderGraphTestPipeline.recordRenderGraphBody = (context, camera, cmd) => + { + var backBufferUVOrigin = SystemInfo.graphicsUVStartsAtTop ? TextureUVOrigin.TopLeft : TextureUVOrigin.BottomLeft; + + var importParams = new ImportResourceParams + { + textureUVOrigin = backBufferUVOrigin, + }; + var importInfo = new RenderTargetInfo + { + width = 1024, + height = 768, + volumeDepth = 1, + msaaSamples = 1, + format = GraphicsFormat.R16G16B16A16_SFloat, + isMemoryless = true, + }; + var backBuffer = m_RenderGraph.ImportTexture(RTHandles.Alloc(BuiltinRenderTextureType.CameraTarget, "Backbuffer Color"), importInfo, importParams); + + importInfo.format = GraphicsFormat.D32_SFloat_S8_UInt; + var depthBuffer = m_RenderGraph.ImportTexture(RTHandles.Alloc(BuiltinRenderTextureType.Depth, "Backbuffer Depth"), importInfo, importParams); + + var computeTexture = m_RenderGraph.CreateTexture(SimpleTextureDesc("ComputeTexture", 1024, 768, 1, GraphicsFormat.R8G8B8A8_UNorm)); + + using (var builder = m_RenderGraph.AddRasterRenderPass("TestPass0", out var passData)) + { + passData.backBufferUVOrigin = backBufferUVOrigin; + passData.renderAttachment = backBuffer; + + builder.SetRenderAttachmentDepth(depthBuffer, AccessFlags.Write); + builder.SetRenderAttachment(backBuffer, 0, AccessFlags.Write); + builder.SetRenderFunc(static (UVOriginPassData data, RasterGraphContext context) => + { + Assert.AreEqual(data.backBufferUVOrigin, context.GetTextureUVOrigin(data.renderAttachment)); + }); + } + + // Breaks the native render pass between the two raster passes + using (var builder = m_RenderGraph.AddComputePass("TestCompute", out var passData)) + { + builder.UseTexture(computeTexture, AccessFlags.ReadWrite); + builder.AllowPassCulling(false); + builder.SetRenderFunc(static (RenderGraphTestPassData data, ComputeGraphContext context) => { }); + } + + using (var builder = m_RenderGraph.AddRasterRenderPass("TestPass1", out var passData)) + { + passData.backBufferUVOrigin = backBufferUVOrigin; + passData.renderAttachment = backBuffer; + + builder.SetRenderAttachmentDepth(depthBuffer, AccessFlags.ReadWrite); + builder.SetRenderAttachment(backBuffer, 0, AccessFlags.ReadWrite); + builder.SetRenderFunc(static (UVOriginPassData data, RasterGraphContext context) => + { + Assert.AreEqual(data.backBufferUVOrigin, context.GetTextureUVOrigin(data.renderAttachment)); + }); + } + + var result = m_RenderGraph.CompileNativeRenderGraph(m_RenderGraph.ComputeGraphHash()); + var passes = result.contextData.GetNativePasses(); + + Assert.AreEqual(2, passes.Count); + for (int attachmentIndex = 0; attachmentIndex < passes[1].attachments.size; ++attachmentIndex) + Assert.AreEqual(RenderBufferStoreAction.DontCare, passes[1].attachments[attachmentIndex].storeAction); + }; + + m_Camera.Render(); + } + finally + { + NativePassCompiler.s_SupportsMemorylessTexturesOverride = null; + NativePassCompiler.s_CanStoreMemorylessTexturesOverride = null; + m_RenderGraph.Cleanup(); + } + } + [Test] public void CanMergeBackBufferAndCustomRenderTargets() { @@ -3814,8 +4038,9 @@ public void SetBufferDataWithNonMappableBufferInRasterPassLogsWarning() // Expect the CommandBuffer warning for non-mappable buffer inside render pass (all platforms) LogAssert.Expect(LogType.Warning, new System.Text.RegularExpressions.Regex(@"The rendering command SetGraphicsBufferData is not supported inside a renderpass")); - // On D3D12, buffer should still have initial zeros since SetBufferData was rejected at device level. - if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Direct3D12) + // On legacy D3D12, buffer should still have initial zeros since SetBufferData was rejected at device level. + // UGK applies the write, as the other backends do. + if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Direct3D12 && !UnityGraphicsKernelTestUtils.IsForcedUGK()) { float[] result = new float[kBufferSize]; buffer.GetData(result); diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/TextureCurveTests.cs b/Packages/com.unity.render-pipelines.core/Tests/Editor/TextureCurveTests.cs new file mode 100644 index 00000000000..1229dcbe3d2 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/TextureCurveTests.cs @@ -0,0 +1,38 @@ +using NUnit.Framework; + +namespace UnityEngine.Rendering.Tests +{ + class TextureCurveTests + { + // Keys at 0.25 and 0.75; time 0.9 is only reachable through the looping curve. + static TextureCurve CreateLoopingCurve(float valueAtQuarter, float valueAtThreeQuarters) + { + var keys = new[] { new Keyframe(0.25f, valueAtQuarter), new Keyframe(0.75f, valueAtThreeQuarters) }; + return new TextureCurve(keys, 0.5f, true, new Vector2(0f, 1f)); + } + + [Test] + public void Evaluate_LoopingCurveCreatedByJsonUtility_ReturnsLoopedValue() + { + using var original = CreateLoopingCurve(1f, 0f); + using var copy = JsonUtility.FromJson(JsonUtility.ToJson(original)); + + Assert.AreEqual(0.216f, copy.Evaluate(0.9f), 1e-5f); + } + + [Test] + public void LoopingCurveOverwrittenByJsonUtility_ReturnsOverwrittenValues() + { + using var target = CreateLoopingCurve(1f, 0f); + using var source = CreateLoopingCurve(0f, 1f); + target.GetTexture(); + + JsonUtility.FromJsonOverwrite(JsonUtility.ToJson(source), target); + + Assert.AreEqual(source.Evaluate(0.9f), target.Evaluate(0.9f), 1e-5f, + "Evaluate returned the curve from before the overwrite."); + CollectionAssert.AreEqual(source.GetTexture().GetPixels(), target.GetTexture().GetPixels(), + "GetTexture returned the texture from before the overwrite."); + } + } +} diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/TextureCurveTests.cs.meta b/Packages/com.unity.render-pipelines.core/Tests/Editor/TextureCurveTests.cs.meta new file mode 100644 index 00000000000..050989a08e3 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/TextureCurveTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7850d0a890274a5cb58079b04ed2a193 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/UnifiedRayTracing/GeometryPoolTests.cs b/Packages/com.unity.render-pipelines.core/Tests/Editor/UnifiedRayTracing/GeometryPoolTests.cs deleted file mode 100644 index bf29c20b9c2..00000000000 --- a/Packages/com.unity.render-pipelines.core/Tests/Editor/UnifiedRayTracing/GeometryPoolTests.cs +++ /dev/null @@ -1,112 +0,0 @@ -using NUnit.Framework; -using Unity.Mathematics; - -namespace UnityEngine.Rendering.UnifiedRayTracing.Tests -{ - internal class GeometryPoolTests - { - RayTracingResources m_Resources; - - [SetUp] - public void SetUp() - { - if (!SystemInfo.supportsComputeShaders) - Assert.Ignore("Cannot run test on this Graphics API. Compute shaders are not supported"); - - m_Resources = new RayTracingResources(); - m_Resources.Load(); - } - - static Mesh CreateTriangleStripMesh(int vertexCount, float zOffset) - { - var vertices = new Vector3[vertexCount]; - for (int i = 0; i < vertexCount; ++i) - vertices[i] = new Vector3(i, i % 2, zOffset); - - var indices = new int[(vertexCount - 2) * 3]; - for (int i = 0; i < vertexCount - 2; ++i) - { - indices[i * 3] = i; - indices[i * 3 + 1] = i + 1; - indices[i * 3 + 2] = i + 2; - } - - var mesh = new Mesh { indexFormat = IndexFormat.UInt32 }; - mesh.vertices = vertices; - mesh.SetIndices(indices, MeshTopology.Triangles, 0); - mesh.UploadMeshData(false); - return mesh; - } - - static void AssertPoolContainsMesh(GeometryPool pool, GeometryPoolHandle handle, Mesh mesh) - { - var meshChunk = pool.GetEntryGeomAllocation(handle).meshChunks[0]; - int vertexStrideInDwords = GeometryPool.GetVertexByteSize() / 4; - - var vertexData = new uint[pool.globalVertexBuffer.count]; - pool.globalVertexBuffer.GetData(vertexData); - var expectedVertices = mesh.vertices; - for (int i = 0; i < expectedVertices.Length; ++i) - { - int dwordOffset = (meshChunk.vertexAlloc.block.offset + i) * vertexStrideInDwords; - var actual = math.asfloat(new uint3(vertexData[dwordOffset], vertexData[dwordOffset + 1], vertexData[dwordOffset + 2])); - Assert.AreEqual((float3)expectedVertices[i], actual, $"Vertex {i} of mesh {mesh.name}"); - } - - var indexData = new uint[pool.globalIndexBuffer.count]; - pool.globalIndexBuffer.GetData(indexData); - var expectedIndices = mesh.GetIndices(0); - for (int i = 0; i < expectedIndices.Length; ++i) - Assert.AreEqual((uint)expectedIndices[i], indexData[meshChunk.indexAlloc.block.offset + i], $"Index {i} of mesh {mesh.name}"); - - var meshChunkTable = new GeoPoolMeshChunk[pool.globalMeshChunkTableEntryBuffer.count]; - pool.globalMeshChunkTableEntryBuffer.GetData(meshChunkTable); - var tableEntry = meshChunkTable[pool.GetEntryGeomAllocation(handle).meshChunkTableAlloc.block.offset]; - Assert.AreEqual(meshChunk.vertexAlloc.block.offset, tableEntry.vertexOffset); - Assert.AreEqual(expectedVertices.Length, tableEntry.vertexCount); - Assert.AreEqual(meshChunk.indexAlloc.block.offset, tableEntry.indexOffset); - Assert.AreEqual(expectedIndices.Length, tableEntry.indexCount); - } - - [Test] - public void Register_MeshExceedsInitialCapacity_GrowsAndPreservesExistingData() - { - const int firstMeshVertexCount = 4; - var desc = new GeometryPoolDesc - { - vertexPoolByteSize = firstMeshVertexCount * GeometryPool.GetVertexByteSize(), - indexPoolByteSize = (firstMeshVertexCount - 2) * 3 * GeometryPool.GetIndexByteSize(), - meshChunkTablesByteSize = GeometryPool.GetMeshChunkTableEntryByteSize() - }; - - var firstMesh = CreateTriangleStripMesh(firstMeshVertexCount, 1.0f); - firstMesh.name = "first"; - var secondMesh = CreateTriangleStripMesh(1000, 2.0f); - secondMesh.name = "second"; - var pool = new GeometryPool(desc, m_Resources.geometryPoolKernels, m_Resources.copyBuffer); - try - { - Assert.IsTrue(pool.Register(firstMesh, out var firstHandle)); - pool.SendGpuCommands(); - int initialVertexCapacity = pool.verticesCount; - int initialIndexCapacity = pool.indicesCount; - int initialMeshChunkTableCapacity = pool.meshChunkTablesEntryCount; - - Assert.IsTrue(pool.Register(secondMesh, out var secondHandle)); - pool.SendGpuCommands(); - - Assert.Greater(pool.verticesCount, initialVertexCapacity); - Assert.Greater(pool.indicesCount, initialIndexCapacity); - Assert.Greater(pool.meshChunkTablesEntryCount, initialMeshChunkTableCapacity); - AssertPoolContainsMesh(pool, firstHandle, firstMesh); - AssertPoolContainsMesh(pool, secondHandle, secondMesh); - } - finally - { - pool.Dispose(); - UnityEngine.Object.DestroyImmediate(firstMesh); - UnityEngine.Object.DestroyImmediate(secondMesh); - } - } - } -} diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/UnifiedRayTracing/GeometryPoolTests.cs.meta b/Packages/com.unity.render-pipelines.core/Tests/Editor/UnifiedRayTracing/GeometryPoolTests.cs.meta deleted file mode 100644 index 8cc92050024..00000000000 --- a/Packages/com.unity.render-pipelines.core/Tests/Editor/UnifiedRayTracing/GeometryPoolTests.cs.meta +++ /dev/null @@ -1,2 +0,0 @@ -fileFormatVersion: 2 -guid: c856d6ea66814c3daf44d8b5dd624f17 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/Volumes/AnimationCurveParameterTests.cs b/Packages/com.unity.render-pipelines.core/Tests/Editor/Volumes/AnimationCurveParameterTests.cs new file mode 100644 index 00000000000..2e557d41cb0 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/Volumes/AnimationCurveParameterTests.cs @@ -0,0 +1,39 @@ +using NUnit.Framework; + +namespace UnityEngine.Rendering.Tests +{ + class AnimationCurveParameterTests + { + [Test] + public void Clone_PreservesKeysAndWrapModes() + { + var curve = AnimationCurve.Linear(0f, 0f, 1f, 1f); + curve.preWrapMode = WrapMode.Loop; + curve.postWrapMode = WrapMode.PingPong; + var source = new AnimationCurveParameter(curve, true); + + var clone = (AnimationCurveParameter)source.Clone(); + + Assert.AreEqual(source.overrideState, clone.overrideState); + Assert.AreEqual(WrapMode.Loop, clone.value.preWrapMode); + Assert.AreEqual(WrapMode.PingPong, clone.value.postWrapMode); + Assert.AreEqual(source.value.keys, clone.value.keys); + Assert.AreEqual(source.value.Evaluate(-0.25f), clone.value.Evaluate(-0.25f), 1e-5f); + Assert.AreEqual(source.value.Evaluate(1.25f), clone.value.Evaluate(1.25f), 1e-5f); + } + + [Test] + public void Clone_DoesNotShareCurveInstance() + { + var source = new AnimationCurveParameter(AnimationCurve.Linear(0f, 0f, 1f, 1f)); + + var clone = (AnimationCurveParameter)source.Clone(); + clone.value.postWrapMode = WrapMode.Loop; + clone.value.AddKey(0.5f, 2f); + + Assert.AreNotSame(source.value, clone.value); + Assert.AreEqual(WrapMode.ClampForever, source.value.postWrapMode); + Assert.AreEqual(2, source.value.length); + } + } +} diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/Volumes/AnimationCurveParameterTests.cs.meta b/Packages/com.unity.render-pipelines.core/Tests/Editor/Volumes/AnimationCurveParameterTests.cs.meta new file mode 100644 index 00000000000..5e9610a68fc --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/Volumes/AnimationCurveParameterTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0a3f089927374845b1738192fcefbbc2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/XR/XRLayoutTests.cs b/Packages/com.unity.render-pipelines.core/Tests/Editor/XR/XRLayoutTests.cs index e7e0b42dbdb..86ae3505dfb 100644 --- a/Packages/com.unity.render-pipelines.core/Tests/Editor/XR/XRLayoutTests.cs +++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/XR/XRLayoutTests.cs @@ -1,5 +1,6 @@ -using NUnit.Framework; +using System; using System.Collections.Generic; +using NUnit.Framework; using UnityEngine.Experimental.Rendering; using UnityEngine.XR; @@ -30,6 +31,7 @@ public void Setup() public void TearDown() { m_LayoutTest.Clear(); + XRSystem.ClearCameraRenderTargets(); Object.DestroyImmediate(m_Camera.gameObject); @@ -205,5 +207,273 @@ public void TwoPassQuadViewsLayout_HasPeripheralAndFovealPasses() Assert.IsTrue(foveal.isLastCameraPass); Assert.IsTrue(foveal.isQuadViewInnerPass); } + + const ulong k_ContainerA = 1000; + const ulong k_ContainerB = 2000; + + static Camera CreateSecondCamera() => new GameObject(nameof(XRLayoutTests) + ".Second").AddComponent(); + + [Test] + public void Registry_Empty_HasNoTargetsAndCameraUnbound() + { + Assert.IsFalse(XRSystem.TryGetRenderTarget(m_Camera, out _)); + Assert.IsFalse(XRSystem.TryGetCameraForTarget(k_ContainerA, out _)); + } + + [Test] + public void Registry_SetThenGet_RoundTrips() + { + XRSystem.SetCameraRenderTarget(k_ContainerA, m_Camera); + + Assert.IsTrue(XRSystem.TryGetRenderTarget(m_Camera, out var renderTargetId)); + Assert.AreEqual(k_ContainerA, renderTargetId); + Assert.IsTrue(XRSystem.TryGetCameraForTarget(k_ContainerA, out var camera)); + Assert.AreEqual(m_Camera, camera); + } + + [Test] + public void Registry_ClearSingle_RemovesOnlyThatBinding() + { + var second = CreateSecondCamera(); + try + { + XRSystem.SetCameraRenderTarget(k_ContainerA, m_Camera); + XRSystem.SetCameraRenderTarget(k_ContainerB, second); + XRSystem.ClearCameraRenderTarget(k_ContainerA); + + Assert.IsFalse(XRSystem.TryGetRenderTarget(m_Camera, out _)); + Assert.IsFalse(XRSystem.TryGetCameraForTarget(k_ContainerA, out _)); + Assert.IsTrue(XRSystem.TryGetRenderTarget(second, out var renderTargetId)); + Assert.AreEqual(k_ContainerB, renderTargetId); + } + finally + { + Object.DestroyImmediate(second.gameObject); + } + } + + [Test] + public void Registry_ClearAll_RemovesEveryBinding() + { + var second = CreateSecondCamera(); + try + { + XRSystem.SetCameraRenderTarget(k_ContainerA, m_Camera); + XRSystem.SetCameraRenderTarget(k_ContainerB, second); + XRSystem.ClearCameraRenderTargets(); + + Assert.IsFalse(XRSystem.TryGetRenderTarget(m_Camera, out _)); + Assert.IsFalse(XRSystem.TryGetRenderTarget(second, out _)); + } + finally + { + Object.DestroyImmediate(second.gameObject); + } + } + + [Test] + public void Registry_SameCameraTwoTargets_IsRejected() + { + XRSystem.SetCameraRenderTarget(k_ContainerA, m_Camera); + + Assert.Throws(() => XRSystem.SetCameraRenderTarget(k_ContainerB, m_Camera)); + Assert.IsFalse(XRSystem.TryGetCameraForTarget(k_ContainerB, out _)); + Assert.IsTrue(XRSystem.TryGetRenderTarget(m_Camera, out var renderTargetId)); + Assert.AreEqual(k_ContainerA, renderTargetId); + } + + [Test] + public void Registry_SameTargetTwoCameras_IsRejected() + { + var second = CreateSecondCamera(); + try + { + XRSystem.SetCameraRenderTarget(k_ContainerA, m_Camera); + + Assert.Throws(() => XRSystem.SetCameraRenderTarget(k_ContainerA, second)); + Assert.IsTrue(XRSystem.TryGetCameraForTarget(k_ContainerA, out var camera)); + Assert.AreEqual(m_Camera, camera); + Assert.IsFalse(XRSystem.TryGetRenderTarget(second, out _)); + } + finally + { + Object.DestroyImmediate(second.gameObject); + } + } + + [Test] + public void Registry_NullCamera_IsRejected() + { + Assert.Throws(() => XRSystem.SetCameraRenderTarget(k_ContainerA, null)); + Assert.IsFalse(XRSystem.TryGetCameraForTarget(k_ContainerA, out _)); + } + + [Test] + public void Registry_DefaultTargetId_IsReserved() + { + Assert.Throws(() => XRSystem.SetCameraRenderTarget(0, m_Camera)); + Assert.IsFalse(XRSystem.TryGetRenderTarget(m_Camera, out _)); + } + + public static IEnumerable s_TestCasesCollectTargetPasses + { + get + { + yield return new TestCaseData(new ulong[] { k_ContainerA, k_ContainerA, k_ContainerB }, k_ContainerA, new[] { 0, 1 }).SetName("Contiguous_FirstContainer"); + yield return new TestCaseData(new ulong[] { k_ContainerA, k_ContainerA, k_ContainerB }, k_ContainerB, new[] { 2 }).SetName("Contiguous_SecondContainer"); + yield return new TestCaseData(new ulong[] { k_ContainerA, k_ContainerB, k_ContainerA, k_ContainerB }, k_ContainerA, new[] { 0, 2 }).SetName("Interleaved_FirstContainer"); + yield return new TestCaseData(new ulong[] { k_ContainerA, k_ContainerB, k_ContainerA, k_ContainerB }, k_ContainerB, new[] { 1, 3 }).SetName("Interleaved_SecondContainer"); + yield return new TestCaseData(new ulong[] { k_ContainerA, k_ContainerA, k_ContainerA }, k_ContainerA, new[] { 0, 1, 2 }).SetName("MoreThanTwoMatches_ReturnsAll"); + yield return new TestCaseData(new ulong[] { k_ContainerB, k_ContainerB }, k_ContainerA, new int[0]).SetName("HiddenContainer_NoMatch"); + yield return new TestCaseData(new ulong[0], k_ContainerA, new int[0]).SetName("NoPasses_NoMatch"); + yield return new TestCaseData(new ulong[] { 0, 0 }, 0UL, new[] { 0, 1 }).SetName("DefaultTarget_AllDefaultPasses_ReturnsAll"); + yield return new TestCaseData(new ulong[] { 0, k_ContainerA, k_ContainerA }, 0UL, new[] { 0 }).SetName("DefaultTarget_IgnoresRenderTargetPasses"); + yield return new TestCaseData(new ulong[] { k_ContainerA, k_ContainerB }, 0UL, new int[0]).SetName("DefaultTarget_OnlyRenderTargetPasses_NoMatch"); + yield return new TestCaseData(new ulong[] { k_ContainerA, ulong.MaxValue }, ulong.MaxValue, new[] { 1 }).SetName("MaxTargetId_Matches"); + } + } + + [Test] + [TestCaseSource(nameof(s_TestCasesCollectTargetPasses))] + public void CollectTargetPasses_SelectsExactlyTheTargetPasses(ulong[] passTargetIds, ulong target, int[] expected) + { + var matchedPasses = new int[passTargetIds.Length]; + int matchCount = XRSystem.CollectTargetPasses(passTargetIds, target, matchedPasses); + + CollectionAssert.AreEqual(expected, matchedPasses.AsSpan(0, matchCount).ToArray()); + } + + public static IEnumerable s_TestCasesClassifyLayout + { + get + { + yield return new TestCaseData(new int[0], true, false, XRLayoutType.Unknown).SetName("NoPasses_Unknown"); + yield return new TestCaseData(new[] { 1 }, true, false, XRLayoutType.OnePassOneView).SetName("OnePass_OneView_OnePassOneView"); + yield return new TestCaseData(new[] { 2 }, true, false, XRLayoutType.SinglePassStereo).SetName("OnePass_TwoViews_SinglePass_SinglePassStereo"); + yield return new TestCaseData(new[] { 2 }, false, false, XRLayoutType.TwoPassStereo).SetName("OnePass_TwoViews_NoSinglePass_TwoPassStereo"); + yield return new TestCaseData(new[] { 1, 1 }, false, false, XRLayoutType.TwoPassStereo).SetName("TwoPasses_OneViewEach_TwoPassStereo"); + yield return new TestCaseData(new[] { 2, 2 }, true, false, XRLayoutType.TwoPassQuadViews).SetName("TwoPasses_TwoViewsEach_SinglePass_TwoPassQuadViews"); + yield return new TestCaseData(new[] { 2, 2 }, false, false, XRLayoutType.Unknown).SetName("TwoPasses_TwoViewsEach_NoSinglePass_Unknown"); + yield return new TestCaseData(new[] { 1, 2 }, true, false, XRLayoutType.Unknown).SetName("TwoPasses_MixedViews_Unknown"); + yield return new TestCaseData(new[] { 2, 2, 2 }, true, false, XRLayoutType.Unknown).SetName("ThreePasses_Unknown"); + yield return new TestCaseData(new[] { 2 }, true, true, XRLayoutType.SinglePassStereo).SetName("RenderTarget_OnePass_TwoViews_SinglePassStereo"); + yield return new TestCaseData(new[] { 1, 1 }, false, true, XRLayoutType.TwoPassStereo).SetName("RenderTarget_TwoPasses_OneViewEach_TwoPassStereo"); + yield return new TestCaseData(new[] { 2, 2 }, true, true, XRLayoutType.Unknown).SetName("RenderTarget_TwoPasses_TwoViewsEach_QuadViewsRejected"); + } + } + + [Test] + [TestCaseSource(nameof(s_TestCasesClassifyLayout))] + public void ClassifyLayout_ReturnsExpectedLayoutType(int[] viewCountsPerPass, bool canUseSinglePass, bool hasRenderTarget, XRLayoutType expected) + { + Assert.AreEqual(expected, XRSystem.ClassifyLayout(viewCountsPerPass, canUseSinglePass, hasRenderTarget)); + } + + internal struct MockRenderPass + { + public ulong renderTargetId; + public int renderParamCount; + public bool canUseSinglePass; + + public MockRenderPass(ulong renderTargetId, int renderParamCount, bool canUseSinglePass) + { + this.renderTargetId = renderTargetId; + this.renderParamCount = renderParamCount; + this.canUseSinglePass = canUseSinglePass; + } + } + + // Mirrors the matching and classification steps of XRSystem.CreateDefaultLayout + static XRLayoutType ClassifyContainer(MockRenderPass[] passes, ulong target, out int matchCount) + { + var passTargetIds = new ulong[passes.Length]; + for (int i = 0; i < passes.Length; ++i) + passTargetIds[i] = passes[i].renderTargetId; + + var matchedPasses = new int[passes.Length]; + matchCount = XRSystem.CollectTargetPasses(passTargetIds, target, matchedPasses); + + var viewCounts = new int[matchCount]; + bool canUseSinglePass = true; + for (int i = 0; i < matchCount; ++i) + { + viewCounts[i] = passes[matchedPasses[i]].renderParamCount; + canUseSinglePass &= passes[matchedPasses[i]].canUseSinglePass; + } + return XRSystem.ClassifyLayout(viewCounts, canUseSinglePass, target != 0); + } + + public static IEnumerable s_TestCasesContainerLayouts + { + get + { + yield return new TestCaseData( + new[] { new MockRenderPass(k_ContainerA, 2, true), new MockRenderPass(k_ContainerB, 2, true) }, + XRLayoutType.SinglePassStereo, 1, XRLayoutType.SinglePassStereo, 1).SetName("BothSinglePassStereo"); + yield return new TestCaseData( + new[] { new MockRenderPass(k_ContainerA, 1, false), new MockRenderPass(k_ContainerA, 1, false), new MockRenderPass(k_ContainerB, 1, false), new MockRenderPass(k_ContainerB, 1, false) }, + XRLayoutType.TwoPassStereo, 2, XRLayoutType.TwoPassStereo, 2).SetName("BothTwoPassStereo_Contiguous"); + yield return new TestCaseData( + new[] { new MockRenderPass(k_ContainerA, 1, false), new MockRenderPass(k_ContainerB, 1, false), new MockRenderPass(k_ContainerA, 1, false), new MockRenderPass(k_ContainerB, 1, false) }, + XRLayoutType.TwoPassStereo, 2, XRLayoutType.TwoPassStereo, 2).SetName("BothTwoPassStereo_Interleaved"); + yield return new TestCaseData( + new[] { new MockRenderPass(k_ContainerA, 2, true), new MockRenderPass(k_ContainerB, 1, false), new MockRenderPass(k_ContainerB, 1, false) }, + XRLayoutType.SinglePassStereo, 1, XRLayoutType.TwoPassStereo, 2).SetName("MixedSinglePassAndTwoPass"); + yield return new TestCaseData( + new[] { new MockRenderPass(k_ContainerA, 2, true), new MockRenderPass(k_ContainerB, 2, false) }, + XRLayoutType.SinglePassStereo, 1, XRLayoutType.TwoPassStereo, 1).SetName("SecondContainerFallsBackToTwoPass"); + yield return new TestCaseData( + new[] { new MockRenderPass(k_ContainerA, 1, false), new MockRenderPass(k_ContainerB, 1, false) }, + XRLayoutType.OnePassOneView, 1, XRLayoutType.OnePassOneView, 1).SetName("BothOnePassOneView"); + yield return new TestCaseData( + new[] { new MockRenderPass(k_ContainerA, 2, true), new MockRenderPass(k_ContainerA, 2, true), new MockRenderPass(k_ContainerB, 2, true), new MockRenderPass(k_ContainerB, 2, true) }, + XRLayoutType.Unknown, 2, XRLayoutType.Unknown, 2).SetName("BothQuadViews_Contiguous_Rejected"); + yield return new TestCaseData( + new[] { new MockRenderPass(k_ContainerA, 2, true), new MockRenderPass(k_ContainerB, 2, true), new MockRenderPass(k_ContainerA, 2, true), new MockRenderPass(k_ContainerB, 2, true) }, + XRLayoutType.Unknown, 2, XRLayoutType.Unknown, 2).SetName("BothQuadViews_Interleaved_Rejected"); + yield return new TestCaseData( + new[] { new MockRenderPass(k_ContainerA, 2, true), new MockRenderPass(k_ContainerB, 1, false), new MockRenderPass(k_ContainerB, 1, false), new MockRenderPass(k_ContainerB, 1, false) }, + XRLayoutType.SinglePassStereo, 1, XRLayoutType.Unknown, 3).SetName("ContainerWithThreePasses_Unknown"); + } + } + + [Test] + [TestCaseSource(nameof(s_TestCasesContainerLayouts))] + public void ContainerPasses_ClassifyToExpectedLayoutPerContainer(MockRenderPass[] passes, XRLayoutType expectedLayoutA, int expectedPassCountA, XRLayoutType expectedLayoutB, int expectedPassCountB) + { + Assert.AreEqual(expectedLayoutA, ClassifyContainer(passes, k_ContainerA, out int passCountA)); + Assert.AreEqual(expectedPassCountA, passCountA); + + Assert.AreEqual(expectedLayoutB, ClassifyContainer(passes, k_ContainerB, out int passCountB)); + Assert.AreEqual(expectedPassCountB, passCountB); + } + + public static IEnumerable s_TestCasesUnregisteredCamera + { + get + { + yield return new TestCaseData( + new[] { new MockRenderPass(0, 1, false), new MockRenderPass(0, 1, false) }, + XRLayoutType.TwoPassStereo, 2).SetName("NoRenderTargets_TakesAllPasses"); + yield return new TestCaseData( + new[] { new MockRenderPass(0, 2, true), new MockRenderPass(0, 2, true) }, + XRLayoutType.TwoPassQuadViews, 2).SetName("NoRenderTargets_QuadViewsAllowed"); + yield return new TestCaseData( + new[] { new MockRenderPass(0, 2, true), new MockRenderPass(k_ContainerA, 2, true), new MockRenderPass(k_ContainerB, 2, true) }, + XRLayoutType.SinglePassStereo, 1).SetName("MainViewAndContainers_TakesMainViewOnly"); + yield return new TestCaseData( + new[] { new MockRenderPass(k_ContainerA, 2, true), new MockRenderPass(k_ContainerB, 2, true) }, + XRLayoutType.Unknown, 0).SetName("ContainersOnly_NoPasses"); + } + } + + [Test] + [TestCaseSource(nameof(s_TestCasesUnregisteredCamera))] + public void UnregisteredCamera_OnlyTakesDefaultTargetPasses(MockRenderPass[] passes, XRLayoutType expectedLayout, int expectedPassCount) + { + // CreateDefaultLayout returns before classifying when no passes match, so the camera gets no XR passes + Assert.AreEqual(expectedLayout, ClassifyContainer(passes, 0, out int passCount)); + Assert.AreEqual(expectedPassCount, passCount); + } } } diff --git a/Packages/com.unity.render-pipelines.core/Tests/Runtime/Debugging/ProfilingSamplerWithCommandBufferTests.cs b/Packages/com.unity.render-pipelines.core/Tests/Runtime/Debugging/ProfilingSamplerWithCommandBufferTests.cs index e58b4af9ea6..be7b4ac4294 100644 --- a/Packages/com.unity.render-pipelines.core/Tests/Runtime/Debugging/ProfilingSamplerWithCommandBufferTests.cs +++ b/Packages/com.unity.render-pipelines.core/Tests/Runtime/Debugging/ProfilingSamplerWithCommandBufferTests.cs @@ -105,8 +105,12 @@ public IEnumerator CommandBufferBeginSampleWithObject_GpuSamples_ReturnsNonZeroC yield break; // UGK-2993 - if (UnityGraphicsKernelTestUtils.IsForcedUGK() && Application.platform == RuntimePlatform.Switch) - IgnoreWithLog("GPU recorder samples are not delivered under UGK on Switch."); + if (UnityGraphicsKernelTestUtils.IsForcedUGK() && (Application.platform == RuntimePlatform.Switch || Application.platform == RuntimePlatform.PS5)) + IgnoreWithLog("GPU recorder samples are not delivered under UGK on Switch and PS5."); + + // UUM-153917: same in the Windows editor under UGK on D3D12. + if (UnityGraphicsKernelTestUtils.IsForcedUGK() && Application.platform == RuntimePlatform.WindowsEditor && SystemInfo.graphicsDeviceType == GraphicsDeviceType.Direct3D12) + IgnoreWithLog("https://jira.unity3d.com/browse/UUM-153917"); var sampler = new ProfilingSampler(nameof(CommandBufferBeginSampleWithObject_GpuSamples_ReturnsNonZeroCount)); using var recorder = ProfilerRecorder.StartNew(ProfilerCategory.Render, sampler.name, 1, ProfilerRecorderOptions.GpuRecorder | ProfilerRecorderOptions.Default); @@ -134,8 +138,12 @@ public IEnumerator CommandBufferBeginSample_GpuSamples_ReturnsNonZeroCount() yield break; // UGK-2993 - if (UnityGraphicsKernelTestUtils.IsForcedUGK() && Application.platform == RuntimePlatform.Switch) - IgnoreWithLog("GPU recorder samples are not delivered under UGK on Switch."); + if (UnityGraphicsKernelTestUtils.IsForcedUGK() && (Application.platform == RuntimePlatform.Switch || Application.platform == RuntimePlatform.PS5)) + IgnoreWithLog("GPU recorder samples are not delivered under UGK on Switch and PS5."); + + // UUM-153917: same in the Windows editor under UGK on D3D12. + if (UnityGraphicsKernelTestUtils.IsForcedUGK() && Application.platform == RuntimePlatform.WindowsEditor && SystemInfo.graphicsDeviceType == GraphicsDeviceType.Direct3D12) + IgnoreWithLog("https://jira.unity3d.com/browse/UUM-153917"); var sampler = new ProfilingSampler(nameof(CommandBufferBeginSample_GpuSamples_ReturnsNonZeroCount)); using var recorder = ProfilerRecorder.StartNew(ProfilerCategory.Render, sampler.name, 1, ProfilerRecorderOptions.GpuRecorder | ProfilerRecorderOptions.Default); diff --git a/Packages/com.unity.render-pipelines.core/Tests/Runtime/PathTracing/CubemapRenderTests.cs b/Packages/com.unity.render-pipelines.core/Tests/Runtime/PathTracing/CubemapRenderTests.cs new file mode 100644 index 00000000000..15740795106 --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Tests/Runtime/PathTracing/CubemapRenderTests.cs @@ -0,0 +1,199 @@ +#if UNITY_EDITOR +using System; +using System.Collections; +using NUnit.Framework; +using UnityEditor; +using UnityEngine.PathTracing.Core; +using UnityEngine.Rendering; +using UnityEngine.TestTools; +#endif + +namespace UnityEngine.PathTracing.Tests +{ + // The shader sources stay outside the UNITY_EDITOR block. Player builds skip that block, and the compiler + // then reads the #if lines inside the shader strings as C# preprocessor directives + internal partial class CubemapRenderTests + { + // CreateUncompiledShader replaces UNIQUE_ID with a new GUID, so the shaders are never in the shader cache yet + const string k_SolidColorShaderSource = +@"Shader ""Hidden/Tests/CubemapRenderUncompiledSolidColor"" +{ + Properties { _Color (""Color"", Vector) = (0,0,0,0) } + SubShader + { + Pass + { + ZTest Always Cull Off ZWrite Off + HLSLPROGRAM + #pragma vertex Vert + #pragma fragment Frag + // UNIQUE_ID + float4 _Color; + float4 Vert(uint vertexID : SV_VertexID) : SV_POSITION + { + float2 uv = float2((vertexID << 1) & 2, vertexID & 2); + return float4(uv * 2.0 - 1.0, 0.0, 1.0); + } + float4 Frag() : SV_Target { return _Color; } + ENDHLSL + } + } + Fallback Off +}"; + + // Outputs magenta unless the no-sun keyword is enabled, like the draw does + const string k_CubemapMaterialShaderSource = +@"Shader ""Hidden/Tests/CubemapRenderUncompiledCubemapMaterial"" +{ + Properties { _Color (""Color"", Vector) = (0,0,0,0) } + SubShader + { + Pass + { + ZTest Always Cull Off ZWrite Off + HLSLPROGRAM + #pragma vertex Vert + #pragma fragment Frag + #pragma multi_compile_local __ _SUNDISK_NONE + // UNIQUE_ID + float4 _Color; + float4 Vert(float3 position : POSITION) : SV_POSITION { return float4(position.xy, 0.5, 1.0); } + float4 Frag() : SV_Target + { + #if defined(_SUNDISK_NONE) + return _Color; + #else + return float4(1.0, 0.0, 1.0, 1.0); + #endif + } + ENDHLSL + } + } + Fallback Off +}"; + } + +#if UNITY_EDITOR + internal partial class CubemapRenderTests + { + const float k_TimeoutSeconds = 60.0f; + const int k_CubemapMaterialResolution = 4; + + bool m_OldAsyncShaderCompilation; + bool m_OldAllowAsync; + Shader m_SolidColorShader; + Shader m_CubemapMaterialShader; + Material m_CubemapMaterial; + Mesh m_FullscreenMesh; + CubemapRender m_CubemapRender; + CommandBuffer m_Cmd; + + [SetUp] + public void SetUp() + { + m_OldAsyncShaderCompilation = EditorSettings.asyncShaderCompilation; + m_OldAllowAsync = ShaderUtil.allowAsyncCompilation; + EditorSettings.asyncShaderCompilation = true; + ShaderUtil.allowAsyncCompilation = true; + + m_SolidColorShader = CreateUncompiledShader(k_SolidColorShaderSource); + m_CubemapMaterialShader = CreateUncompiledShader(k_CubemapMaterialShaderSource); + m_CubemapMaterial = new Material(m_CubemapMaterialShader); + + m_FullscreenMesh = new Mesh + { + vertices = new[] { new Vector3(-1, -1, 0), new Vector3(3, -1, 0), new Vector3(-1, 3, 0) }, + triangles = new[] { 0, 1, 2 }, + bounds = new Bounds(Vector3.zero, Vector3.one * 1000.0f), + }; + + m_CubemapRender = new CubemapRender(m_FullscreenMesh, m_FullscreenMesh, m_SolidColorShader); + m_Cmd = new CommandBuffer { name = "CubemapRenderTests" }; + } + + [TearDown] + public void TearDown() + { + m_Cmd?.Release(); + m_CubemapRender?.Dispose(); + Object.DestroyImmediate(m_FullscreenMesh); + Object.DestroyImmediate(m_CubemapMaterial); + Object.DestroyImmediate(m_CubemapMaterialShader); + Object.DestroyImmediate(m_SolidColorShader); + ShaderUtil.allowAsyncCompilation = m_OldAllowAsync; + EditorSettings.asyncShaderCompilation = m_OldAsyncShaderCompilation; + } + + // A unique source guarantees the shader is not in the shader cache yet + static Shader CreateUncompiledShader(string source) + => ShaderUtil.CreateShaderAsset(source.Replace("UNIQUE_ID", Guid.NewGuid().ToString()), false); + + void UpdateCubemapRender(int resolution) + { + Assert.IsTrue(ShaderUtil.allowAsyncCompilation, "The test expects async shader compilation to be enabled."); + m_Cmd.Clear(); + m_CubemapRender.Update(m_Cmd, null, resolution, out _); + Graphics.ExecuteCommandBuffer(m_Cmd); + } + + IEnumerator UpdateUntilCubemapIsUpToDate(int resolution) + { + float startTime = Time.realtimeSinceStartup; + while (m_CubemapRender.Hash == 0) + { + if (Time.realtimeSinceStartup - startTime > k_TimeoutSeconds) + Assert.Fail($"The environment cubemap was not drawn within {k_TimeoutSeconds} seconds."); + + UpdateCubemapRender(resolution); + yield return null; + } + } + + void AssertCubemapEquals(Color expected) + { + var cubemap = m_CubemapRender.GetCubemap(); + var request = AsyncGPUReadback.Request(cubemap, 0, 0, 1, 0, 1, 0, 6); + request.WaitForCompletion(); + Assert.IsFalse(request.hasError, "Failed to read back the environment cubemap."); + + for (int face = 0; face < 6; ++face) + { + Color actual = request.GetData(face)[0]; + string message = $"Face {(CubemapFace)face} is {actual} but expected {expected}. The cubemap was marked up to date without being drawn correctly."; + Assert.AreEqual(expected.r, actual.r, 1e-4f, message); + Assert.AreEqual(expected.g, actual.g, 1e-4f, message); + Assert.AreEqual(expected.b, actual.b, 1e-4f, message); + } + } + + [UnityTest] + public IEnumerator ColorMode_WhenShaderIsCompilingAsync_CubemapIsOnlyMarkedUpToDateOnceDrawn() + { + var expected = new Color(0.8f, 0.3f, 0.1f, 1.0f); + m_CubemapRender.SetMode(CubemapRender.Mode.Color); + m_CubemapRender.SetColor(expected); + + yield return UpdateUntilCubemapIsUpToDate(1); + + AssertCubemapEquals(expected); + } + + [UnityTest] + public IEnumerator MaterialMode_WhenShaderIsCompilingAsync_DefersDrawInsteadOfCompilingSynchronously() + { + var expected = new Color(0.2f, 0.5f, 0.9f, 1.0f); + m_CubemapMaterial.SetVector("_Color", expected); + m_CubemapRender.SetMode(CubemapRender.Mode.Material); + m_CubemapRender.SetMaterial(m_CubemapMaterial); + + UpdateCubemapRender(k_CubemapMaterialResolution); + Assert.AreEqual(0, m_CubemapRender.Hash, "The first frame should defer the draw while the cubemap material shader compiles, not block on a synchronous compile."); + + yield return UpdateUntilCubemapIsUpToDate(k_CubemapMaterialResolution); + + AssertCubemapEquals(expected); + Assert.IsFalse(m_CubemapMaterial.IsKeywordEnabled("_SUNDISK_NONE"), "The no-sun keyword should not stay enabled on the cubemap material."); + } + } +#endif +} diff --git a/Packages/com.unity.render-pipelines.core/Tests/Runtime/PathTracing/CubemapRenderTests.cs.meta b/Packages/com.unity.render-pipelines.core/Tests/Runtime/PathTracing/CubemapRenderTests.cs.meta new file mode 100644 index 00000000000..51643ec65ae --- /dev/null +++ b/Packages/com.unity.render-pipelines.core/Tests/Runtime/PathTracing/CubemapRenderTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 78b60cedc8c24bb4a7706aee1f9437b0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.core/Tests/Runtime/PathTracing/Unity.PathTracing.Runtime.Tests.asmdef b/Packages/com.unity.render-pipelines.core/Tests/Runtime/PathTracing/Unity.PathTracing.Runtime.Tests.asmdef index 51201104881..42ab3518b21 100644 --- a/Packages/com.unity.render-pipelines.core/Tests/Runtime/PathTracing/Unity.PathTracing.Runtime.Tests.asmdef +++ b/Packages/com.unity.render-pipelines.core/Tests/Runtime/PathTracing/Unity.PathTracing.Runtime.Tests.asmdef @@ -5,7 +5,8 @@ "GUID:214c0945bb158c940aada223f3223ee8", "GUID:c49c619b6af2be941af9bcbca2641964", "GUID:d8b63aba1907145bea998dd612889d6b", - "GUID:df380645f10b7bc4b97d4f5eb6303d95" + "GUID:df380645f10b7bc4b97d4f5eb6303d95", + "GUID:27619889b8ba8c24980f49ee34dbb44a" ], "includePlatforms": [], "excludePlatforms": [], diff --git a/Packages/com.unity.render-pipelines.core/Tests/Runtime/RuntimeProfilerTests.cs b/Packages/com.unity.render-pipelines.core/Tests/Runtime/RuntimeProfilerTests.cs index 56744b521fc..c762ae19878 100644 --- a/Packages/com.unity.render-pipelines.core/Tests/Runtime/RuntimeProfilerTests.cs +++ b/Packages/com.unity.render-pipelines.core/Tests/Runtime/RuntimeProfilerTests.cs @@ -64,8 +64,8 @@ public IEnumerator RuntimeProfilerGivesNonZeroOutput() if (XRSettings.enabled) supportsGpuFrameTime = false; // XR #endif - // UGK-3010: zero on every UGK graphics API, not just Android/Metal. - if (UnityGraphicsKernelTestUtils.IsForcedUGK()) + // UGK-3010: under UGK only Vulkan and D3D12 report graph timing for FrameTime.GPU so far. + if (UnityGraphicsKernelTestUtils.IsForcedUGK() && SystemInfo.graphicsDeviceType != GraphicsDeviceType.Vulkan && SystemInfo.graphicsDeviceType != GraphicsDeviceType.Direct3D12) supportsGpuFrameTime = false; yield return Warmup(); diff --git a/Packages/com.unity.render-pipelines.high-definition/Documentation~/Render-Pipeline-Wizard.md b/Packages/com.unity.render-pipelines.high-definition/Documentation~/Render-Pipeline-Wizard.md index 1ac76e1b877..701dfd2b52b 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Documentation~/Render-Pipeline-Wizard.md +++ b/Packages/com.unity.render-pipelines.high-definition/Documentation~/Render-Pipeline-Wizard.md @@ -63,9 +63,9 @@ This section provides extra configuration options to help you set up your HDRP P | **Configuration Option** | **Suboption** | **Description** | |-------------------------------|----------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **Legacy VR System** | | Checks that Virtual Reality Supported is disabled. This is the deprecated system.
Select the Fix button to disable Virtual Reality Supported. | -| **XR Management Package** | | Checks that the XR Management Package is installed.
Select the Fix button to install it. | -| **XR Management Package** | **Oculus Plugin** | The wizard can't check this directly. This option gives information on the procedure to follow to check it.
To install the plugin manually, go to Edit > Project Settings > XR Plugin Manager | -| **XR Management Package** | **Single-Pass Instancing** | The wizard can't check this directly. This option gives information on the procedure to follow to check it.
Go to Edit > Project Settings > XR Plugin Manager > Oculus and make sure Stereo Rendering Mode uses Single-Pass Instancing | +| **XR Foundation Package** | | Checks that the XR Foundation Package is installed.
Select the Fix button to install it. | +| **XR Foundation Package** | **Oculus Plugin** | The wizard can't check this directly. This option gives information on the procedure to follow to check it.
To install the plugin manually, go to Edit > Project Settings > XR Plugin Manager | +| **XR Foundation Package** | **Single-Pass Instancing** | The wizard can't check this directly. This option gives information on the procedure to follow to check it.
Go to Edit > Project Settings > XR Plugin Manager > Oculus and make sure Stereo Rendering Mode uses Single-Pass Instancing | | **XR Legacy Helpers Package** | | Checks that the XR Legacy Helpers Package is installed. It's required to handle inputs with the TrackedPoseDriver component.
Select the Fix button to install it. | ### HDRP + DXR diff --git a/Packages/com.unity.render-pipelines.high-definition/Documentation~/System-Requirements.md b/Packages/com.unity.render-pipelines.high-definition/Documentation~/System-Requirements.md index e1c0735b5b1..14e34c3ced6 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Documentation~/System-Requirements.md +++ b/Packages/com.unity.render-pipelines.high-definition/Documentation~/System-Requirements.md @@ -29,7 +29,7 @@ HDRP is compatible with the following platforms: - Microsoft - Xbox One - Xbox Series X and Xbox Series S -- MacOS (minimum version 10.13) using Metal graphics +- macOS (minimum version 14) using Metal graphics - Linux and Windows platforms with Vulkan **Note**: HDRP only works on these platforms if the device you use supports Compute Shaders. HDRP doesn't support OpenGL or OpenGL ES devices. On Linux, Vulkan might not be installed by default. In that case you need to install it manually to run HDRP. diff --git a/Packages/com.unity.render-pipelines.high-definition/Documentation~/shared/lens-flare/reference-screen-space-lens-flare.md b/Packages/com.unity.render-pipelines.high-definition/Documentation~/shared/lens-flare/reference-screen-space-lens-flare.md index c9a62c95c4e..96783b8da15 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Documentation~/shared/lens-flare/reference-screen-space-lens-flare.md +++ b/Packages/com.unity.render-pipelines.high-definition/Documentation~/shared/lens-flare/reference-screen-space-lens-flare.md @@ -16,7 +16,7 @@ Use the **Flares** settings to control regular flares, reversed flares and warpe | ----------------------- | ----------------- | ------------------------------------------------------------ | | **Regular Multiplier** | | Set the strength of regular flares. If the value is 0, HDRP doesn't calculate or render regular flares. The default is 1. | | **Reversed Multiplier** | | Set the strength of reversed flares. If the value is 0, HDRP doesn't calculate or render reversed flares. The default is 1. | -| **Warped Multipler** | | Set the strength of warped flares. If the value is 0, HDRP doesn't calculate or render warped flares. The default is 1. | +| **Warped Multiplier** | | Set the strength of warped flares. If the value is 0, HDRP doesn't calculate or render warped flares. The default is 1. | | | **Scale** | Scale the width (**x**) and height (**y**) of warped flares. The defaults are 1. This property only appears if you open the **More** (⋮) menu and select **Show Additional Properties**. | | **Samples** | | Set the number of times HDRP repeats the regular, reversed and warped flares. The range is 1 through 3. The default is 1. Increasing **Samples** has a big impact on performance. | | | **Sample Dimmer** | Set the strength of the lens flares HDRP adds if you set **Samples** to 2 or 3. The higher the value, the less intense the flares. This property only appears if you open the **More** (⋮) menu and select **Show Additional Properties**. | diff --git a/Packages/com.unity.render-pipelines.high-definition/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.high-definition/Editor/Material/ShaderGraph/SurfaceSubTarget.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SurfaceSubTarget.cs index ef59d323b19..cd7b36b87ed 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SurfaceSubTarget.cs +++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SurfaceSubTarget.cs @@ -256,6 +256,10 @@ public override void GetFields(ref TargetFieldContext context) if (builtinData.depthOffset) context.AddField(HDStructFields.FragInputs.positionRWS); + // LOD crossfade dithering seeds from the per-pixel view vector + if (builtinData.supportLodCrossFade && !context.pass.IsRelatedToRaytracing()) + context.AddField(HDStructFields.FragInputs.positionRWS); + context.AddField(HDFields.CustomVelocity, systemData.customVelocity); context.AddField(HDFields.TessellationFactor, systemData.tessellation); diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Camera/HDCameraUI.Drawers.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Camera/HDCameraUI.Drawers.cs index fd9cd6f40f6..2ab572c1d1f 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Camera/HDCameraUI.Drawers.cs +++ b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Camera/HDCameraUI.Drawers.cs @@ -1,4 +1,4 @@ -#if ENABLE_VR && ENABLE_XR_MANAGEMENT +#if ENABLE_VR && (ENABLE_XR_MANAGEMENT || XR_FOUNDATION_7_0_0_OR_NEWER) using UnityEditor.XR; #endif @@ -34,7 +34,7 @@ public enum Expandable static readonly ExpandedState k_ExpandedState = new ExpandedState(Expandable.Projection, "HDRP"); -#if ENABLE_VR && ENABLE_XR_MANAGEMENT +#if ENABLE_VR && (ENABLE_XR_MANAGEMENT || XR_FOUNDATION_7_0_0_OR_NEWER) private static readonly CED.IDrawer OrthographicXRError = CED.Conditional( (serialized, owner) => serialized.xrRendering.boolValue && serialized.baseCameraSettings.orthographic.boolValue, (serialized, owner) => { @@ -50,7 +50,7 @@ public enum Expandable Expandable.Projection, k_ExpandedState, FoldoutOption.Indent, -#if ENABLE_VR && ENABLE_XR_MANAGEMENT +#if ENABLE_VR && (ENABLE_XR_MANAGEMENT || XR_FOUNDATION_7_0_0_OR_NEWER) OrthographicXRError, #endif CED.Group( diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Camera/HDCameraUI.Output.Drawers.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Camera/HDCameraUI.Output.Drawers.cs index 1390bf28474..6912064b58c 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Camera/HDCameraUI.Output.Drawers.cs +++ b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Camera/HDCameraUI.Output.Drawers.cs @@ -21,7 +21,7 @@ static Output() k_ExpandedState, FoldoutOption.Indent, CED.Group( -#if ENABLE_VR && ENABLE_XR_MANAGEMENT +#if ENABLE_VR && (ENABLE_XR_MANAGEMENT || XR_FOUNDATION_7_0_0_OR_NEWER) Drawer_SectionXRRendering, #endif #if ENABLE_MULTIPLE_DISPLAYS @@ -51,7 +51,7 @@ static void Drawer_Output_MSAA_Warning(SerializedHDCamera p, Editor owner) } } -#if ENABLE_VR && ENABLE_XR_MANAGEMENT +#if ENABLE_VR && (ENABLE_XR_MANAGEMENT || XR_FOUNDATION_7_0_0_OR_NEWER) static void Drawer_SectionXRRendering(SerializedHDCamera p, Editor owner) { EditorGUILayout.PropertyField(p.xrRendering, Styles.xrRenderingContent); diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Camera/HDCameraUI.Output.Skin.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Camera/HDCameraUI.Output.Skin.cs index d8fc0f1c021..4abfa10eb50 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Camera/HDCameraUI.Output.Skin.cs +++ b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Camera/HDCameraUI.Output.Skin.cs @@ -12,7 +12,7 @@ class Styles public static readonly GUIContent targetDisplay = L10n.TextContent("Target Display", null, null, null); #endif -#if ENABLE_VR && ENABLE_XR_MANAGEMENT +#if ENABLE_VR && (ENABLE_XR_MANAGEMENT || XR_FOUNDATION_7_0_0_OR_NEWER) public static readonly GUIContent xrRenderingContent = L10n.TextContent("XR Rendering", null, null, null); #endif diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Tools/Converter/BuiltInToHDRPReadonlyMaterialConverter.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/Tools/Converter/BuiltInToHDRPReadonlyMaterialConverter.cs index 1aee1bc2c3b..91cd316230a 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Editor/Tools/Converter/BuiltInToHDRPReadonlyMaterialConverter.cs +++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Tools/Converter/BuiltInToHDRPReadonlyMaterialConverter.cs @@ -18,6 +18,13 @@ internal class BuiltInToURP3DReadonlyMaterialConverter : ReadonlyMaterialConvert public override bool isEnabled => GraphicsSettings.currentRenderPipeline is HDRenderPipelineAsset; public override string isDisabledMessage => "Converter requires HDRP. Convert your project to HDRP to use this converter."; + public override void BeforeConvert() + { + // The replacement materials live in the global settings, which may not exist yet or be out of date + HDRenderPipelineGlobalSettings.Ensure(); + base.BeforeConvert(); + } + protected override Dictionary> materialMappings { get diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Tools/LookDev/Stage.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/Tools/LookDev/Stage.cs index 42ac3329738..f9fdd706361 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Editor/Tools/LookDev/Stage.cs +++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Tools/LookDev/Stage.cs @@ -64,8 +64,8 @@ public Stage(string sceneName) m_Camera.enabled = false; m_Camera.clearFlags = CameraClearFlags.Depth; m_Camera.cullingMask = 1 << k_PreviewCullingLayerIndex; - m_Camera.renderingPath = RenderingPath.DeferredShading; #pragma warning disable CS0618 + m_Camera.renderingPath = RenderingPath.DeferredShading; m_Camera.useOcclusionCulling = false; #pragma warning restore CS0618 m_Camera.scene = m_PreviewScene; diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Unity.RenderPipelines.HighDefinition.Editor.asmdef b/Packages/com.unity.render-pipelines.high-definition/Editor/Unity.RenderPipelines.HighDefinition.Editor.asmdef index 30144afa766..97c928d8d68 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Editor/Unity.RenderPipelines.HighDefinition.Editor.asmdef +++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Unity.RenderPipelines.HighDefinition.Editor.asmdef @@ -41,6 +41,11 @@ "expression": "4.0.1", "define": "ENABLE_XR_MANAGEMENT" }, + { + "name": "com.unity.xr.foundation", + "expression": "7.0.0", + "define": "XR_FOUNDATION_7_0_0_OR_NEWER" + }, { "name": "com.unity.modules.nvidia", "expression": "1.0.0", diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Wizard/HDWizard.Configuration.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/Wizard/HDWizard.Configuration.cs index f57a2038eec..5a23296ee83 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Editor/Wizard/HDWizard.Configuration.cs +++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Wizard/HDWizard.Configuration.cs @@ -419,6 +419,7 @@ void FixLightmap(bool fromAsyncUnused) OnUpdateLightmapEncoding(BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget)); } +#pragma warning disable CS0618 // Type or member is obsolete bool IsShadowCorrect() => QualitySettings.shadows == ShadowQuality.All; @@ -426,6 +427,7 @@ void FixShadow(bool fromAsyncUnised) { QualitySettings.ForEach(() => QualitySettings.shadows = ShadowQuality.All); } +#pragma warning restore CS0618 bool IsShadowmaskCorrect() => QualitySettings.shadowmaskMode == ShadowmaskMode.DistanceShadowmask; @@ -611,16 +613,20 @@ void FixMigratableAssets(bool fromAsyncUnused) void UpdateVRXRManagementInstalledCheck() { m_vrXRManagementInstalledCheck = Result.Pending; + bool foundationInstalled = false; + m_UsedPackageRetriever.ProcessAsync( + k_XRFoundationPackageName, + (installed, info) => foundationInstalled = installed); m_UsedPackageRetriever.ProcessAsync( k_XRanagementPackageName, - (installed, info) => m_vrXRManagementInstalledCheck = installed ? Result.OK : Result.Failed); + (installed, info) => m_vrXRManagementInstalledCheck = (foundationInstalled || installed) ? Result.OK : Result.Failed); } void FixVRXRManagementPackageInstalled(bool fromAsync) { if (fromAsync) RestartFixAllAfterDomainReload(InclusiveMode.VR); - m_PackageInstaller.ProcessAsync(k_XRanagementPackageName, null); + m_PackageInstaller.ProcessAsync(k_XRFoundationPackageName, null); } Result m_vrLegacyHelpersInstalledCheck = Result.Pending; @@ -871,6 +877,7 @@ void FixDXRActivation(bool fromAsyncUnused) const string k_HdrpPackageName = "com.unity.render-pipelines.high-definition"; const string k_HdrpConfigPackageName = "com.unity.render-pipelines.high-definition-config"; const string k_XRanagementPackageName = "com.unity.xr.management"; + const string k_XRFoundationPackageName = "com.unity.xr.foundation"; const string k_LegacyInputHelpersPackageName = "com.unity.xr.legacyinputhelpers"; void IsLocalConfigurationPackageEmbeddedAsync(Action callback) diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Wizard/HDWizard.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/Wizard/HDWizard.cs index 2cda1a7e606..34791be0cd2 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Editor/Wizard/HDWizard.cs +++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Wizard/HDWizard.cs @@ -110,11 +110,11 @@ public ConfigStyle(string label, string error, string button = null, MessageType label: L10n.Tr("Legacy VR System", null), error: L10n.Tr("Legacy VR System need to be disabled in Player Settings!", null)); public static readonly ConfigStyle vrXRManagementPackage = new ConfigStyle( - label: L10n.Tr("XR Management Package", null), - error: L10n.Tr("XR Management Package is required to run in VR!", null)); + label: L10n.Tr("XR Foundation Package", null), + error: L10n.Tr("XR Foundation Package is required to run in VR!", null)); public static readonly ConfigStyle vrXRManagementPackageInstalled = new ConfigStyle( label: L10n.Tr("Package Installed", null), - error: L10n.Tr("Last version of XR Management Package must be added in your project!", null)); + error: L10n.Tr("Last version of XR Foundation Package must be added in your project!", null)); public static readonly ConfigStyle vrOculusPlugin = new ConfigStyle( label: L10n.Tr("Oculus Plugin", null), error: L10n.Tr("Oculus Plugin must installed manually.\nGo in Edit > Project Settings > XR Plugin Manager and add Oculus XR Plugin.\n(This can't be verified by the Wizard)", null), diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 78a36bad60f..82f670d37a9 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -539,8 +539,8 @@ enum ClusterDepthSource : int // Compute kernel indices below are pipeline-lifetime: populated by InitializeLightLoop from the pipeline constructor and reused across domain reload. [NoAutoStaticsCleanup] static int s_GenListPerTileKernel; - [NoAutoStaticsCleanup] static readonly int[,] s_ClusterKernels = new int[(int)ClusterPrepassSource.Count, (int)ClusterDepthSource.Count]; - [NoAutoStaticsCleanup] static readonly int[,] s_ClusterObliqueKernels = new int[(int)ClusterPrepassSource.Count, (int)ClusterDepthSource.Count]; + static readonly int[,] s_ClusterKernels = new int[(int)ClusterPrepassSource.Count, (int)ClusterDepthSource.Count]; + static readonly int[,] s_ClusterObliqueKernels = new int[(int)ClusterPrepassSource.Count, (int)ClusterDepthSource.Count]; [NoAutoStaticsCleanup] static int s_ClearVoxelAtomicKernel; [NoAutoStaticsCleanup] static int s_ClearDispatchIndirectKernel; [NoAutoStaticsCleanup] static int s_BuildIndirectKernel; @@ -549,7 +549,7 @@ enum ClusterDepthSource : int [NoAutoStaticsCleanup] static int s_shadeOpaqueDirectFptlKernel; [NoAutoStaticsCleanup] static int s_shadeOpaqueDirectFptlDebugDisplayKernel; - [NoAutoStaticsCleanup] static readonly int[] s_shadeOpaqueIndirectFptlKernels = new int[LightDefinitions.s_NumFeatureVariants]; + static readonly int[] s_shadeOpaqueIndirectFptlKernels = new int[LightDefinitions.s_NumFeatureVariants]; [NoAutoStaticsCleanup] static int s_deferredContactShadowKernel; diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/HDRenderPipeline.ScreenSpaceGlobalIllumination.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/HDRenderPipeline.ScreenSpaceGlobalIllumination.cs index 3dbd621072b..7c20c61db94 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/HDRenderPipeline.ScreenSpaceGlobalIllumination.cs +++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/HDRenderPipeline.ScreenSpaceGlobalIllumination.cs @@ -156,6 +156,7 @@ class TraceSSGIPassData // History buffers public TextureHandle colorPyramid; public TextureHandle historyDepth; + public Vector4 historySizeAndScale; // Intermediate buffers public TextureHandle hitPointBuffer; @@ -237,6 +238,7 @@ TextureHandle TraceSSGI(RenderGraph renderGraph, HDCamera hdCamera, GlobalIllumi else passData.historyDepth = renderGraph.defaultResources.blackTextureXR; builder.UseTexture(passData.historyDepth, AccessFlags.Read); + passData.historySizeAndScale = historyDepth != null ? EvaluateRayTracingHistorySizeAndScale(hdCamera, historyDepth) : Vector4.one; // Temporary textures passData.hitPointBuffer = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) @@ -298,6 +300,7 @@ TextureHandle TraceSSGI(RenderGraph renderGraph, HDCamera hdCamera, GlobalIllumi natCmd.SetComputeTextureParam(data.ssGICS, data.projectKernel, HDShaderIDs._IndirectDiffuseHitPointTexture, data.hitPointBuffer); natCmd.SetComputeTextureParam(data.ssGICS, data.projectKernel, HDShaderIDs._ColorPyramidTexture, data.colorPyramid); natCmd.SetComputeTextureParam(data.ssGICS, data.projectKernel, HDShaderIDs._HistoryDepthTexture, data.historyDepth); + natCmd.SetComputeVectorParam(data.ssGICS, HDShaderIDs._HistorySizeAndScale, data.historySizeAndScale); natCmd.SetComputeBufferParam(data.ssGICS, data.projectKernel, HDShaderIDs._DepthPyramidMipLevelOffsets, data.offsetBuffer); natCmd.SetComputeBufferParam(data.ssGICS, data.projectKernel, HDShaderIDs.g_vLightListTile, data.lightList); @@ -318,7 +321,6 @@ class UpscaleSSGIPassData public int texWidth; public int texHeight; public int viewCount; - public Vector4 halfScreenSize; public float lowResPercentage; public ShaderVariablesBilateralUpsample shaderVariablesBilateralUpsampleCB; @@ -341,7 +343,9 @@ TextureHandle UpscaleSSGI(RenderGraph renderGraph, HDCamera hdCamera, GlobalIllu passData.viewCount = hdCamera.viewCount; float lowResPercentage = GetSSGILowResPercentage(hdCamera).x; - passData.shaderVariablesBilateralUpsampleCB._HalfScreenSize = new Vector4(passData.texWidth / lowResPercentage, passData.texHeight / lowResPercentage, 1.0f / (passData.texWidth * lowResPercentage), 1.0f / (passData.texHeight * lowResPercentage)); + int lowResWidth = (int)Mathf.Floor(passData.texWidth * lowResPercentage); + int lowResHeight = (int)Mathf.Floor(passData.texHeight * lowResPercentage); + passData.shaderVariablesBilateralUpsampleCB._HalfScreenSize = new Vector4(lowResWidth, lowResHeight, 1.0f / lowResWidth, 1.0f / lowResHeight); passData.lowResPercentage = lowResPercentage; unsafe { @@ -352,11 +356,6 @@ TextureHandle UpscaleSSGI(RenderGraph renderGraph, HDCamera hdCamera, GlobalIllu passData.shaderVariablesBilateralUpsampleCB._TapOffsets[i] = BilateralUpsample.tapOffsets_2x2[i]; } - // Setup lowres bounds. - int lowResWidth = (int)Mathf.Floor(passData.texWidth * passData.lowResPercentage); - int lowResHeight = (int)Mathf.Floor(passData.texHeight * passData.lowResPercentage); - passData.halfScreenSize.Set(lowResWidth, lowResHeight, 1.0f / lowResWidth, 1.0f / lowResHeight); - // Grab the right kernel passData.bilateralUpsampleCS = runtimeShaders.bilateralUpsampleCS; passData.upscaleKernel = passData.lowResPercentage == 0.5f ? m_BilateralUpSampleColorKernelHalf : m_BilateralUpSampleColorKernel; @@ -385,7 +384,6 @@ TextureHandle UpscaleSSGI(RenderGraph renderGraph, HDCamera hdCamera, GlobalIllu // Inject all the input buffers natCmd.SetComputeTextureParam(data.bilateralUpsampleCS, data.upscaleKernel, HDShaderIDs._DepthTexture, data.depthTexture); natCmd.SetComputeTextureParam(data.bilateralUpsampleCS, data.upscaleKernel, HDShaderIDs._LowResolutionTexture, data.inputBuffer); - natCmd.SetComputeVectorParam(data.bilateralUpsampleCS, HDShaderIDs._HalfScreenSize, data.halfScreenSize); // Inject the output textures natCmd.SetComputeTextureParam(data.bilateralUpsampleCS, data.upscaleKernel, HDShaderIDs._OutputUpscaledTexture, data.outputBuffer); diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceGlobalIllumination.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceGlobalIllumination.compute index 516f3d5fe4e..3f760fb7605 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceGlobalIllumination.compute +++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceGlobalIllumination.compute @@ -204,6 +204,8 @@ void TraceReflectionProbes(PositionInputs posInput, float3 normalWS, float3 rayD TEXTURE2D_X(_IndirectDiffuseHitPointTexture); // Depth buffer of the previous frame (full resolution) TEXTURE2D_X(_HistoryDepthTexture); +// xy: previous frame viewport size, zw: previous viewport size / history buffer size +float4 _HistorySizeAndScale; RW_TEXTURE2D_X(float3, _IndirectDiffuseTextureRW); // The maximal difference in depth that is considered acceptable to read from the color pyramid @@ -270,9 +272,14 @@ void REPROJECT_GLOBAL_ILLUMINATION(uint3 dispatchThreadId : SV_DispatchThreadID, || (prevFrameUV.y > _ColorPyramidUvScaleAndLimitPrevFrame.w)) invalid = true; + // The depth history was written at the previous frame's viewport size, which differs from the current one under dynamic resolution + float2 historyTapCoord = prevFrameNDC * _HistorySizeAndScale.xy; + if (any(historyTapCoord < 0) || any(historyTapCoord >= _HistorySizeAndScale.xy)) + invalid = true; + // Grab the depth of the hit point and reject the history buffer if the depth is too different // TODO: Find a better metric - float hitPointHistoryDepth = LOAD_TEXTURE2D_X(_HistoryDepthTexture, prevFrameNDC * _ScreenSize.xy).x; + float hitPointHistoryDepth = LOAD_TEXTURE2D_X(_HistoryDepthTexture, min(max(historyTapCoord, 0), _HistorySizeAndScale.xy - 1)).x; if (abs(hitPointHistoryDepth - hitPointDepth) > DEPTH_DIFFERENCE_THRESHOLD) invalid = true; diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Canvas/HDCanvasPass.hlsl b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Canvas/HDCanvasPass.hlsl index 273f87703ed..9d7693099f2 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Canvas/HDCanvasPass.hlsl +++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Canvas/HDCanvasPass.hlsl @@ -88,9 +88,9 @@ Varyings BuildVaryings(Attributes input) float2 pixelSize = output.positionCS.w; pixelSize /= float2(1, 1) * abs(mul((float2x2)UNITY_MATRIX_P, _ScreenParams.xy)); - float4 clampedRect = clamp(_ClipRect, -2e10, 2e10); - float2 maskUV = (input.positionOS.xy - clampedRect.xy) / (clampedRect.zw - clampedRect.xy); - output.texCoord1 = float4(input.positionOS.xy * 2 - clampedRect.xy - clampedRect.zw, 0.25 / (0.25 * float2(_UIMaskSoftnessX, _UIMaskSoftnessY) + abs(pixelSize.xy))); + // Canvas position and pixel size, both linear in the vertex so they interpolate exactly under perspective. + // The fragment turns them into each edge's fade, so tilted masks keep their edges. + output.texCoord1 = float4(input.positionOS.xy, abs(pixelSize.xy)); #else output.texCoord1 = input.uv1; #endif @@ -190,12 +190,13 @@ out float4 outColor : SV_Target0 #ifdef UNITY_UI_CLIP_RECT //mask = Uv2 - float2 softness = float2(_UIMaskSoftnessX, _UIMaskSoftnessY); - float2 halfPixelBias = 0.5 - 0.5 * softness * unpacked.texCoord1.zw; - half2 m = saturate((_ClipRect.zw - _ClipRect.xy - abs(unpacked.texCoord1.xy)) * unpacked.texCoord1.zw + halfPixelBias); - half2 hardThreshold = 0.5 + 1e-3 * step(0, unpacked.texCoord1.xy); - m = lerp(m, step(hardThreshold, m), step(softness, 0)); - outColor.a *= m.x * m.y; + // Each edge fades over its own distance and softness: left, bottom, right, top. + float4 clampedRect = clamp(_ClipRect, -2e10, 2e10); + float4 edgeDistance = float4(unpacked.texCoord1.xy - clampedRect.xy, clampedRect.zw - unpacked.texCoord1.xy); + half4 soft = saturate((edgeDistance + unpacked.texCoord1.zwzw) / (0.5 * _UIMaskSoftness + 2 * unpacked.texCoord1.zwzw)); + half4 hard = half4(edgeDistance.xy >= 0, edgeDistance.zw > 0); + half4 m = _UIMaskSoftness > 0 ? soft : hard; + outColor.a *= min(m.x, m.z) * min(m.y, m.w); #endif #ifdef _ALPHATEST_ON diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/DiffusionProfile/DiffusionProfileSettings.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/DiffusionProfile/DiffusionProfileSettings.cs index 470aa7ec8b7..506149400c3 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/DiffusionProfile/DiffusionProfileSettings.cs +++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/DiffusionProfile/DiffusionProfileSettings.cs @@ -384,7 +384,7 @@ internal void Reset() if (profile != null && profile.hash == 0) { profile.ResetToDefault(); - profile.hash = DiffusionProfileHashTable.GenerateUniqueHash(this); + DiffusionProfileHashTable.UpdateDiffusionProfileHashNow(this); } } diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/SixWayLit/SixWaySmokeLit.hlsl b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/SixWayLit/SixWaySmokeLit.hlsl index e9df3b7111b..0d5b838ea34 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/SixWayLit/SixWaySmokeLit.hlsl +++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/SixWayLit/SixWaySmokeLit.hlsl @@ -306,7 +306,6 @@ CBSDF EvaluateBSDF(float3 V, float3 L, PreLightData preLightData, BSDFData bsdfD #if defined(_RECEIVE_SHADOWS_OFF) #define LIGHT_EVALUATION_NO_SHADOWS #endif -#define LIGHT_EVALUATION_NO_CLOUDS_SHADOWS #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightEvaluation.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/MaterialEvaluation.hlsl" diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Debug.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Debug.cs index d1b54f783e7..4b5c8787277 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Debug.cs +++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Debug.cs @@ -1576,6 +1576,12 @@ class DebugViewMaterialData public GBufferOutput gbuffer; public TextureHandle depthBuffer; + public TextureHandle waterDepthStencil; + public BufferHandle waterSurfaceProfiles; + public BufferHandle cameraHeightBuffer; + public BufferHandle waterLine; + public TextureHandle waterGBuffer3; + public Texture clearColorTexture; public RenderTexture clearDepthTexture; public bool clearDepth; @@ -1677,6 +1683,18 @@ TextureHandle RenderDebugViewMaterial(RenderGraph renderGraph, CullingResults cu } passData.dbuffer = ReadDBuffer(dbuffer, builder); + // Water absorption buffers + passData.waterDepthStencil = prepassOutput.depthBufferPreRefraction; + builder.UseTexture(passData.waterDepthStencil, AccessFlags.Read); + passData.waterSurfaceProfiles = prepassOutput.waterSurfaceProfiles; + builder.UseBuffer(passData.waterSurfaceProfiles, AccessFlags.Read); + passData.cameraHeightBuffer = prepassOutput.waterGBuffer.cameraHeight; + builder.UseBuffer(passData.cameraHeightBuffer, AccessFlags.Read); + passData.waterLine = prepassOutput.waterLine; + builder.UseBuffer(passData.waterLine, AccessFlags.Read); + passData.waterGBuffer3 = prepassOutput.waterGBuffer.waterGBuffer3; + builder.UseTexture(passData.waterGBuffer3, AccessFlags.Read); + passData.clearColorTexture = Compositor.CompositionManager.GetClearTextureForStackedCamera(hdCamera); // returns null if is not a stacked camera passData.clearDepthTexture = Compositor.CompositionManager.GetClearDepthForStackedCamera(hdCamera); // returns null if is not a stacked camera passData.clearDepth = hdCamera.clearDepth; @@ -1695,6 +1713,14 @@ TextureHandle RenderDebugViewMaterial(RenderGraph renderGraph, CullingResults cu BindDefaultTexturesLightingBuffers(ctx.defaultResources, natCmd); + // Water absorption buffers, read by transparent materials with fog or refractive sorting + natCmd.SetGlobalTexture(HDShaderIDs._StencilTexture, data.waterDepthStencil, RenderTextureSubElement.Stencil); + natCmd.SetGlobalTexture(HDShaderIDs._RefractiveDepthBuffer, data.waterDepthStencil, RenderTextureSubElement.Depth); + natCmd.SetGlobalBuffer(HDShaderIDs._WaterCameraHeightBuffer, data.cameraHeightBuffer); + natCmd.SetGlobalBuffer(HDShaderIDs._WaterSurfaceProfiles, data.waterSurfaceProfiles); + natCmd.SetGlobalBuffer(HDShaderIDs._WaterLineBuffer, data.waterLine); + natCmd.SetGlobalTexture(HDShaderIDs._WaterGBufferTexture3, data.waterGBuffer3); + bool bUseClustered = data.perVoxelLightLists.IsValid(); CoreUtils.SetKeyword(natCmd, "USE_FPTL_LIGHTLIST", !bUseClustered); CoreUtils.SetKeyword(natCmd, "USE_CLUSTERED_LIGHTLIST", bUseClustered); 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 d24fb91f7d8..949b12e7bc8 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 @@ -387,7 +387,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) { @@ -778,7 +778,7 @@ class CopyXRDepthPassData public int passIndex; } - void CopyDepth(RenderGraph renderGraph, HDCamera hdCamera, in TextureHandle depthBuffer, in TextureHandle output, bool copyForXR) + void CopyDepth(RenderGraph renderGraph, in TextureHandle depthBuffer, in TextureHandle output, bool copyForXR) { string name = copyForXR ? "Copy XR Depth" : "Copy Depth"; var profileID = copyForXR ? HDProfileId.XRDepthCopy : HDProfileId.DuplicateDepthBuffer; @@ -789,8 +789,7 @@ void CopyDepth(RenderGraph renderGraph, HDCamera hdCamera, in TextureHandle dept builder.UseTexture(passData.depthBuffer, AccessFlags.Read); passData.output = output; builder.SetRenderAttachmentDepth(output, AccessFlags.Write); - passData.blitScaleBias = copyForXR ? new Vector2(hdCamera.actualWidth / hdCamera.finalViewport.width, hdCamera.actualHeight / hdCamera.finalViewport.height) - : RTHandles.rtHandleProperties.rtHandleScale; + passData.blitScaleBias = RTHandles.rtHandleProperties.rtHandleScale; passData.flipY = copyForXR; passData.passIndex = renderGraph.GetTextureDesc(depthBuffer).msaaSamples != MSAASamples.None ? 1 : 0; Debug.Assert(!(copyForXR && passData.passIndex != 0), "MSAA depth copies do not support XR scaling and Y-flipping."); @@ -1780,7 +1779,7 @@ TransparentPrepassOutput RenderTransparentPrepass(RenderGraph renderGraph, Culli renderQueueRange: GetTransparentRenderQueueRange(hdCamera, false))); // Copy depth buffer for refraction - CopyDepth(renderGraph, hdCamera, prepassOutput.depthBuffer, output.depthBufferPreRefraction, false); + CopyDepth(renderGraph, prepassOutput.depthBuffer, output.depthBufferPreRefraction, false); if (hasWater) { diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index 7b29f6c21a4..2bb29f2893d 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -1677,6 +1677,23 @@ internal void Reset() } } + // UUM-160872: Expose the stack the camera rendered with to endCameraRendering callbacks, as URP does + static void EndCameraRenderingWithVolumeStack(ScriptableRenderContext renderContext, Camera camera, HDCamera hdCamera) + { + var mainVolumeStack = VolumeManager.instance.stack; + if (hdCamera != null) + VolumeManager.instance.stack = hdCamera.volumeStack; + + try + { + EndCameraRendering(renderContext, camera); + } + finally + { + VolumeManager.instance.stack = mainVolumeStack; + } + } + bool PrepareAndCullCamera( Camera camera, XRPass xrPass, @@ -1771,7 +1788,7 @@ bool PrepareAndCullCamera( renderContext.Submit(); m_CullingResultsPool.Release(cullingResults); if (xrPass.isLastCameraPass) - EndCameraRendering(renderContext, camera); + EndCameraRenderingWithVolumeStack(renderContext, camera, hdCamera); return false; } @@ -2642,7 +2659,7 @@ protected override void Render(ScriptableRenderContext renderContext, List(); diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/TemporalFilter.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/TemporalFilter.compute index 43b53428452..e5dfe7fd5f4 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/TemporalFilter.compute +++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/TemporalFilter.compute @@ -192,7 +192,11 @@ void TEMPORAL_ACCUMULATION(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 g // Compute the pixel coordinate for the history tapping float2 historyUVUnscaled = ((currentCoord + 0.5)/(_ScreenSize.xy * _DenoiserResolutionMultiplierVals.xx)) - velocity; - float2 historyUV = historyUVUnscaled * _DenoiserResolutionMultiplierVals.zz *_HistorySizeAndScale.zw; + // Under dynamic resolution only the previous viewport is valid; clamp half a texel inside it so bilinear taps + // never read stale texels + float2 historyScale = _DenoiserResolutionMultiplierVals.zz * _HistorySizeAndScale.zw; + float2 historyTexelSize = rcp(max(_HistorySizeAndScale.xy * _DenoiserResolutionMultiplierVals.zz, 1.0)); + float2 historyUV = ClampAndScaleUV(historyUVUnscaled, historyTexelSize, 0.5f, historyScale); // Fetch the current value, history value and current sample count #if HISTORY_IS_ARRAY diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/SceneViewDrawMode.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/SceneViewDrawMode.cs index a2da338a960..f13296ee294 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/SceneViewDrawMode.cs +++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/SceneViewDrawMode.cs @@ -9,6 +9,7 @@ class SceneViewDrawMode { static HashSet sceneViewHaveValidateFunction = new HashSet(); +#pragma warning disable CS0618 // Type or member is obsolete static private bool RejectDrawMode(SceneView.CameraMode cameraMode) { return cameraMode.drawMode != DrawCameraMode.ShadowCascades && @@ -25,6 +26,7 @@ static private bool RejectDrawMode(SceneView.CameraMode cameraMode) cameraMode.drawMode != DrawCameraMode.SpriteMask && cameraMode.drawMode != DrawCameraMode.TextureStreaming; } +#pragma warning restore CS0618 static void UpdateSceneViewStates() { diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/HDUtils.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/HDUtils.cs index 8c6063f48c3..2d864420ab5 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/HDUtils.cs +++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/HDUtils.cs @@ -952,14 +952,14 @@ internal static bool IsOperatingSystemSupported(string os) // Metal support depends on OS version: // macOS 10.11.x doesn't have tessellation / earlydepthstencil support, early driver versions were buggy in general // macOS 10.12.x should usually work with AMD, but issues with Intel/Nvidia GPUs. Regardless of the GPU, there are issues with MTLCompilerService crashing with some shaders - // macOS 10.13.x should work, but active development tests against current OS + // macOS 14 is required for atomics on texture_buffer (MSL 3.1), which HDRP uses for typed buffers // // Has worked experimentally with iOS in the past, but it's not currently supported // if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Metal) { - if (os.StartsWith("Mac") && !IsMacOSVersionAtLeast(os, 10, 13, 0)) + if (os.StartsWith("Mac") && !IsMacOSVersionAtLeast(os, 14, 0, 0)) return false; } diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Utilities/DiffusionProfileHashTable.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/Utilities/DiffusionProfileHashTable.cs index 7803fbffde8..21f35b33d93 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Utilities/DiffusionProfileHashTable.cs +++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Utilities/DiffusionProfileHashTable.cs @@ -12,8 +12,19 @@ namespace UnityEditor.Rendering.HighDefinition [InitializeOnLoad] class DiffusionProfileHashTable { + // In rare cases, the final profile hash can differ from its GUID hash, because collisions are only checked against loaded profiles. + // 1. Load order. Hash collision resolution depends on load order. The later (colliding) profile is bumped to the next free hash and a warning is logged. + // 2. Collision cascade. A bumped hash can collide with an existing one that is still unloaded, which is then bumped later on load. + // 3. Domain reload. The table is cleared and profiles are checked again in arbitrary order, which can trigger a cascade (2.) + [System.NonSerialized] static Dictionary diffusionProfileHashes = new Dictionary(); + [System.NonSerialized] + static Dictionary diffusionProfileOwners = new Dictionary(); + + // Max offset from the GUID hash for a stored hash to be kept. + // A profile moved further is regenerated on every load. + internal const uint k_MaxHashOffset = 16; // Stable hash to avoid having different result after upgrading mono // Source: https://github.com/Unity-Technologies/mono/blob/unity-2021.2-mbe-pre-upgrade/mcs/class/referencesource/mscorlib/system/string.cs#L824 @@ -40,7 +51,7 @@ unsafe static int MonoStringHash(string guid) } } - static uint GetDiffusionProfileHash(DiffusionProfileSettings asset) + internal static uint GetDiffusionProfileHash(DiffusionProfileSettings asset) { string assetPath = AssetDatabase.GetAssetPath(asset); @@ -57,46 +68,107 @@ static uint GetDiffusionProfileHash(DiffusionProfileSettings asset) return (exponent << 23) | mantissa; } - static internal uint GenerateUniqueHash(DiffusionProfileSettings asset) + public static void UpdateDiffusionProfileHashNow(DiffusionProfileSettings profile) { - uint hash = GetDiffusionProfileHash(asset); + uint hash = profile.profile.hash; + uint guidHash = GetDiffusionProfileHash(profile); + EntityId entityId = profile.GetEntityId(); - while (diffusionProfileHashes.ContainsValue(hash)) + // Hash 0 means the profile was just created. + // Otherwise, the hash is regenerated from the GUID, for example when the asset was duplicated. + bool isWithinMaxOffset = IsWithinMaxHashOffset(hash, guidHash); + if (!isWithinMaxOffset || IsHashTaken(hash, entityId)) { - Debug.LogWarning("Collision found in asset: " + asset + ", generating a new hash, previous hash: " + hash); - hash++; + // Within the max offset, the stored hash is only regenerated when another profile took it + bool storedHashTaken = isWithinMaxOffset; + uint newHash = GenerateUniqueHash(profile, guidHash, entityId, storedHashTaken); + if (newHash != hash) + { + profile.profile.hash = newHash; + EditorUtility.SetDirty(profile); + + // SetDirty is discarded when called from OnEnable during asset load. + // Only a hash changed by a collision needs to be saved, the GUID hash is regenerated on every load. + if (newHash != guidHash || storedHashTaken) + { + EditorApplication.delayCall += () => + { + if (profile != null) + EditorUtility.SetDirty(profile); + }; + } + } } - return hash; + Register(profile, entityId); } - public static void UpdateDiffusionProfileHashNow(DiffusionProfileSettings profile) + static bool IsWithinMaxHashOffset(uint storedHash, uint guidHash) { - uint hash = profile.profile.hash; + // Unsigned subtraction wraps a stored hash below guidHash, including 0, to a large value + return storedHash - guidHash < k_MaxHashOffset; + } - // If the hash is 0, then we need to generate a new one (it means that the profile was just created) - if (hash == 0) + static bool IsHashTaken(uint hash, EntityId entityId) + { + if (!diffusionProfileOwners.TryGetValue(hash, out EntityId owner) || owner == entityId) + return false; + + // The owner was deleted + if (string.IsNullOrEmpty(AssetDatabase.GetAssetPath(owner))) + { + diffusionProfileOwners.Remove(hash); + diffusionProfileHashes.Remove(owner); + return false; + } + + return true; + } + + static uint GenerateUniqueHash(DiffusionProfileSettings asset, uint guidHash, EntityId entityId, bool storedHashTaken) + { + uint hash = guidHash; + while (IsHashTaken(hash, entityId)) { - profile.profile.hash = GenerateUniqueHash(profile); - EditorUtility.SetDirty(profile); - // We can't move the asset + hash++; } - // If the asset is not in the list, we regenerate it's hash using the GUID (which leads to the same result every time) -#pragma warning disable 618 // Todo(@daniel.andersen): Potentially use GetRawData or sometin' - else if (!diffusionProfileHashes.ContainsKey(profile.GetEntityId())) -#pragma warning restore 618 + + if (hash != guidHash || storedHashTaken) { - uint newHash = GenerateUniqueHash(profile); - if (newHash != profile.profile.hash) - { - profile.profile.hash = newHash; - EditorUtility.SetDirty(profile); - } + uint storedHash = asset.profile.hash; + uint takenHash = storedHashTaken ? storedHash : guidHash; + string assetPath = AssetDatabase.GetAssetPath(asset); + string ownerPath = AssetDatabase.GetAssetPath(diffusionProfileOwners[takenHash]); + string message = $"Collision found in asset: {assetPath}, hash {takenHash} is already used by {ownerPath}, using hash {hash} instead."; + if (!IsWithinMaxHashOffset(hash, guidHash)) + message += $" {k_MaxHashOffset} or more diffusion profiles have similar hashes, so the hash of {assetPath} is regenerated on every load and can change. " + + $"Duplicate {assetPath} and assign the copy to the materials that use it."; + else if (storedHash != 0 && storedHash != hash) + message += $" Select {assetPath} again on the materials that use it."; + Debug.LogWarning(message, asset); } - else // otherwise, no issue, we don't change the hash and we keep it to check for collisions -#pragma warning disable 618 // Todo(@daniel.andersen): Potentially use GetRawData or sometin' - diffusionProfileHashes.Add(profile.GetEntityId(), profile.profile.hash); -#pragma warning restore 618 + + return hash; + } + + static void Register(DiffusionProfileSettings profile, EntityId entityId) + { + uint hash = profile.profile.hash; + if (hash == 0) + return; + + if (diffusionProfileHashes.TryGetValue(entityId, out uint previousHash) && previousHash != hash && !IsHashTaken(previousHash, entityId)) + diffusionProfileOwners.Remove(previousHash); + + diffusionProfileHashes[entityId] = hash; + diffusionProfileOwners[hash] = entityId; + } + + internal static void Unregister(DiffusionProfileSettings profile) + { + EntityId entityId = profile.GetEntityId(); + if (diffusionProfileHashes.Remove(entityId, out uint hash) && !IsHashTaken(hash, entityId)) + diffusionProfileOwners.Remove(hash); } } } diff --git a/Packages/com.unity.shadergraph/Editor/UIResources.meta b/Packages/com.unity.render-pipelines.universal/DocCodeSamples.Tests.meta similarity index 77% rename from Packages/com.unity.shadergraph/Editor/UIResources.meta rename to Packages/com.unity.render-pipelines.universal/DocCodeSamples.Tests.meta index d3d5f4d3563..8cb34eb71bb 100644 --- a/Packages/com.unity.shadergraph/Editor/UIResources.meta +++ b/Packages/com.unity.render-pipelines.universal/DocCodeSamples.Tests.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: c6cba29f8d5a44d5af357f36b630f0b3 +guid: 0e1fbca4ec8742e18ab70240adb15654 folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/Packages/com.unity.render-pipelines.universal/DocCodeSamples.Tests/GlobalShaderVariablesSamples.cs b/Packages/com.unity.render-pipelines.universal/DocCodeSamples.Tests/GlobalShaderVariablesSamples.cs new file mode 100644 index 00000000000..812d620b3af --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/DocCodeSamples.Tests/GlobalShaderVariablesSamples.cs @@ -0,0 +1,464 @@ +using UnityEngine; +using UnityEngine.Experimental.Rendering; +using UnityEngine.Rendering; +using UnityEngine.Rendering.RenderGraphModule; +using UnityEngine.Rendering.Universal; + +// Code samples of the URP global shader variables API. The API documentation shows the regions of this file through +// , so rename a region in the XML documentation too. Keep the empty /// line between +// the before a sample and its element: without it, the documentation shows the sample as code only up to +// its first blank line. This assembly compiles only when the tests of the package compile (UNITY_INCLUDE_TESTS), which +// keeps the samples compiling. + +#region temporary-copy +class HalfResolutionOpaquePass : ScriptableRenderPass +{ + static readonly int s_HalfResolutionOpaqueTextureId = Shader.PropertyToID("_HalfResolutionOpaqueTexture"); + + class PassData + { + public UniversalGlobalShaderData globalShaderData; + public RendererListHandle rendererList; + public Vector2Int size; + } + + public HalfResolutionOpaquePass() + { + // The pass reads the descriptors of the camera textures, which the back buffer doesn't have. + requiresIntermediateTexture = true; + } + + public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) + { + UniversalResourceData resourceData = frameData.Get(); + UniversalRenderingData renderingData = frameData.Get(); + UniversalCameraData cameraData = frameData.Get(); + UniversalLightData lightData = frameData.Get(); + + TextureDesc colorDesc = resourceData.activeColorTexture.GetDescriptor(renderGraph); + colorDesc.width = Mathf.Max(1, colorDesc.width / 2); + colorDesc.height = Mathf.Max(1, colorDesc.height / 2); + colorDesc.name = "_HalfResolutionOpaqueTexture"; + colorDesc.clearBuffer = true; + TextureDesc depthDesc = resourceData.activeDepthTexture.GetDescriptor(renderGraph); + depthDesc.width = colorDesc.width; + depthDesc.height = colorDesc.height; + depthDesc.name = "_HalfResolutionOpaqueDepth"; + depthDesc.clearBuffer = true; + TextureHandle color = renderGraph.CreateTexture(colorDesc); + + using IRasterRenderGraphBuilder builder = renderGraph.AddRasterRenderPass("Half Resolution Opaque", + out PassData passData); + + // Keep the UniversalGlobalShaderData item in the pass data. + // Its variables are available only while the render graph executes. + passData.globalShaderData = frameData.Get(); + passData.size = new Vector2Int(colorDesc.width, colorDesc.height); + + DrawingSettings drawingSettings = RenderingUtils.CreateDrawingSettings(new ShaderTagId("UniversalForward"), + renderingData, cameraData, lightData, SortingCriteria.CommonOpaque); + RendererListParams rendererListParams = new RendererListParams(renderingData.cullResults, drawingSettings, + new FilteringSettings(RenderQueueRange.opaque)); + passData.rendererList = renderGraph.CreateRendererList(rendererListParams); + builder.UseRendererList(passData.rendererList); + + builder.SetRenderAttachment(color, 0); + builder.SetRenderAttachmentDepth(renderGraph.CreateTexture(depthDesc), AccessFlags.Write); + builder.SetGlobalTextureAfterPass(color, s_HalfResolutionOpaqueTextureId); + + // Pushing shader variables changes global state. + builder.AllowGlobalStateModification(true); + + builder.SetRenderFunc(static (PassData data, RasterGraphContext context) => + { + // Disposing the copy at the end of the using scope restores the values the later passes read. + using IUniversalGlobalShaderVariablesTemporaryUploader globals = data.globalShaderData.Get(); + globals._ScreenSize = new Vector4(data.size.x, data.size.y, 1f / data.size.x, 1f / data.size.y); + globals.Push(context.cmd); + + context.cmd.DrawRendererList(data.rendererList); + }); + } +} + +class HalfResolutionOpaqueFeature : ScriptableRendererFeature +{ + HalfResolutionOpaquePass m_Pass; + + public override void Create() + { + m_Pass = new HalfResolutionOpaquePass { renderPassEvent = RenderPassEvent.AfterRenderingOpaques }; + } + + public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData renderingData) + { + renderer.EnqueuePass(m_Pass); + } +} +#endregion + +#region temporary-copy-compute +class QuarterResolutionComputePass : ScriptableRenderPass +{ + static readonly int s_ResultId = Shader.PropertyToID("_Result"); + static readonly int s_QuarterResolutionTextureId = Shader.PropertyToID("_QuarterResolutionTexture"); + + class PassData + { + public UniversalGlobalShaderData globalShaderData; + public ComputeShader computeShader; + public int kernel; + public TextureHandle result; + public Vector2Int size; + } + + readonly ComputeShader m_ComputeShader; + readonly int m_Kernel; + + public QuarterResolutionComputePass(ComputeShader computeShader) + { + m_ComputeShader = computeShader; + m_Kernel = computeShader.FindKernel("CSMain"); + + // The pass reads the descriptor of the camera color texture, which the back buffer doesn't have. + requiresIntermediateTexture = true; + } + + public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) + { + UniversalResourceData resourceData = frameData.Get(); + + TextureDesc desc = resourceData.activeColorTexture.GetDescriptor(renderGraph); + desc.width = Mathf.Max(1, desc.width / 4); + desc.height = Mathf.Max(1, desc.height / 4); + desc.name = "_QuarterResolutionTexture"; + desc.enableRandomWrite = true; + desc.msaaSamples = MSAASamples.None; + + using IComputeRenderGraphBuilder builder = renderGraph.AddComputePass("Quarter Resolution Compute", + out PassData passData); + passData.globalShaderData = frameData.Get(); + passData.computeShader = m_ComputeShader; + passData.kernel = m_Kernel; + passData.result = renderGraph.CreateTexture(desc); + passData.size = new Vector2Int(desc.width, desc.height); + builder.UseTexture(passData.result, AccessFlags.Write); + builder.SetGlobalTextureAfterPass(passData.result, s_QuarterResolutionTextureId); + + // With loose uniforms, PushToCompute() pushes the values globally, which changes global state. + builder.AllowGlobalStateModification(true); + + builder.SetRenderFunc(static (PassData data, ComputeGraphContext context) => + { + using IUniversalGlobalShaderVariablesTemporaryUploader globals = data.globalShaderData.Get(); + globals._ScreenSize = new Vector4(data.size.x, data.size.y, 1f / data.size.x, 1f / data.size.y); + globals.PushToCompute(context.cmd, data.computeShader); + + context.cmd.SetComputeTextureParam(data.computeShader, data.kernel, s_ResultId, data.result); + context.cmd.DispatchCompute(data.computeShader, data.kernel, (data.size.x + 7) / 8, (data.size.y + 7) / 8, 1); + }); + } +} +#endregion + +#region global-variables +class SharpenTexturesPass : ScriptableRenderPass +{ + class PassData + { + public UniversalGlobalShaderData globalShaderData; + public float mipBias; + } + + public float mipBias = -1f; + + public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) + { + using IUnsafeRenderGraphBuilder builder = renderGraph.AddUnsafePass("Sharpen Textures", + out PassData passData); + passData.globalShaderData = frameData.Get(); + passData.mipBias = mipBias; + + // The pass changes what the later passes read, so it must allow global state modification. + builder.AllowGlobalStateModification(true); + + builder.SetRenderFunc(static (PassData data, UnsafeGraphContext context) => + { + IUniversalGlobalShaderVariablesUploader globals = data.globalShaderData.GetGlobal(); + globals._GlobalMipBias = new Vector2(data.mipBias, Mathf.Pow(2f, data.mipBias)); + globals.Push(context.cmd); + }); + } +} +#endregion + +#region restore-camera-values +class RestoreCameraValuesPass : ScriptableRenderPass +{ + class PassData + { + public UniversalGlobalShaderData globalShaderData; + public bool keepMipBias; + } + + public bool keepMipBias; + + public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) + { + using IUnsafeRenderGraphBuilder builder = renderGraph.AddUnsafePass("Restore Camera Values", + out PassData passData); + passData.globalShaderData = frameData.Get(); + passData.keepMipBias = keepMipBias; + builder.AllowGlobalStateModification(true); + + builder.SetRenderFunc(static (PassData data, UnsafeGraphContext context) => + { + IUniversalGlobalShaderVariablesUploader globals = data.globalShaderData.GetGlobal(); + if (!data.keepMipBias) + { + globals.PushDefault(context.cmd); + return; + } + + // ResetToDefault() doesn't push, so the reset and the kept mip bias reach the GPU in a single push. + Vector2 mipBias = globals._GlobalMipBias; + globals.ResetToDefault(); + globals._GlobalMipBias = mipBias; + globals.Push(context.cmd); + }); + } +} +#endregion + +#region temporary-copy-camera-values +class CameraValuesLayerPass : ScriptableRenderPass +{ + class PassData + { + public UniversalGlobalShaderData globalShaderData; + public RendererListHandle rendererList; + } + + public LayerMask layerMask; + + public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) + { + UniversalResourceData resourceData = frameData.Get(); + UniversalRenderingData renderingData = frameData.Get(); + UniversalCameraData cameraData = frameData.Get(); + UniversalLightData lightData = frameData.Get(); + + using IRasterRenderGraphBuilder builder = renderGraph.AddRasterRenderPass("Camera Values Layer", + out PassData passData); + passData.globalShaderData = frameData.Get(); + + DrawingSettings drawingSettings = RenderingUtils.CreateDrawingSettings(new ShaderTagId("UniversalForward"), + renderingData, cameraData, lightData, SortingCriteria.CommonOpaque); + RendererListParams rendererListParams = new RendererListParams(renderingData.cullResults, drawingSettings, + new FilteringSettings(RenderQueueRange.opaque, layerMask)); + passData.rendererList = renderGraph.CreateRendererList(rendererListParams); + builder.UseRendererList(passData.rendererList); + builder.SetRenderAttachment(resourceData.activeColorTexture, 0); + builder.SetRenderAttachmentDepth(resourceData.activeDepthTexture, AccessFlags.ReadWrite); + builder.AllowGlobalStateModification(true); + + builder.SetRenderFunc(static (PassData data, RasterGraphContext context) => + { + using IUniversalGlobalShaderVariablesTemporaryUploader globals = data.globalShaderData.Get(); + globals.ResetToDefault(); + globals.Push(context.cmd); + + context.cmd.DrawRendererList(data.rendererList); + }); + } +} +#endregion + +#region both-renderers +class CameraTargetSizePass : ScriptableRenderPass +{ + class PassData + { + // Only one of them is set, depending on the renderer that runs the pass. + public UniversalGlobalShaderData globalShaderData; + public Universal2DGlobalShaderData globalShaderData2D; + public Vector2Int size; + } + + public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) + { + Camera camera = frameData.Get().camera; + + using IUnsafeRenderGraphBuilder builder = renderGraph.AddUnsafePass("Camera Target Size", + out PassData passData); + if (frameData.Contains()) + passData.globalShaderData = frameData.Get(); + else + passData.globalShaderData2D = frameData.Get(); + passData.size = new Vector2Int(camera.pixelWidth, camera.pixelHeight); + builder.AllowGlobalStateModification(true); + + builder.SetRenderFunc(static (PassData data, UnsafeGraphContext context) => + { + // IGlobalShaderVariablesCommonUploader has the variables that both renderers fill. + IGlobalShaderVariablesCommonUploader globals; + if (data.globalShaderData != null) + globals = data.globalShaderData.GetGlobal(); + else + globals = data.globalShaderData2D.GetGlobal(); + + globals._ScreenSize = new Vector4(data.size.x, data.size.y, 1f / data.size.x, 1f / data.size.y); + globals.Push(context.cmd); + }); + } +} +#endregion + +#region renderer-2d +class FrozenTimeSpritesPass : ScriptableRenderPass +{ + class PassData + { + public Universal2DGlobalShaderData globalShaderData; + public RendererListHandle rendererList; + public float time; + } + + public LayerMask layerMask; + public float frozenTime; + + public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) + { + UniversalResourceData resourceData = frameData.Get(); + UniversalRenderingData renderingData = frameData.Get(); + UniversalCameraData cameraData = frameData.Get(); + UniversalLightData lightData = frameData.Get(); + + using IRasterRenderGraphBuilder builder = renderGraph.AddRasterRenderPass("Frozen Time Sprites", + out PassData passData); + passData.globalShaderData = frameData.Get(); + passData.time = frozenTime; + + DrawingSettings drawingSettings = RenderingUtils.CreateDrawingSettings(new ShaderTagId("Universal2D"), + renderingData, cameraData, lightData, SortingCriteria.CommonTransparent); + RendererListParams rendererListParams = new RendererListParams(renderingData.cullResults, drawingSettings, + new FilteringSettings(RenderQueueRange.transparent, layerMask)); + passData.rendererList = renderGraph.CreateRendererList(rendererListParams); + builder.UseRendererList(passData.rendererList); + builder.SetRenderAttachment(resourceData.activeColorTexture, 0); + builder.AllowGlobalStateModification(true); + + builder.SetRenderFunc(static (PassData data, RasterGraphContext context) => + { + using IUniversal2DGlobalShaderVariablesTemporaryUploader globals = data.globalShaderData.Get(); + float time = data.time; + globals._Time = new Vector4(time / 20f, time, time * 2f, time * 3f); + globals._SinTime = new Vector4(Mathf.Sin(time / 8f), Mathf.Sin(time / 4f), Mathf.Sin(time / 2f), + Mathf.Sin(time)); + globals._CosTime = new Vector4(Mathf.Cos(time / 8f), Mathf.Cos(time / 4f), Mathf.Cos(time / 2f), + Mathf.Cos(time)); + globals._TimeParameters = new Vector4(time, Mathf.Sin(time), Mathf.Cos(time), 0f); + globals.Push(context.cmd); + + context.cmd.DrawRendererList(data.rendererList); + }); + } +} +#endregion + +#region shadow-structs +class FirstCascadeShadowsPass : ScriptableRenderPass +{ + class PassData + { + public UniversalGlobalShaderData globalShaderData; + public RendererListHandle rendererList; + } + + public LayerMask layerMask; + + public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) + { + UniversalResourceData resourceData = frameData.Get(); + UniversalRenderingData renderingData = frameData.Get(); + UniversalCameraData cameraData = frameData.Get(); + UniversalLightData lightData = frameData.Get(); + + using IRasterRenderGraphBuilder builder = renderGraph.AddRasterRenderPass("First Cascade Shadows", + out PassData passData); + passData.globalShaderData = frameData.Get(); + + DrawingSettings drawingSettings = RenderingUtils.CreateDrawingSettings(new ShaderTagId("UniversalForward"), + renderingData, cameraData, lightData, SortingCriteria.CommonOpaque); + RendererListParams rendererListParams = new RendererListParams(renderingData.cullResults, drawingSettings, + new FilteringSettings(RenderQueueRange.opaque, layerMask)); + passData.rendererList = renderGraph.CreateRendererList(rendererListParams); + builder.UseRendererList(passData.rendererList); + builder.SetRenderAttachment(resourceData.activeColorTexture, 0); + builder.SetRenderAttachmentDepth(resourceData.activeDepthTexture, AccessFlags.ReadWrite); + builder.AllowGlobalStateModification(true); + + builder.SetRenderFunc(static (PassData data, RasterGraphContext context) => + { + using IUniversalGlobalShaderVariablesTemporaryUploader globals = data.globalShaderData.Get(); + + // The properties return copies of the structs: read the property, change the copy, and assign it back. + MainLightShadowMatrices matrices = globals._MainLightWorldToShadow; + MainLightShadowCascadeVectors pcssAtlas = globals._MainLightPCSSAtlas; + for (int cascade = 1; cascade < MainLightShadowMatrices.count - 1; cascade++) + { + matrices[cascade] = matrices.cascade4; + pcssAtlas[cascade] = pcssAtlas.cascade4; + } + globals._MainLightWorldToShadow = matrices; + globals._MainLightPCSSAtlas = pcssAtlas; + globals.Push(context.cmd); + + context.cmd.DrawRendererList(data.rendererList); + }); + } +} +#endregion + +#region outside-camera-rendering +static class MeshPreview +{ + static readonly int s_GlobalShaderVariablesId = Shader.PropertyToID("GlobalShaderVariables"); + static readonly int s_ScreenSizeId = Shader.PropertyToID("_ScreenSize"); + static readonly ShaderTagId s_LightModeTag = new ShaderTagId("LightMode"); + static readonly ShaderTagId s_UniversalForwardLightMode = new ShaderTagId("UniversalForward"); + + public static void Render(RenderTexture target, Mesh mesh, Material material, Matrix4x4 view, Matrix4x4 projection) + { + CommandBuffer cmd = new CommandBuffer { name = "Mesh Preview" }; + cmd.SetRenderTarget(target); + cmd.ClearRenderTarget(true, true, Color.clear); + cmd.SetViewProjectionMatrices(view, projection); + + // While Use Persistent Global Constant Buffer is enabled, the buffer that URP bound for its last camera stays + // bound, and the shaders don't read what SetGlobal* sets. Unbind the buffer first. URP binds it again for its + // next camera. + cmd.SetGlobalConstantBuffer((GraphicsBuffer)null, s_GlobalShaderVariablesId, 0, 0); + + // Then set the variables that the shaders read. + cmd.SetGlobalVector(s_ScreenSizeId, new Vector4(target.width, target.height, 1f / target.width, 1f / target.height)); + + int pass = FindPassWithLightMode(material, s_UniversalForwardLightMode); + if (pass >= 0) + cmd.DrawMesh(mesh, Matrix4x4.identity, material, 0, pass); + Graphics.ExecuteCommandBuffer(cmd); + cmd.Release(); + } + + // Pass names differ between URP shaders, for example ForwardLit in URP Lit, but the light mode tag doesn't. + static int FindPassWithLightMode(Material material, ShaderTagId lightMode) + { + for (int i = 0; i < material.passCount; i++) + { + if (material.shader.FindPassTagValue(i, s_LightModeTag) == lightMode) + return i; + } + return -1; + } +} +#endregion diff --git a/Packages/com.unity.render-pipelines.universal/DocCodeSamples.Tests/GlobalShaderVariablesSamples.cs.meta b/Packages/com.unity.render-pipelines.universal/DocCodeSamples.Tests/GlobalShaderVariablesSamples.cs.meta new file mode 100644 index 00000000000..05528725471 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/DocCodeSamples.Tests/GlobalShaderVariablesSamples.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9158f0567ff7446ba24ff6f4ffb5eed5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/DocCodeSamples.Tests/Unity.RenderPipelines.Universal.DocCodeSamples.asmdef b/Packages/com.unity.render-pipelines.universal/DocCodeSamples.Tests/Unity.RenderPipelines.Universal.DocCodeSamples.asmdef new file mode 100644 index 00000000000..88151a0fb12 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/DocCodeSamples.Tests/Unity.RenderPipelines.Universal.DocCodeSamples.asmdef @@ -0,0 +1,25 @@ +{ + "name": "Unity.RenderPipelines.Universal.DocCodeSamples", + "rootNamespace": "", + "references": [ + "GUID:15fc0a57446b3144c949da3e2b9737a9", + "GUID:df380645f10b7bc4b97d4f5eb6303d95", + "GUID:27619889b8ba8c24980f49ee34dbb44a", + "GUID:0acc523941302664db1f4e527237feb3" + ], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": true, + "precompiledReferences": [ + "nunit.framework.dll" + ], + "autoReferenced": false, + "defineConstraints": [ + "UNITY_INCLUDE_TESTS" + ], + "versionDefines": [], + "noEngineReferences": false +} diff --git a/Packages/com.unity.render-pipelines.universal/DocCodeSamples.Tests/Unity.RenderPipelines.Universal.DocCodeSamples.asmdef.meta b/Packages/com.unity.render-pipelines.universal/DocCodeSamples.Tests/Unity.RenderPipelines.Universal.DocCodeSamples.asmdef.meta new file mode 100644 index 00000000000..0d42df8c053 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/DocCodeSamples.Tests/Unity.RenderPipelines.Universal.DocCodeSamples.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: cc3e56d1b83240018b2d2aa5a2e9149d +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/BuiltInPixelPerfectCameraConverter.cs b/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/BuiltInPixelPerfectCameraConverter.cs index cb28daa1473..48792a508c6 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/BuiltInPixelPerfectCameraConverter.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/BuiltInPixelPerfectCameraConverter.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using UnityEditor.Rendering.Converter; +using UnityEditor.Search; using UnityEngine; using UnityEngine.Categorization; @@ -45,6 +46,58 @@ internal static T FindComponent(GameObject root, string globalObjectId) where return null; } + internal static PixelPerfectCameraConverterItem CreateItem(SearchItem item) + { + // Direct conversion - works for both assets and scene objects + var unityObject = item.ToObject(); + + if (unityObject == null) + return CreateUnloadedSceneObjectItem(item); + + // Ensure we're always working with GameObjects + GameObject go = null; + + if (unityObject is GameObject gameObject) + go = gameObject; + else if (unityObject is Component component) + go = component.gameObject; + else + return null; // Not a GameObject or Component + + var gid = GlobalObjectId.GetGlobalObjectIdSlow(go); + + if (gid.identifierType == GlobalObjectIdentifierType.ImportedAsset) + { + return new PixelPerfectCameraConverterItem(gid.ToString()) + { + name = $"{unityObject.name} (Prefab)", + info = AssetDatabase.GetAssetPath(unityObject), + }; + } + + return new PixelPerfectCameraConverterItem(gid.ToString()) + { + name = AssetsConverter.GetSceneObjectName(UnityEditor.Search.SearchUtils.GetTransformPath(go.transform)), + info = go.scene.path, + }; + } + + // A scene object only loads while its scene is open, so build the item from the search result and let + // Convert open the scene + static PixelPerfectCameraConverterItem CreateUnloadedSceneObjectItem(SearchItem item) + { + var scenePath = AssetsConverter.GetUnloadedScenePath(item.id); + if (scenePath == null) + return null; + + // Search labels scene objects with their path in the hierarchy + return new PixelPerfectCameraConverterItem(item.id) + { + name = AssetsConverter.GetSceneObjectName(item.GetLabel(item.context, true) ?? string.Empty), + info = scenePath, + }; + } + #if PIXEL_PERFECT_2D_EXISTS public bool isEnabled => true; public string isDisabledMessage { get; } @@ -118,35 +171,9 @@ void OnSearchFinish() new List<(string query, string description)> { ("t:UnityEngine.U2D.PixelPerfectCamera", "Game Objects Referencing a U2D Pixel Perfect Camera") }, (item, description) => { - // Direct conversion - works for both assets and scene objects - var unityObject = item.ToObject(); - - if (unityObject == null) - return; - - // Ensure we're always working with GameObjects - GameObject go = null; - - if (unityObject is GameObject gameObject) - go = gameObject; - else if (unityObject is Component component) - go = component.gameObject; - else - return; // Not a GameObject or Component - - var gid = GlobalObjectId.GetGlobalObjectIdSlow(go); - if (!processedIds.Add(gid.ToString())) - return; - - int type = gid.identifierType; // 1=Asset, 2=SceneObject - - var ppCameraItem = new PixelPerfectCameraConverterItem(gid.ToString()) - { - name = $"{unityObject.name} ({(type == 1 ? "Prefab" : "SceneObject")})", - info = type == 1 ? AssetDatabase.GetAssetPath(unityObject) : go.scene.path, - }; - - returnList.Add(ppCameraItem); + var ppCameraItem = CreateItem(item); + if (ppCameraItem != null && processedIds.Add(ppCameraItem.GlobalObjectId)) + returnList.Add(ppCameraItem); }, OnSearchFinish ); diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/BuiltInToURP2DReadonlyMaterialConverter.cs b/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/BuiltInToURP2DReadonlyMaterialConverter.cs index 5277689e34e..033e674c122 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/BuiltInToURP2DReadonlyMaterialConverter.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/BuiltInToURP2DReadonlyMaterialConverter.cs @@ -29,6 +29,13 @@ public override bool isEnabled public override string isDisabledMessage => "Converter requires URP with a 2D Renderer. Convert your project to URP to use this converter."; + public override void BeforeConvert() + { + // The replacement materials live in the global settings, which may not exist yet or be out of date + UniversalRenderPipelineGlobalSettings.Ensure(); + base.BeforeConvert(); + } + protected override Dictionary> materialMappings { get diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/ParametricToFreeformLightUpgrader.cs b/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/ParametricToFreeformLightUpgrader.cs index 9ef67901770..93ba6ecc1c5 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/ParametricToFreeformLightUpgrader.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/ParametricToFreeformLightUpgrader.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using UnityEditor.Rendering.Converter; using UnityEditor.SceneManagement; +using UnityEditor.Search; using UnityEngine; using UnityEngine.Categorization; using UnityEngine.Rendering; @@ -69,42 +70,59 @@ void OnSearchFinish() }, (item, description) => { - // Direct conversion - works for both assets and scene objects - var unityObject = item.ToObject(); + var lightUpgraderItem = CreateItem(item); + if (lightUpgraderItem != null && processedIds.Add(lightUpgraderItem.GlobalObjectId)) + returnList.Add(lightUpgraderItem); + }, + OnSearchFinish + ); + } - if (unityObject == null) - return; + internal static ParametricToFreeformLightUpgraderItem CreateItem(SearchItem item) + { + // Direct conversion - works for both assets and scene objects + var unityObject = item.ToObject(); - // Ensure we're always working with GameObjects - GameObject go = null; + if (unityObject == null) + return CreateUnloadedSceneObjectItem(item); - if (unityObject is GameObject gameObject) - go = gameObject; - else if (unityObject is Component component) - go = component.gameObject; - else - return; // Not a GameObject or Component + // Ensure we're always working with GameObjects + GameObject go = null; - var gid = GlobalObjectId.GetGlobalObjectIdSlow(go); - if (!processedIds.Add(gid.ToString())) - return; + if (unityObject is GameObject gameObject) + go = gameObject; + else if (unityObject is Component component) + go = component.gameObject; + else + return null; // Not a GameObject or Component - int type = gid.identifierType; // 1=Asset, 2=SceneObject + var gid = GlobalObjectId.GetGlobalObjectIdSlow(go); - var isPrefab = type == 1; - var lightUpgraderItem = new ParametricToFreeformLightUpgraderItem(gid.ToString()) - { - info = isPrefab - ? $"Prefab: {AssetDatabase.GetAssetPath(unityObject)}" - : $"Scene: {go.scene.path}", - type = type - }; + int type = gid.identifierType; // 1=Asset, 2=SceneObject + var isPrefab = type == 1; + return new ParametricToFreeformLightUpgraderItem(gid.ToString()) + { + info = isPrefab + ? $"Prefab: {AssetDatabase.GetAssetPath(unityObject)}" + : $"Scene: {go.scene.path}", + type = type + }; + } - returnList.Add(lightUpgraderItem); - }, - OnSearchFinish - ); + // A scene object only loads while its scene is open, so build the item from the search result and let + // Convert open the scene + static ParametricToFreeformLightUpgraderItem CreateUnloadedSceneObjectItem(SearchItem item) + { + var scenePath = AssetsConverter.GetUnloadedScenePath(item.id); + if (scenePath == null) + return null; + + return new ParametricToFreeformLightUpgraderItem(item.id) + { + info = $"Scene: {scenePath}", + type = GlobalObjectIdentifierType.SceneObject + }; } const float k_EnscribedSquareDiagonalLength = 0.70710678118654752440084436210485f; diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/URP3DToURP2DReadonlyMaterialConverter.cs b/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/URP3DToURP2DReadonlyMaterialConverter.cs index 7b2e5993eca..1f58365ec1d 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/URP3DToURP2DReadonlyMaterialConverter.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/URP3DToURP2DReadonlyMaterialConverter.cs @@ -30,6 +30,13 @@ public override bool isEnabled public override string isDisabledMessage => "Converter requires URP with a 2D Renderer. Convert your project to URP to use this converter."; + public override void BeforeConvert() + { + // The replacement materials live in the global settings, which may not exist yet or be out of date + UniversalRenderPipelineGlobalSettings.Ensure(); + base.BeforeConvert(); + } + private bool m_Initialized = false; private void InitializeIfNeeded() diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/Light2DPrefilteringAnalysis.cs b/Packages/com.unity.render-pipelines.universal/Editor/2D/Light2DPrefilteringAnalysis.cs index f45408a7a24..c5653a98a5a 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/2D/Light2DPrefilteringAnalysis.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/Light2DPrefilteringAnalysis.cs @@ -28,7 +28,7 @@ static class Light2DPrefilteringAnalysis // - Non-volumetric draws enable exactly one USE_SHAPE_LIGHT_TYPE_, where N is the // light's rank among the blend styles in use in its layer batch. // - Volumetric draws enable none (the USE_DEFAULT_LIGHT_TYPE shader fallback handles it). - // - On GLES3 (Renderer2D.supportsMRT == false) the index is forced to 0 regardless. + // - On OpenGLES3 and OpenGLCore (Renderer2D.supportsMRT == false) the index is forced to 0 regardless. // The 11 multi-keyword combinations multi_compile generates are unreachable for this shader. static readonly string[] kShapeLightTypeKeywords = { @@ -45,12 +45,44 @@ static class Light2DPrefilteringAnalysis internal const string kEmptyComboSentinel = ""; /// - /// Walks every enabled build scene and returns the set of comma-joined keyword combos + /// Walks every scene a build can include and returns the set of comma-joined keyword combos /// that could legitimately request at /// runtime. Scenes opened by this method are closed before returning so we don't disturb /// the user's editor workspace. /// internal static string[] AnalyzeBuildScenes() + { + return AnalyzeScenes(GetCandidateScenePaths()); + } + + // The scenes a player build can include. BuildPipeline.BuildPlayer can build scenes that + // are not in the Build Profiles list (UUM-160655). Only BuildPlayerProcessor.PrepareForBuild + // sees its scene list, and this analysis also runs for AssetBundle builds and from + // IPreprocessShaders, where no player scene list exists. So scan the enabled Build Profiles + // scenes (any path, including Packages/) plus every scene under Assets/. + internal static IEnumerable GetCandidateScenePaths() + { + foreach (var sceneSettings in EditorBuildSettings.scenes) + { + // Use the same path the build uses (EditorBuildSettingsScene.GetActiveSceneList). + // The engine already updates this path from the GUID when a scene is moved. + if (sceneSettings.enabled) + yield return sceneSettings.path; + } + + foreach (var guid in AssetDatabase.FindAssets("t:SceneAsset", new[] { "Assets" })) + yield return AssetDatabase.GUIDToAssetPath(guid); + } + + /// + /// Analyzes the given scenes, as does for the build's + /// candidate scenes. Paths that are not scene assets are skipped, a scene listed twice is + /// analyzed once, and a scene that doesn't depend on is not opened. + /// + /// Scene asset paths to analyze. + /// If not null, receives the path of each scene opened for analysis. + /// The kept keyword combos. + internal static string[] AnalyzeScenes(IEnumerable scenePaths, ICollection openedScenePaths = null) { HashSet combos = new HashSet(); @@ -60,31 +92,38 @@ internal static string[] AnalyzeBuildScenes() // DontDestroyOnLoad. So the slots are added once all build scenes have been scanned. var shapeLightDraws = new HashSet[kShapeLightTypeKeywords.Length]; - EditorBuildSettingsScene[] scenes = EditorBuildSettings.scenes; - foreach (var sceneSettings in scenes) - { - if (!sceneSettings.enabled) - continue; - - // Use the same path the build uses (EditorBuildSettingsScene.GetActiveSceneList), so - // we analyze exactly the scenes that get built. The engine already updates this path - // from the GUID when a scene is moved. - string scenePath = sceneSettings.path; + // Dedupe by GUID, so case or slash differences in a path don't scan a scene twice. + var visitedGuids = new HashSet(); + string light2DScriptPath = GetLight2DScriptPath(); + foreach (var scenePath in scenePaths) + { // Skip entries that don't point at a scene asset (deleted, never existed, or not a // scene); OpenScene would throw. Use the AssetDatabase rather than File.Exists so // scenes in immutable packages (virtual Packages/... paths) are still found. if (string.IsNullOrEmpty(scenePath) || AssetDatabase.GetMainAssetTypeAtPath(scenePath) != typeof(SceneAsset)) continue; + if (!visitedGuids.Add(AssetDatabase.AssetPathToGUID(scenePath))) + continue; + Scene scene = EditorSceneManager.GetSceneByPath(scenePath); bool weOpenedIt = !scene.isLoaded; + // The dependency check reads the saved file, so only use it to skip opening a scene. + // A loaded scene can hold a Light2D added since its last save, which the build will + // include once the user saves at the build prompt, so always scan the loaded scene. + if (weOpenedIt && !SceneMayContainLight2D(scenePath, light2DScriptPath)) + continue; + // Open as a preview scene rather than additively: Light2DManager registers preview // scene lights in a per scene list, so a global light in a build scene can't be // mistaken for a duplicate of one in a scene the user already has open. if (weOpenedIt) + { scene = EditorSceneManager.OpenPreviewScene(scenePath); + openedScenePaths?.Add(scenePath); + } try { @@ -107,6 +146,41 @@ internal static string[] AnalyzeBuildScenes() return result; } + // The asset path of the script that defines Light2D, or null if it can't be found. + static string GetLight2DScriptPath() + { + foreach (var guid in AssetDatabase.FindAssets("t:MonoScript " + nameof(Light2D))) + { + // The search matches every script whose name contains "Light2D". A MonoScript's + // class must match its file name, so skip the others without loading them. + string path = AssetDatabase.GUIDToAssetPath(guid); + if (System.IO.Path.GetFileNameWithoutExtension(path) != nameof(Light2D)) + continue; + + var script = AssetDatabase.LoadAssetAtPath(path); + if (script != null && script.GetClass() == typeof(Light2D)) + return path; + } + return null; + } + + // Opening a scene is costly, so first check whether it references the Light2D script. + // The recursive lookup also finds Light2Ds in nested prefabs and prefab variants, and it + // reads the asset database, so it works the same for text and binary scenes. If the script + // can't be found, open the scene anyway rather than miss its lights. + static bool SceneMayContainLight2D(string scenePath, string light2DScriptPath) + { + if (light2DScriptPath == null) + return true; + + foreach (var dependency in AssetDatabase.GetDependencies(scenePath, true)) + { + if (string.Equals(dependency, light2DScriptPath, System.StringComparison.OrdinalIgnoreCase)) + return true; + } + return false; + } + static void AnalyzeSceneForLights(Scene scene, HashSet combos, HashSet[] shapeLightDraws) { foreach (var rootObject in scene.GetRootGameObjects()) @@ -124,8 +198,8 @@ static void AnalyzeSceneForLights(Scene scene, HashSet combos, HashSet[] shapeLightDraws, HashSet combos) { int blendStyleRank = 0; diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/Unity.RenderPipelines.Universal.2D.Editor.Overrides.asmdef b/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/Unity.RenderPipelines.Universal.2D.Editor.Overrides.asmdef index 40745ec8b32..3899d3d3e7d 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/Unity.RenderPipelines.Universal.2D.Editor.Overrides.asmdef +++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/Unity.RenderPipelines.Universal.2D.Editor.Overrides.asmdef @@ -45,6 +45,11 @@ "expression": "4.0.1", "define": "XR_MANAGEMENT_4_0_1_OR_NEWER" }, + { + "name": "com.unity.xr.foundation", + "expression": "7.0.0", + "define": "XR_FOUNDATION_7_0_0_OR_NEWER" + }, { "name": "com.unity.visualeffectgraph", "expression": "1.0.0", diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/Light2DPass.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/Light2DPass.hlsl index 2df8da14f26..157f66bb063 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/Light2DPass.hlsl +++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/Light2DPass.hlsl @@ -251,5 +251,12 @@ FragmentOutput frag(PackedVaryings packedInput) lightColor *= _L2D_VOLUME_OPACITY; #endif - return ToFragmentOutput(lightColor * _InverseHDREmulationScale); + // Mirror Hidden/Light2D: shape and provider lights scale RGB only + // (vert_shape_shared), while Point lights scale RGBA (frag_point). + // Scaling alpha for shape lights darkens them under Alpha Blend overlap. + if (_L2D_LIGHT_TYPE == 3) + lightColor *= _InverseHDREmulationScale; + else + lightColor.rgb *= _InverseHDREmulationScale; + return ToFragmentOutput(lightColor); } diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/RenderingLayerMaskPass.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/RenderingLayerMaskPass.hlsl index 40f86779301..7a2505eaac7 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/RenderingLayerMaskPass.hlsl +++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/RenderingLayerMaskPass.hlsl @@ -2,8 +2,6 @@ #include "Packages/com.unity.render-pipelines.universal/Shaders/2D/Include/SurfaceData2D.hlsl" #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Debug/Debugging2D.hlsl" -half4 _RendererColor; - PackedVaryings vert(Attributes input) { Varyings output = (Varyings)0; @@ -15,7 +13,7 @@ PackedVaryings vert(Attributes input) #endif output = BuildVaryings(input); #if !_ENABLE_SORT_3D_AS_2D_COMPATIBLE - output.color *= _RendererColor * unity_SpriteColor; // vertex color has to applied here + output.color *= unity_SpriteColor; // vertex color has to applied here #endif #if defined(DEBUG_DISPLAY) output.normalWS = TransformObjectToWorldNormal(input.normalOS); diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/SpriteForwardPass.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/SpriteForwardPass.hlsl index fda9bbf2516..d32cf53f0dc 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/SpriteForwardPass.hlsl +++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/SpriteForwardPass.hlsl @@ -2,14 +2,12 @@ #include "Packages/com.unity.render-pipelines.universal/Shaders/2D/Include/SurfaceData2D.hlsl" #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Debug/Debugging2D.hlsl" -half4 _RendererColor; - PackedVaryings vert(Attributes input) { Varyings output = (Varyings)0; input.positionOS = UnityFlipSprite(input.positionOS, unity_SpriteProps.xy); output = BuildVaryings(input); - output.color *= _RendererColor * unity_SpriteColor; // vertex color has to applied here + output.color *= unity_SpriteColor; // vertex color has to applied here PackedVaryings packedOutput = PackVaryings(output); return packedOutput; } diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/SpriteLitPass.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/SpriteLitPass.hlsl index a36fe011b1e..34f13716e11 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/SpriteLitPass.hlsl +++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/SpriteLitPass.hlsl @@ -1,8 +1,6 @@ #include "Packages/com.unity.render-pipelines.universal/Shaders/2D/Include/Core2D.hlsl" #include "Packages/com.unity.render-pipelines.universal/Shaders/2D/Include/CombinedShapeLightShared.hlsl" -half4 _RendererColor; - PackedVaryings vert(Attributes input) { Varyings output = (Varyings)0; @@ -11,7 +9,7 @@ PackedVaryings vert(Attributes input) SetUpSpriteInstanceProperties(); input.positionOS = UnityFlipSprite(input.positionOS, unity_SpriteProps.xy); output = BuildVaryings(input); - output.color *= _RendererColor * unity_SpriteColor; // vertex color has to applied here + output.color *= unity_SpriteColor; // vertex color has to applied here #if defined(DEBUG_DISPLAY) output.normalWS = TransformObjectToWorldNormal(input.normalOS); #endif diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/SpriteUnlitPass.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/SpriteUnlitPass.hlsl index f97aa179688..d14b571bddb 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/SpriteUnlitPass.hlsl +++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/SpriteUnlitPass.hlsl @@ -2,8 +2,6 @@ #include "Packages/com.unity.render-pipelines.universal/Shaders/2D/Include/SurfaceData2D.hlsl" #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Debug/Debugging2D.hlsl" -half4 _RendererColor; - PackedVaryings vert(Attributes input) { Varyings output = (Varyings)0; @@ -12,7 +10,7 @@ PackedVaryings vert(Attributes input) SetUpSpriteInstanceProperties(); input.positionOS = UnityFlipSprite(input.positionOS, unity_SpriteProps.xy); output = BuildVaryings(input); - output.color *= _RendererColor * unity_SpriteColor; // vertex color has to applied here + output.color *= unity_SpriteColor; // vertex color has to applied here #if defined(DEBUG_DISPLAY) output.normalWS = TransformObjectToWorldNormal(input.normalOS); #endif diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalSpriteCustomLitSubTarget.cs b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalSpriteCustomLitSubTarget.cs index 727164ea414..4d202245cdc 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalSpriteCustomLitSubTarget.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalSpriteCustomLitSubTarget.cs @@ -202,7 +202,7 @@ public static PassDescriptor RenderingLayerMask(UniversalTarget target) renderStates = Universal2DSubTargetDescriptors.RenderStateCollections.RenderingLayerMask, pragmas = CorePragmas._2DDefault, defines = new DefineCollection(), - keywords = SpriteCustomLitKeywords.Lit, + keywords = SpriteCustomLitKeywords.Normal, includes = SpriteCustomLitIncludes.RenderingLayerMask, // Custom Interpolator Support diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalSpriteLitSubTarget.cs b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalSpriteLitSubTarget.cs index 7eeed3c4f68..d8dd4ab3a7c 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalSpriteLitSubTarget.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalSpriteLitSubTarget.cs @@ -225,7 +225,7 @@ public static PassDescriptor RenderingLayerMask(UniversalTarget target) renderStates = Universal2DSubTargetDescriptors.RenderStateCollections.RenderingLayerMask, pragmas = CorePragmas._2DDefault, defines = new DefineCollection(), - keywords = SpriteLitKeywords.Lit, + keywords = SpriteLitKeywords.Normal, includes = SpriteLitIncludes.RenderingLayerMask, // Custom Interpolator Support diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Analytics/XRGraphics/XRGraphicsAnalyticsUtils.cs b/Packages/com.unity.render-pipelines.universal/Editor/Analytics/XRGraphics/XRGraphicsAnalyticsUtils.cs index ecace02838c..7c143e0d73b 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/Analytics/XRGraphics/XRGraphicsAnalyticsUtils.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/Analytics/XRGraphics/XRGraphicsAnalyticsUtils.cs @@ -1,5 +1,5 @@ using System.Collections.Generic; -#if XR_MANAGEMENT_4_0_1_OR_NEWER +#if XR_MANAGEMENT_4_0_1_OR_NEWER || XR_FOUNDATION_7_0_0_OR_NEWER using UnityEditor.XR.Management; using UnityEngine.XR.Management; #endif @@ -23,7 +23,7 @@ static class XRGraphicsAnalyticsUtils internal static List GetActiveXRLoaders(BuildTargetGroup buildTargetGroup) { var loaders = new List(); -#if XR_MANAGEMENT_4_0_1_OR_NEWER +#if XR_MANAGEMENT_4_0_1_OR_NEWER || XR_FOUNDATION_7_0_0_OR_NEWER XRGeneralSettings generalSettings = XRGeneralSettingsPerBuildTarget.XRGeneralSettingsForBuildTarget(buildTargetGroup); if (generalSettings != null && generalSettings.Manager != null) { diff --git a/Packages/com.unity.render-pipelines.universal/Editor/AssemblyInfo.cs b/Packages/com.unity.render-pipelines.universal/Editor/AssemblyInfo.cs index 3f62d53fbc2..2f24bb351ac 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/AssemblyInfo.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/AssemblyInfo.cs @@ -4,6 +4,7 @@ [assembly: InternalsVisibleTo("UniversalGraphicsTests")] [assembly: InternalsVisibleTo("Universal2DEditorTests")] [assembly: InternalsVisibleTo("Unity.RenderPipelines.Universal.Editor.Tests")] +[assembly: InternalsVisibleTo("Unity.RenderPipelines.Universal.Editor.CLI")] [assembly: InternalsVisibleTo("Unity.Testing.SRP.Universal-Upgrade.Editor")] [assembly: InternalsVisibleTo("Unity.GraphicTests.Performance.Universal.Editor")] [assembly: InternalsVisibleTo("Unity.VisualEffectGraph.EditorTests")] 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 e669e7d733c..0aa6d8c96f5 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(); } } diff --git a/Packages/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/UniversalRenderPipelineAssetPostprocessor.cs b/Packages/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/UniversalRenderPipelineAssetPostprocessor.cs new file mode 100644 index 00000000000..e5322f8d1f9 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/UniversalRenderPipelineAssetPostprocessor.cs @@ -0,0 +1,27 @@ +using System.Collections.Generic; +using UnityEditor.Callbacks; +using UnityEngine.Rendering.Universal; + +namespace UnityEditor.Rendering.Universal +{ + class UniversalRenderPipelineAssetPostprocessor : AssetPostprocessor + { + [RunAfterClass(typeof(UniversalRenderPipelineGlobalSettingsPostprocessor))] + static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) + { + List urpAssets = null; + foreach (var path in importedAssets) + { + if (AssetDatabase.GetMainAssetTypeAtPath(path) != typeof(UniversalRenderPipelineAsset)) + continue; + + var urpAsset = AssetDatabase.LoadAssetAtPath(path); + if (urpAsset != null) + (urpAssets ??= new List()).Add(urpAsset); + } + + if (urpAssets != null) + UniversalRenderPipelineGlobalSettings.MigratePendingShadowSettingsToVolumeProfiles(urpAssets); + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/UniversalRenderPipelineAssetPostprocessor.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/UniversalRenderPipelineAssetPostprocessor.cs.meta new file mode 100644 index 00000000000..a24b40161b5 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/UniversalRenderPipelineAssetPostprocessor.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: fcfbe505c803463db7267a9d96fb96c7 diff --git a/Packages/com.unity.render-pipelines.universal/Editor/BuildProcessors/URPPreprocessBuild.cs b/Packages/com.unity.render-pipelines.universal/Editor/BuildProcessors/URPPreprocessBuild.cs index fe28e64a668..dfe63523ca8 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/BuildProcessors/URPPreprocessBuild.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/BuildProcessors/URPPreprocessBuild.cs @@ -5,6 +5,7 @@ using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Rendering.Universal; +using Unity.RenderPipelines.Core.Runtime.Shared; namespace UnityEditor.Rendering.Universal { @@ -47,9 +48,26 @@ static void EnsureVolumeProfile() { Debug.Log("Default Volume Profile has been modified to ensure all overrides are present. This is required to avoid missing overrides at runtime which can lead to unexpected rendering issues. Please save these changes to avoid this message in the future."); } + else + { + WarnIfReadOnlyProfileMissesOverrides(volumeProfileSettings.volumeProfile); + } } } + static void WarnIfReadOnlyProfileMissesOverrides(VolumeProfile profile) + { + if (!CoreEditorUtils.IsAssetInReadOnlyPackage(AssetDatabase.GetAssetPath(profile))) + return; + + var missingTypes = VolumeProfileUtils.GetTypesMissingFromDefaultProfile(profile, GraphicsSettings.currentRenderPipelineAssetType); + if (missingTypes.Count == 0) + return; + + Debug.LogWarning($"URP: The Default Volume Profile '{AssetLinkUtils.AssetLink(profile)}' is in a read-only package, so the build can't add the volume overrides it's missing: {string.Join(", ", missingTypes.ConvertAll(t => t.Name))}. " + + "The player can't use these overrides from any volume profile. Copy the Default Volume Profile into the Assets folder and assign the copy in Project Settings > Graphics > URP."); + } + internal static void LogIncludedAssets(List assetsList) { using (UnityEngine.Pool.GenericPool.Get(out var assetsIncluded)) diff --git a/Packages/com.unity.render-pipelines.universal/Editor/CLI.meta b/Packages/com.unity.render-pipelines.universal/Editor/CLI.meta new file mode 100644 index 00000000000..666aedc8f21 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Editor/CLI.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 256956375395cc04e949c30843086568 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Editor/CLI/BufferCaptureCLI.cs b/Packages/com.unity.render-pipelines.universal/Editor/CLI/BufferCaptureCLI.cs new file mode 100644 index 00000000000..5a93aca354d --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Editor/CLI/BufferCaptureCLI.cs @@ -0,0 +1,235 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using Newtonsoft.Json; +using Unity.Pipeline.Commands; +using Unity.Pipeline.Editor.Authoring; +using Unity.Pipeline.Models; +using UnityEngine; + +namespace UnityEditor.Rendering.Universal.CLI +{ + /// + /// CLI adapter for BufferCapture: renders a camera offscreen and saves rendering buffers as PNGs. + /// + static class BufferCaptureCLI + { + internal enum View + { + Game, + Scene, + } + + [Serializable] + internal class TargetDescription + { + public string name; + + // Null when no camera could be resolved, so support wasn't checked + public bool? supported; + public string unsupportedReason; + public string description; + } + + [Serializable] + internal class SkippedTarget + { + public string buffer; + public string reason; + } + + [Serializable] + internal class CapturedImage + { + public string buffer; + public string savedPath; + public int width; + public int height; + public string base64; + } + + [Serializable] + internal class ObjectIdOutput + { + public string mappingPath; + public int objectCount; + } + + [Serializable] + internal class CaptureResult + { + public string view; + public string camera; + public string cameraPath; + public string outputDir; + public CapturedImage[] images; + + // Buffers from 'all' that the camera can't produce + public SkippedTarget[] skipped; + + // Null when object_id was not captured + public ObjectIdOutput objectId; + } + + [CliCommand("urp", "list_buffers", "List the buffers 'urp capture_buffers' can produce, and whether the camera supports each one. unsupportedReason says why not (renderer type, shadow settings, ...).", MainThreadRequired = true, Tags = new[] { "capture" }, Effect = CommandEffect.ReadOnly)] + public static ExitCode ListBuffers(CommandContext cmd, + [CliArg("view", "Camera to check support for when 'camera' is not set: 'scene' (last active Scene view) or 'game' (Camera.main).")] View view = View.Game, + [CliArg("camera", "Handle of a Camera or its GameObject (hierarchy path, globalId or instanceId). Overrides 'view'.")] ObjectRef camera = null) + { + if (!BufferCapture.isUniversalRenderPipelineActive) + throw new InvalidOperationException("The Universal Render Pipeline is not active."); + + BufferCapture.ThrowIfRenderingDebuggerActive(); + + Camera cam = null; + try + { + cam = ResolveCamera(view, camera, out _); + } + catch (InvalidOperationException e) when (camera == null || camera.IsEmpty) + { + // Still list the buffers when the view has no camera + cmd.Std.Error.WriteLine($"{e.Message} Buffer support was not checked."); + } + + foreach (var t in UniversalBufferCaptureTargets.all) + { + var reason = cam != null ? t.GetUnsupportedReason(cam) : null; + cmd.Result.WriteRecord(new TargetDescription + { + name = t.name, + supported = cam != null ? reason == null : (bool?)null, + unsupportedReason = reason, + description = t.description, + }); + } + return ExitCode.Success; + } + + [CliCommand("urp", "capture_buffers", "Render a camera offscreen and save rendering buffers (color, depth, albedo, normal, object_id, ...) as PNGs. Does not change what the Editor views display. Example: urp capture_buffers --buffers color,object_id --view scene. --buffers takes a comma-separated list or 'all' (see 'urp list_buffers'). object_id also writes a JSON file mapping colors to GameObjects, with each object's materials and shaders and their status (unsaved changes, shader compile errors). Files go to Temp/CaptureBuffer/ unless --output-dir is set; files already there are overwritten. Fails while any Rendering Debugger setting is active.", MainThreadRequired = true, Tags = new[] { "capture" }, Effect = CommandEffect.Destructive)] + public static CaptureResult CaptureBuffers( + [CliArg("buffers", "Comma-separated buffers to capture, or 'all' for every buffer. Run 'urp list_buffers' for the list, e.g. color, object_id, depth, albedo, normal.")] string buffers = "color", + [CliArg("view", "Camera to use when 'camera' is not set: 'scene' (last active Scene view) or 'game' (Camera.main).")] View view = View.Game, + [CliArg("camera", "Handle of a Camera or its GameObject (hierarchy path, globalId or instanceId, e.g. from 'gameobject find --type Camera'). Overrides 'view'.")] ObjectRef camera = null, + [CliArg("width", "Output width in pixels. 0 uses the camera's pixel width.")] int width = 0, + [CliArg("height", "Output height in pixels. 0 uses the camera's pixel height.")] int height = 0, + [CliArg("output-dir", "Folder to write .png files to: absolute, or relative to the project root. Defaults to Temp/CaptureBuffer/. Existing files are overwritten. Only files under Assets/ are imported as assets.")] string outputDir = null, + [CliArg("include-inline-image", "Also return each image inline as base64.")] bool includeInlineImage = false) + { + try + { + if (!BufferCapture.isUniversalRenderPipelineActive) + throw new InvalidOperationException("The Universal Render Pipeline is not active."); + BufferCapture.ThrowIfRenderingDebuggerActive(); + + var requested = BufferCapture.ParseTargets(buffers); + var cam = ResolveCamera(view, camera, out var resolvedView); + var skipped = new List(); + var targets = BufferCapture.SelectSupportedTargets(requested, cam, skipped); + var directory = ResolveOutputDirectory(outputDir); + var capture = BufferCapture.Capture(cam, targets, directory, width, height); + if (capture.mapping != null) + File.WriteAllText(capture.mappingPath, JsonConvert.SerializeObject(capture.mapping, Formatting.Indented)); + + var written = capture.images.Select(i => i.path).ToList(); + if (capture.mapping != null) + written.Add(capture.mappingPath); + ImportIfUnderAssets(written); + + return new CaptureResult + { + view = resolvedView, + camera = cam.name, + cameraPath = cam.gameObject.scene.IsValid() ? "/" + BufferCapture.GetHierarchyPath(cam.transform) : null, + outputDir = directory, + images = capture.images.Select(i => new CapturedImage + { + buffer = i.target.name, + savedPath = i.path, + width = i.width, + height = i.height, + base64 = includeInlineImage ? Convert.ToBase64String(i.png) : null, + }).ToArray(), + skipped = skipped.Select(s => new SkippedTarget { buffer = s.target.name, reason = s.reason }).ToArray(), + objectId =capture.mapping == null ? null : new ObjectIdOutput + { + mappingPath = capture.mappingPath, + objectCount = capture.mapping.objects.Length, + }, + }; + } + catch (Exception e) when (!(e is ArgumentException || e is InvalidOperationException)) + { + Debug.LogException(e); + throw; + } + } + + static Camera ResolveCamera(View view, ObjectRef cameraHandle, out string resolvedView) + { + if (cameraHandle != null && !cameraHandle.IsEmpty) + { + resolvedView = "camera"; + if (!ObjectResolver.TryResolve(cameraHandle, out var obj, out var error)) + throw new ArgumentException(error); + + var cam = obj as Camera ?? (obj as GameObject)?.GetComponent(); + if (cam == null) + throw new ArgumentException($"'{obj.name}' is not a Camera or a GameObject with a Camera."); + BufferCapture.ThrowIfOverlayCamera(cam); + return cam; + } + + resolvedView = view.ToString().ToLowerInvariant(); + switch (view) + { + case View.Scene: + return BufferCapture.GetSceneViewCamera(); + case View.Game: + return BufferCapture.GetGameViewCamera(); + default: + throw new ArgumentException($"Invalid view '{view}'. Expected 'scene' or 'game'."); + } + } + + static string projectRoot => Path.GetFullPath(Path.GetDirectoryName(Application.dataPath)); + + static string ResolveOutputDirectory(string outputDir) + { + if (string.IsNullOrWhiteSpace(outputDir)) + { + var stamp = DateTime.Now.ToString("yyyyMMdd_HHmmss_fff", CultureInfo.InvariantCulture); + return Path.Combine(projectRoot, "Temp", "CaptureBuffer", stamp); + } + + return Path.GetFullPath(Path.IsPathRooted(outputDir) ? outputDir : Path.Combine(projectRoot, outputDir)); + } + + // Only files under Assets are assets; anywhere else they stay plain files without a .meta + static void ImportIfUnderAssets(IEnumerable paths) + { + var assets = Path.GetFullPath(Application.dataPath) + Path.DirectorySeparatorChar; + var assetPaths = paths + .Where(p => p.StartsWith(assets, StringComparison.OrdinalIgnoreCase)) + .Select(p => "Assets/" + p.Substring(assets.Length).Replace(Path.DirectorySeparatorChar, '/')) + .ToList(); + if (assetPaths.Count == 0) + return; + + AssetDatabase.StartAssetEditing(); + try + { + foreach (var assetPath in assetPaths) + { + AssetDatabase.ImportAsset(assetPath); + } + } + finally + { + AssetDatabase.StopAssetEditing(); + } + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Editor/CLI/BufferCaptureCLI.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/CLI/BufferCaptureCLI.cs.meta new file mode 100644 index 00000000000..18899a82369 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Editor/CLI/BufferCaptureCLI.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: b9f98d88a35ca6845ac9aa771130b5e6 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Editor/CLI/Unity.RenderPipelines.Universal.Editor.CLI.asmdef b/Packages/com.unity.render-pipelines.universal/Editor/CLI/Unity.RenderPipelines.Universal.Editor.CLI.asmdef new file mode 100644 index 00000000000..6e545ad1dc9 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Editor/CLI/Unity.RenderPipelines.Universal.Editor.CLI.asmdef @@ -0,0 +1,29 @@ +{ + "name": "Unity.RenderPipelines.Universal.Editor.CLI", + "rootNamespace": "UnityEditor.Rendering.Universal.CLI", + "references": [ + "Unity.Pipeline", + "Unity.Pipeline.Attributes", + "Unity.Pipeline.Editor", + "Unity.RenderPipelines.Universal.Editor" + ], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": false, + "defineConstraints": [ + "UNITY_PIPELINE_PACKAGE_AVAILABLE" + ], + "versionDefines": [ + { + "name": "com.unity.pipeline", + "expression": "1.0.0", + "define": "UNITY_PIPELINE_PACKAGE_AVAILABLE" + } + ], + "noEngineReferences": false +} diff --git a/Packages/com.unity.render-pipelines.universal/Editor/CLI/Unity.RenderPipelines.Universal.Editor.CLI.asmdef.meta b/Packages/com.unity.render-pipelines.universal/Editor/CLI/Unity.RenderPipelines.Universal.Editor.CLI.asmdef.meta new file mode 100644 index 00000000000..54c65f3c477 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Editor/CLI/Unity.RenderPipelines.Universal.Editor.CLI.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 15631c8dffe22644c83657a6180c00fe +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Camera/UniversalRenderPipelineCameraEditor.cs b/Packages/com.unity.render-pipelines.universal/Editor/Camera/UniversalRenderPipelineCameraEditor.cs index 62ffeb7d30b..05a6d4146a3 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/Camera/UniversalRenderPipelineCameraEditor.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/Camera/UniversalRenderPipelineCameraEditor.cs @@ -16,6 +16,7 @@ namespace UnityEditor.Rendering.Universal [CustomEditor(typeof(Camera))] [SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))] [CanEditMultipleObjects] + [URPHelpURL("urp/urp-cameras-landing")] class UniversalRenderPipelineCameraEditor : Editor { ReorderableList m_LayerList; diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Camera/UniversalRenderPipelineCameraUI.Drawers.cs b/Packages/com.unity.render-pipelines.universal/Editor/Camera/UniversalRenderPipelineCameraUI.Drawers.cs index 06b3ca6bb21..bd166d4e2f9 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/Camera/UniversalRenderPipelineCameraUI.Drawers.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/Camera/UniversalRenderPipelineCameraUI.Drawers.cs @@ -73,7 +73,7 @@ static void DrawerProjection(UniversalRenderPipelineSerializedCamera p, Editor o bool pixelPerfectEnabled = camera.TryGetComponent(out var pixelPerfectCamera) && pixelPerfectCamera.enabled; if (pixelPerfectEnabled) EditorGUILayout.HelpBox(Styles.pixelPerfectInfo, MessageType.Info); -#if XR_MANAGEMENT_4_0_1_OR_NEWER && ENABLE_VR && ENABLE_XR_MODULE +#if (XR_MANAGEMENT_4_0_1_OR_NEWER || XR_FOUNDATION_7_0_0_OR_NEWER) && ENABLE_VR && ENABLE_XR_MODULE if (p.baseCameraSettings.orthographic.boolValue && p.allowXRRendering.boolValue) { var buildTargetGroup = BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget); diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Camera/UniversalRenderPipelineCameraUI.Skin.cs b/Packages/com.unity.render-pipelines.universal/Editor/Camera/UniversalRenderPipelineCameraUI.Skin.cs index 947f168f9ab..43c11b8b922 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/Camera/UniversalRenderPipelineCameraUI.Skin.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/Camera/UniversalRenderPipelineCameraUI.Skin.cs @@ -7,7 +7,7 @@ static partial class UniversalRenderPipelineCameraUI public class Styles { public static readonly GUIContent cameraType = L10n.TextContent("Render Type", "Defines if a camera renders directly to a target or overlays on top of another camera’s output. Overlay option is not available when Deferred Render Data is in use.", null, null); - public static readonly string pixelPerfectInfo = L10n.Tr("Projection settings have been overriden by the Pixel Perfect Camera.", null); + public static readonly string pixelPerfectInfo = L10n.Tr("Projection settings have been overridden by the Pixel Perfect Camera.", null); // Stack cameras public static readonly GUIContent stackSettingsText = L10n.TextContent("Stack", "The list of overlay cameras assigned to this camera.", null, null); diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Debug/BufferCapture.meta b/Packages/com.unity.render-pipelines.universal/Editor/Debug/BufferCapture.meta new file mode 100644 index 00000000000..9330871a68b --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Editor/Debug/BufferCapture.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 159e272346ea90c4b94bf11b171edae3 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Debug/BufferCapture/BufferCapture.cs b/Packages/com.unity.render-pipelines.universal/Editor/Debug/BufferCapture/BufferCapture.cs new file mode 100644 index 00000000000..ec81b4219f3 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Editor/Debug/BufferCapture/BufferCapture.cs @@ -0,0 +1,685 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEngine; +using UnityEngine.Rendering; +using UnityEngine.Rendering.Universal; +using UnityEngine.SceneManagement; + +namespace UnityEditor.Rendering.Universal +{ + // Renders a camera offscreen and saves rendering buffers as PNGs, so tools such as AI agents can inspect a frame + // without changing what the Editor views display. + static class BufferCapture + { + internal const string allTargets = "all"; + + const int k_SquareTargetSize = 1024; + const int k_FallbackWidth = 1920; + const int k_FallbackHeight = 1080; + const int k_MaxDimension = 8192; + const int k_MaxShaderMessages = 3; + const int k_MaxIdColorRetries = 8; + + internal sealed class Target + { + public string name { get; } + public string description { get; } + + // Full screen debug views fill the output, so atlases get a square output instead of the camera's aspect. + public bool squareOutput { get; } + + // Data views (depth, normals, smoothness, ...) are stored as raw values, not sRGB-encoded. + public bool linearOutput { get; } + + // Configures the pipeline for one render request of the camera; the returned scope restores it. + public Func beginCapture { get; } + + public bool isObjectId { get; } + + readonly Func m_GetUnsupportedReason; + + public Target(string name, string description, bool squareOutput, Func beginCapture, bool isObjectId = false, bool linearOutput = false, Func getUnsupportedReason = null) + { + this.name = name; + this.description = description; + this.squareOutput = squareOutput; + this.linearOutput = linearOutput; + this.beginCapture = beginCapture; + this.isObjectId = isObjectId; + m_GetUnsupportedReason = getUnsupportedReason; + } + + // Why the camera can't produce this target (renderer, shadow settings, ...), or null when it can + public string GetUnsupportedReason(Camera camera) => m_GetUnsupportedReason?.Invoke(camera); + } + + internal readonly struct RequestedTarget + { + public readonly Target target; + + // False when the target only came from 'all' + public readonly bool named; + + public RequestedTarget(Target target, bool named) + { + this.target = target; + this.named = named; + } + } + + internal sealed class SkippedTarget + { + public Target target; + public string reason; + } + + [Serializable] + internal class PixelBounds + { + public int xMin; + public int yMin; + public int xMax; + public int yMax; + } + + [Serializable] + internal class ObjectIdEntry + { + public string color; + public string name; + public string path; + + // Index into ObjectIdMapping.scenes, or -1 when the object is not in a scene + public int scene; + public string type; + public string entityId; + public int pixelCount; + public float coverage; + public PixelBounds bounds; + + // Indices into ObjectIdMapping.materials, one per material slot (-1 for an empty slot) + public int[] materials; + } + + [Serializable] + internal class ShaderMessageInfo + { + public string severity; + public string message; + public string file; + public int line; + } + + [Serializable] + internal class ShaderInfo + { + public string name; + public string path; + public bool hasError; + public bool hasWarnings; + public ShaderMessageInfo[] messages; + } + + [Serializable] + internal class MaterialInfo + { + public string name; + public string path; + public bool hasUnsavedChanges; + + // Index into ObjectIdMapping.shaders, or -1 when the material has no shader + public int shader; + } + + [Serializable] + internal class SceneInfo + { + public string name; + + // Null for a scene that has not been saved + public string path; + } + + [Serializable] + internal class ObjectIdMapping + { + public string camera; + public int width; + public int height; + public string background; + public string boundsOrigin; + public int unresolvedPixelCount; + public SceneInfo[] scenes; + public ShaderInfo[] shaders; + public MaterialInfo[] materials; + public ObjectIdEntry[] objects; + } + + internal sealed class CapturedImage + { + public Target target; + public string path; + public int width; + public int height; + public byte[] png; + } + + internal sealed class CaptureResult + { + public readonly List images = new List(); + + // The caller writes the mapping to mappingPath + public string mappingPath; + public ObjectIdMapping mapping; + } + + internal static bool isUniversalRenderPipelineActive + => GraphicsSettings.currentRenderPipeline is UniversalRenderPipelineAsset; + + internal static List ParseTargets(string targetList) + { + var available = UniversalBufferCaptureTargets.all; + var targets = new List(); + + var names = (string.IsNullOrWhiteSpace(targetList) ? "color" : targetList) + .Split(',') + .Select(n => n.Trim().ToLowerInvariant()) + .Where(n => n.Length > 0); + + foreach (var name in names) + { + if (name == allTargets) + { + targets.AddRange(available.Select(t => new RequestedTarget(t, false))); + continue; + } + + var target = Array.Find(available, t => t.name == name); + if (target == null) + throw new ArgumentException($"Unknown buffer '{name}'. Valid buffers: {allTargets}, {string.Join(", ", available.Select(t => t.name))}."); + + targets.Add(new RequestedTarget(target, true)); + } + + return targets + .GroupBy(t => t.target.name) + .Select(g => new RequestedTarget(g.First().target, g.Any(t => t.named))) + .ToList(); + } + + // Targets that only came from 'all' are skipped when unsupported; a named unsupported target fails the request + internal static List SelectSupportedTargets(IReadOnlyList requested, Camera camera, List skipped) + { + if (!isUniversalRenderPipelineActive) + throw new InvalidOperationException("The Universal Render Pipeline is not active."); + + var targets = new List(); + foreach (var request in requested) + { + var reason = request.target.GetUnsupportedReason(camera); + if (reason == null) + targets.Add(request.target); + else if (request.named) + throw new InvalidOperationException($"Buffer '{request.target.name}' is not supported for camera '{camera.name}': {reason}"); + else + skipped.Add(new SkippedTarget { target = request.target, reason = reason }); + } + + return targets; + } + + // Captures apply their modes on top of the global Rendering Debugger settings, so modes the user enabled would + // leak into them, and hiding debug overlays would turn the capture's own modes off + internal static void ThrowIfRenderingDebuggerActive() + { + const string k_Fix = "Disable them in the Rendering Debugger (Window > Analysis > Rendering Debugger), or reset it, and try again."; + + var settings = UniversalRenderPipelineDebugDisplaySettings.Instance; + if (settings.isHidingDebugOverlays) + throw new InvalidOperationException($"The Rendering Debugger is hiding debug overlays. {k_Fix}"); + + if (!settings.AreAnySettingsActive) + return; + + var active = new List(); + settings.ForEach(data => + { + if (data.AreAnySettingsActive) + active.Add(data.GetType().Name.Replace("DebugDisplaySettings", "")); + }); + throw new InvalidOperationException($"Rendering Debugger settings are active ({string.Join(", ", active)}). {k_Fix}"); + } + + internal static Camera GetSceneViewCamera() + { + var sceneView = SceneView.lastActiveSceneView; + if (sceneView == null || sceneView.camera == null) + throw new InvalidOperationException("No Scene view is open."); + + // WORKAROUND: the Scene view only applies its pivot, rotation and lens to the camera when it repaints + // (SceneView.SetupCamera), so the camera is stale after a domain reload or while the Editor is in the + // background. Force a synchronous repaint first. + EditorWindowBridge.RepaintImmediately(sceneView); + return sceneView.camera; + } + + internal static Camera GetGameViewCamera() + { + var camera = Camera.main; + if (camera == null || IsOverlayCamera(camera)) + camera = Camera.allCameras.FirstOrDefault(c => !IsOverlayCamera(c)); + if (camera == null) + throw new InvalidOperationException("No enabled Base camera in the open scenes."); + return camera; + } + + // URP only renders Overlay cameras as part of a Base camera's stack, so a request for one renders nothing + internal static void ThrowIfOverlayCamera(Camera camera) + { + if (IsOverlayCamera(camera)) + throw new ArgumentException($"'{camera.name}' is an Overlay camera, which only renders as part of a Base camera's stack. Use its Base camera instead."); + } + + static bool IsOverlayCamera(Camera camera) + { + return camera.TryGetComponent(out var data) && + data.renderType == CameraRenderType.Overlay; + } + + internal static CaptureResult Capture(Camera camera, IReadOnlyList targets, string directory, int width, int height) + { + if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null) + throw new InvalidOperationException("No GPU available (batchmode with -nographics); cannot capture."); + + if (!isUniversalRenderPipelineActive) + throw new InvalidOperationException("The Universal Render Pipeline is not active."); + + ThrowIfOverlayCamera(camera); + + Directory.CreateDirectory(directory); + var result = new CaptureResult(); + + // Sized from the camera's on-screen viewport, so this must run before the rect is reset below + var outputSizes = new Vector2Int[targets.Count]; + for (int i = 0; i < targets.Count; ++i) + { + GetOutputSize(camera.pixelWidth, camera.pixelHeight, targets[i].squareOutput, width, height, out var w, out var h); + outputSizes[i] = new Vector2Int(w, h); + } + + // Debug modes use shader variants that may not be compiled yet; a one-off capture can't wait for async compilation + bool oldAsyncCompilation = ShaderUtil.allowAsyncCompilation; + ShaderUtil.allowAsyncCompilation = false; + + // Render requests apply the camera's viewport rect within the output texture, so fill the whole output instead + var prevRect = camera.rect; + camera.rect = new Rect(0, 0, 1, 1); + try + { + for (int i = 0; i < targets.Count; ++i) + { + var target = targets[i]; + int w = outputSizes[i].x; + int h = outputSizes[i].y; + var path = Path.Combine(directory, target.name + ".png"); + + var png = target.isObjectId + ? CaptureObjectId(camera, w, h, path, result) + : CaptureColor(camera, target, w, h, path); + + result.images.Add(new CapturedImage { target = target, path = path, width = w, height = h, png = png }); + } + } + finally + { + camera.rect = prevRect; + ShaderUtil.allowAsyncCompilation = oldAsyncCompilation; + } + + return result; + } + + static byte[] CaptureColor(Camera camera, Target target, int width, int height, string path) + { + var readWrite = target.linearOutput ? RenderTextureReadWrite.Linear : RenderTextureReadWrite.sRGB; + var rt = new RenderTexture(width, height, 24, RenderTextureFormat.ARGB32, readWrite); + var tex = new Texture2D(width, height, TextureFormat.RGBA32, false, target.linearOutput); + try + { + var request = new RenderPipeline.StandardRequest { destination = rt }; + if (!RenderPipeline.SupportsRenderRequest(camera, request)) + throw new InvalidOperationException("The active render pipeline does not support StandardRequest."); + + using (target.beginCapture?.Invoke(camera)) + RenderPipeline.SubmitRenderRequest(camera, request); + + ReadBack(rt, tex); + return WritePng(tex, path); + } + finally + { + UnityEngine.Object.DestroyImmediate(tex); + rt.Release(); + UnityEngine.Object.DestroyImmediate(rt); + } + } + + static byte[] CaptureObjectId(Camera camera, int width, int height, string path, CaptureResult result) + { + var rt = new RenderTexture(width, height, 24, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear); + var idTex = new Texture2D(width, height, TextureFormat.RGBA32, false, true); + var colorTex = new Texture2D(width, height, TextureFormat.RGBA32, false); + var prevTarget = camera.targetTexture; + try + { + var request = new ObjectIdRequest(rt); + + // SupportsRenderRequest creates the pipeline instance, which Camera.SubmitRenderRequest assumes exists + RenderPipeline.SupportsRenderRequest(camera, request); + if (RenderPipelineManager.currentPipeline == null) + throw new InvalidOperationException("The URP render pipeline instance could not be created."); + + // WORKAROUND: ObjectIdRequest ignores its destination size; the picking fallback (FillPickBuffer) derives + // the viewport from the camera's current target, so point the camera at the output while it renders. + camera.targetTexture = rt; + camera.SubmitRenderRequest(request); + camera.targetTexture = prevTarget; + + var idToObject = request.result?.idToObjectMapping; + if (idToObject == null) + throw new InvalidOperationException($"The object id render request for camera '{camera.name}' returned no result."); + + ReadBack(rt, idTex); + var mapping = BuildObjectIdImage(idTex.GetPixels32(), width, height, idToObject, out var colored); + mapping.camera = camera.name; + + colorTex.SetPixels32(colored); + colorTex.Apply(); + var png = WritePng(colorTex, path); + + result.mappingPath = Path.ChangeExtension(path, ".json"); + result.mapping = mapping; + return png; + } + finally + { + camera.targetTexture = prevTarget; + UnityEngine.Object.DestroyImmediate(idTex); + UnityEngine.Object.DestroyImmediate(colorTex); + rt.Release(); + UnityEngine.Object.DestroyImmediate(rt); + } + } + + internal static ObjectIdMapping BuildObjectIdImage(Color32[] ids, int width, int height, UnityEngine.Object[] idToObject, out Color32[] colored) + { + // Picking assigns one id per material slot, so several ids can map to the same object + var entries = new Dictionary(); + var objectColors = new Dictionary(); + var usedColors = new HashSet(); + var materialTable = new MaterialTable(); + var sceneTable = new SceneTable(); + int unresolvedPixelCount = 0; + colored = new Color32[ids.Length]; + + for (int i = 0; i < ids.Length; ++i) + { + int id = ObjectIdResult.DecodeIdFromColor(ids[i]); + if (id == 0) + { + colored[i] = new Color32(0, 0, 0, 255); + continue; + } + + // Indices past the renderer list belong to gizmos or BatchRendererGroup instances + if (id < 0 || id >= idToObject.Length || idToObject[id] == null) + { + unresolvedPixelCount++; + colored[i] = new Color32(255, 255, 255, 255); + continue; + } + + // Texture rows start at the bottom; report bounds with a top-left origin like the PNG + int x = i % width; + int y = height - 1 - i / width; + var obj = idToObject[id]; + if (!entries.TryGetValue(obj, out var entry)) + { + var color = GetUniqueIdColor(id, usedColors); + objectColors.Add(obj, color); + entry = CreateEntry(color, obj, materialTable, sceneTable); + entry.bounds = new PixelBounds { xMin = x, yMin = y, xMax = x, yMax = y }; + entries.Add(obj, entry); + } + + colored[i] = objectColors[obj]; + entry.pixelCount++; + entry.bounds.xMin = Math.Min(entry.bounds.xMin, x); + entry.bounds.yMin = Math.Min(entry.bounds.yMin, y); + entry.bounds.xMax = Math.Max(entry.bounds.xMax, x); + entry.bounds.yMax = Math.Max(entry.bounds.yMax, y); + } + + float pixelTotal = width * height; + foreach (var entry in entries.Values) + entry.coverage = entry.pixelCount / pixelTotal; + + var objects = entries.Values.OrderByDescending(e => e.pixelCount).ToArray(); + return new ObjectIdMapping + { + width = width, + height = height, + background = "#000000", + boundsOrigin = "top-left", + unresolvedPixelCount = unresolvedPixelCount, + scenes = sceneTable.scenes.ToArray(), + shaders = materialTable.shaders.ToArray(), + materials = materialTable.materials.ToArray(), + objects = objects + }; + } + + static ObjectIdEntry CreateEntry(Color32 color, UnityEngine.Object obj, MaterialTable materialTable, SceneTable sceneTable) + { + var go = obj as GameObject ?? (obj as Component)?.gameObject; + return new ObjectIdEntry + { + color = "#" + ColorUtility.ToHtmlStringRGB(color), + name = go != null ? go.name : obj.name, + path = go != null ? GetHierarchyPath(go.transform) : null, + scene = go != null ? sceneTable.GetSceneIndex(go.scene) : -1, + type = obj.GetType().Name, + entityId = obj.GetEntityId().ToString(), + materials = materialTable.GetMaterialIndices(obj), + }; + } + + sealed class SceneTable + { + public readonly List scenes = new List(); + readonly Dictionary m_SceneIndices = new Dictionary(); + + public int GetSceneIndex(Scene scene) + { + if (!scene.IsValid()) + return -1; + + if (m_SceneIndices.TryGetValue(scene, out var index)) + return index; + + index = scenes.Count; + m_SceneIndices.Add(scene, index); + scenes.Add(new SceneInfo + { + name = scene.name, + path = string.IsNullOrEmpty(scene.path) ? null : scene.path, + }); + return index; + } + } + + // Stores each material and shader once, so the mapping stays small when many objects share them + sealed class MaterialTable + { + public readonly List shaders = new List(); + public readonly List materials = new List(); + readonly Dictionary m_ShaderIndices = new Dictionary(); + readonly Dictionary m_MaterialIndices = new Dictionary(); + + public int[] GetMaterialIndices(UnityEngine.Object obj) + { + if (!(obj is Renderer renderer)) + return Array.Empty(); + + var sharedMaterials = renderer.sharedMaterials; + var indices = new int[sharedMaterials.Length]; + for (int i = 0; i < sharedMaterials.Length; ++i) + indices[i] = sharedMaterials[i] != null ? GetMaterialIndex(sharedMaterials[i]) : -1; + return indices; + } + + int GetMaterialIndex(Material material) + { + if (m_MaterialIndices.TryGetValue(material, out var index)) + return index; + + index = materials.Count; + m_MaterialIndices.Add(material, index); + materials.Add(new MaterialInfo + { + name = material.name, + path = GetAssetPath(material), + hasUnsavedChanges = EditorUtility.IsDirty(material), + shader = material.shader != null ? GetShaderIndex(material.shader) : -1, + }); + return index; + } + + int GetShaderIndex(Shader shader) + { + if (m_ShaderIndices.TryGetValue(shader, out var index)) + return index; + + // ShaderHasError fetches the cached compiler messages that GetShaderMessages returns + bool hasError = ShaderUtil.ShaderHasError(shader); + bool hasWarnings = ShaderUtil.ShaderHasWarnings(shader); + + var path = GetAssetPath(shader); + index = shaders.Count; + m_ShaderIndices.Add(shader, index); + shaders.Add(new ShaderInfo + { + name = shader.name, + path = path, + hasError = hasError, + hasWarnings = hasWarnings, + messages = hasError || hasWarnings ? GetMessages(shader, path) : Array.Empty(), + }); + return index; + } + + // Messages repeat per graphics API; keep the first few distinct ones, errors first. + // The compiler leaves file empty for errors in the shader asset itself. + static ShaderMessageInfo[] GetMessages(Shader shader, string shaderPath) + { + return ShaderUtil.GetShaderMessages(shader) + .OrderBy(m => m.severity == ShaderCompilerMessageSeverity.Error ? 0 : 1) + .GroupBy(m => (m.message, m.file, m.line)) + .Select(g => g.First()) + .Take(k_MaxShaderMessages) + .Select(m => new ShaderMessageInfo + { + severity = m.severity.ToString(), + message = m.message, + file = string.IsNullOrEmpty(m.file) ? shaderPath : m.file, + line = m.line, + }) + .ToArray(); + } + + static string GetAssetPath(UnityEngine.Object asset) + { + var path = AssetDatabase.GetAssetPath(asset); + return string.IsNullOrEmpty(path) ? null : path; + } + } + + // Colors of two ids can still match once the retries run out + static Color32 GetUniqueIdColor(int id, HashSet usedColors) + { + Color32 color = default; + for (uint attempt = 0; attempt <= k_MaxIdColorRetries; ++attempt) + { + color = GetIdColor(id, attempt); + if (usedColors.Add(color.r | (color.g << 8) | (color.b << 16))) + break; + } + + return color; + } + + static Color32 GetIdColor(int id, uint attempt) + { + const uint k_GoldenRatioHash = 0x9E3779B9u; + uint hash = ((uint)id + attempt * k_GoldenRatioHash) * k_GoldenRatioHash; + float hue = (hash >> 8) / (float)(1 << 24); + float saturation = Mathf.Lerp(0.6f, 0.95f, (hash & 0xF) / 15f); + float value = Mathf.Lerp(0.7f, 1f, ((hash >> 4) & 0xF) / 15f); + return Color.HSVToRGB(hue, saturation, value); + } + + internal static string GetHierarchyPath(Transform transform) + { + var path = transform.name; + for (var parent = transform.parent; parent != null; parent = parent.parent) + path = parent.name + "/" + path; + return path; + } + + internal static void GetOutputSize(int cameraWidth, int cameraHeight, bool squareOutput, int width, int height, out int w, out int h) + { + if (squareOutput) + { + w = width > 0 ? width : k_SquareTargetSize; + h = height > 0 ? height : w; + } + else + { + w = width > 0 ? width : cameraWidth; + h = height > 0 ? height : cameraHeight; + } + + if (w <= 1 || h <= 1) + { + w = k_FallbackWidth; + h = k_FallbackHeight; + } + + int longestEdge = Mathf.Max(w, h); + if (longestEdge > k_MaxDimension) + { + float scale = (float)k_MaxDimension / longestEdge; + w = Mathf.Max(1, Mathf.RoundToInt(w * scale)); + h = Mathf.Max(1, Mathf.RoundToInt(h * scale)); + } + } + + static void ReadBack(RenderTexture source, Texture2D destination) + { + var prevActive = RenderTexture.active; + RenderTexture.active = source; + destination.ReadPixels(new Rect(0, 0, source.width, source.height), 0, 0); + destination.Apply(); + RenderTexture.active = prevActive; + } + + static byte[] WritePng(Texture2D tex, string path) + { + var png = tex.EncodeToPNG(); + File.WriteAllBytes(path, png); + return png; + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Debug/BufferCapture/BufferCapture.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/Debug/BufferCapture/BufferCapture.cs.meta new file mode 100644 index 00000000000..80748036ec9 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Editor/Debug/BufferCapture/BufferCapture.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 1ba4d54c16eb4154682c2a9df9d76fac \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Debug/BufferCapture/UniversalBufferCaptureTargets.cs b/Packages/com.unity.render-pipelines.universal/Editor/Debug/BufferCapture/UniversalBufferCaptureTargets.cs new file mode 100644 index 00000000000..549203f4ecd --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Editor/Debug/BufferCapture/UniversalBufferCaptureTargets.cs @@ -0,0 +1,190 @@ +using System; +using UnityEngine; +using UnityEngine.Rendering; +using UnityEngine.Rendering.Universal; + +namespace UnityEditor.Rendering.Universal +{ + // The buffers BufferCapture can produce, mostly Rendering Debugger views + static class UniversalBufferCaptureTargets + { + // Renderer2D's sprite shaders output the invalid mode color (red) for the material and lighting modes they + // don't implement, and a constant world space normal. Only UniversalRenderer composites full screen debug modes. + static readonly Type[] k_UniversalRenderer = { typeof(UniversalRenderer) }; + static readonly Type[] k_UniversalAnd2DRenderers = { typeof(UniversalRenderer), typeof(Renderer2D) }; + + static readonly BufferCapture.Target[] k_Targets = + { + Create("color", "Final camera output, with Rendering Debugger modes disabled.", null), + new BufferCapture.Target("object_id", "Each object in a distinct color, with a JSON file mapping colors to GameObjects (uses Scene view picking). Objects rendered by Overlay cameras in the camera's stack are not included.", false, null, isObjectId: true), + Create("depth", "Depth buffer, remapped for display.", k_UniversalRenderer, fullScreenMode: DebugFullScreenMode.Depth, linearOutput: true), + Create("shadow_main", "Main light shadow map atlas.", k_UniversalRenderer, fullScreenMode: DebugFullScreenMode.MainLightShadowMap, squareOutput: true, linearOutput: true, getSceneUnsupportedReason: GetMainLightShadowsUnsupportedReason), + Create("shadow_additional", "Additional lights shadow map atlas.", k_UniversalRenderer, fullScreenMode: DebugFullScreenMode.AdditionalLightsShadowMap, squareOutput: true, linearOutput: true, getSceneUnsupportedReason: GetAdditionalLightShadowsUnsupportedReason), + Create("albedo", "Material albedo.", k_UniversalAnd2DRenderers, materialMode: DebugMaterialMode.Albedo), + Create("specular", "Material specular color.", k_UniversalRenderer, materialMode: DebugMaterialMode.Specular), + Create("alpha", "Material alpha.", k_UniversalAnd2DRenderers, materialMode: DebugMaterialMode.Alpha, linearOutput: true), + Create("smoothness", "Material smoothness.", k_UniversalRenderer, materialMode: DebugMaterialMode.Smoothness, linearOutput: true), + Create("metallic", "Material metallic.", k_UniversalRenderer, materialMode: DebugMaterialMode.Metallic, linearOutput: true), + Create("ambient_occlusion", "Material ambient occlusion.", k_UniversalRenderer, materialMode: DebugMaterialMode.AmbientOcclusion, linearOutput: true), + Create("emission", "Material emission.", k_UniversalRenderer, materialMode: DebugMaterialMode.Emission), + Create("normal", "World space normals.", k_UniversalRenderer, materialMode: DebugMaterialMode.NormalWorldSpace, linearOutput: true), + Create("normal_tangent", "Tangent space normals.", k_UniversalAnd2DRenderers, materialMode: DebugMaterialMode.NormalTangentSpace, linearOutput: true), + Create("lighting_complexity", "Number of lights affecting each pixel.", k_UniversalRenderer, materialMode: DebugMaterialMode.LightingComplexity), + Create("shadow_cascades", "Main light shadow cascades in distinct colors.", k_UniversalRenderer, lightingMode: DebugLightingMode.ShadowCascades), + Create("lighting", "Lighting only, including normal maps.", k_UniversalAnd2DRenderers, lightingMode: DebugLightingMode.LightingWithNormalMaps), + Create("reflections", "Reflections only.", k_UniversalRenderer, lightingMode: DebugLightingMode.Reflections), + Create("global_illumination", "Indirect irradiance.", k_UniversalRenderer, lightingMode: DebugLightingMode.GlobalIllumination), + }; + + internal static BufferCapture.Target[] all => k_Targets; + + static BufferCapture.Target Create( + string name, + string description, + Type[] supportedRenderers, + DebugFullScreenMode fullScreenMode = DebugFullScreenMode.None, + DebugMaterialMode materialMode = DebugMaterialMode.None, + DebugLightingMode lightingMode = DebugLightingMode.None, + bool squareOutput = false, + bool linearOutput = false, + Func getSceneUnsupportedReason = null) + { + return new BufferCapture.Target(name, description, squareOutput, + _ => new DebugDisplayScope(fullScreenMode, materialMode, lightingMode), + linearOutput: linearOutput, + getUnsupportedReason: camera => GetRendererUnsupportedReason(camera, supportedRenderers) ?? + (fullScreenMode != DebugFullScreenMode.None ? GetFullScreenModeUnsupportedReason(camera) : null) ?? + getSceneUnsupportedReason?.Invoke(camera)); + } + + // DebugDisplayScope needs the component to make offscreen cameras composite full screen debug modes + static string GetFullScreenModeUnsupportedReason(Camera camera) + { + // URP takes Scene view post-processing from the view itself, which DebugDisplayScope can't override + if (camera.cameraType == CameraType.SceneView && !CoreUtils.ArePostProcessesEnabled(camera)) + return "Capturing this Rendering Debugger mode from the Scene view requires its Post Processing effect to be enabled and its draw mode not to be Wireframe."; + + if (camera.TryGetComponent(out _)) + return null; + + return $"Camera '{camera.name}' has no Universal Additional Camera Data component, which capturing this Rendering Debugger mode requires."; + } + + static ScriptableRenderer GetRenderer(Camera camera) + { + camera.TryGetComponent(out var additionalCameraData); + return UniversalRenderPipeline.GetRenderer(camera, additionalCameraData); + } + + // A null supportedRenderers means any renderer + static string GetRendererUnsupportedReason(Camera camera, Type[] supportedRenderers) + { + if (supportedRenderers == null) + return null; + + var rendererType = GetRenderer(camera).GetType(); + if (Array.Exists(supportedRenderers, t => t.IsAssignableFrom(rendererType))) + return null; + + return $"The camera uses {rendererType.Name}, which doesn't support this Rendering Debugger mode."; + } + + // Only checks settings. Without a visible shadow casting light, URP gives its empty placeholder shadow map. + static string GetCommonShadowsUnsupportedReason(Camera camera) + { + if (!SystemInfo.supportsShadows) + return "The graphics device doesn't support shadows."; + + camera.TryGetComponent(out var additionalCameraData); + if (camera.cameraType != CameraType.SceneView && additionalCameraData != null && !additionalCameraData.renderShadows) + return $"Render Shadows is disabled on camera '{camera.name}'."; + + if (VolumeManager.instance.isInitialized) + { + float volumeMaxShadowDistance = GetVolumeMaxShadowDistance(camera, additionalCameraData); + if (Mathf.Min(volumeMaxShadowDistance, camera.farClipPlane) < camera.nearClipPlane) + return $"The Shadows volume override's Max Shadow Distance ({volumeMaxShadowDistance}) is shorter than the near clip plane of camera '{camera.name}' ({camera.nearClipPlane})."; + } + + if (CoreUtils.IsSceneLightingDisabled(camera)) + return "Scene lighting is disabled in the Scene view."; + + return null; + } + + // VolumeManager.instance.stack can't be used, it holds the values of the camera that rendered last. + // In Play mode, cameras that update volumes via scripting render with a cached stack, which this ignores. + static float GetVolumeMaxShadowDistance(Camera camera, UniversalAdditionalCameraData additionalCameraData) + { + camera.GetVolumeLayerMaskAndTrigger(additionalCameraData, out LayerMask layerMask, out Transform trigger); + var stack = VolumeManager.instance.CreateStack(); + try + { + VolumeManager.instance.Update(stack, trigger, layerMask); + return UniversalRenderPipeline.GetShadowsVolume(stack).maxShadowDistance.value; + } + finally + { + VolumeManager.instance.DestroyStack(stack); + } + } + + static string GetMainLightShadowsUnsupportedReason(Camera camera) + { + var asset = UniversalRenderPipeline.asset; + if (asset.mainLightRenderingMode != LightRenderingMode.PerPixel) + return "The URP Asset's Main Light rendering mode isn't Per Pixel."; + if (!asset.supportsMainLightShadows) + return "Main light shadows are disabled in the URP Asset."; + + return GetCommonShadowsUnsupportedReason(camera); + } + + static string GetAdditionalLightShadowsUnsupportedReason(Camera camera) + { + var asset = UniversalRenderPipeline.asset; + var renderer = GetRenderer(camera) as UniversalRenderer; + bool isForwardPlus = renderer != null && renderer.renderingModeActual == RenderingMode.ForwardPlus; + var lightsMode = asset.additionalLightsRenderingMode; + if (lightsMode == LightRenderingMode.PerVertex || (lightsMode != LightRenderingMode.PerPixel && !isForwardPlus)) + return "The URP Asset's Additional Lights rendering mode isn't Per Pixel."; + if (!asset.supportsAdditionalLightShadows) + return "Additional light shadows are disabled in the URP Asset."; + + return GetCommonShadowsUnsupportedReason(camera); + } + + // WORKAROUND: URP has no per-request debug settings, so this overrides the global + // Rendering Debugger state around one synchronous render request. Editor views never render a frame with it. + sealed class DebugDisplayScope : IDisposable + { + readonly DebugFullScreenMode m_FullScreenMode; + readonly int m_FullScreenSizePercent; + readonly DebugMaterialMode m_MaterialMode; + readonly DebugLightingMode m_LightingMode; + + public DebugDisplayScope(DebugFullScreenMode fullScreenMode, DebugMaterialMode materialMode, DebugLightingMode lightingMode) + { + var settings = UniversalRenderPipelineDebugDisplaySettings.Instance; + m_FullScreenMode = settings.renderingSettings.fullScreenDebugMode; + m_FullScreenSizePercent = settings.renderingSettings.fullScreenDebugModeOutputSizeScreenPercent; + m_MaterialMode = settings.materialSettings.materialDebugMode; + m_LightingMode = settings.lightingSettings.lightingDebugMode; + + settings.renderingSettings.fullScreenDebugMode = fullScreenMode; + settings.renderingSettings.fullScreenDebugModeOutputSizeScreenPercent = 100; + settings.materialSettings.materialDebugMode = materialMode; + settings.lightingSettings.lightingDebugMode = lightingMode; + } + + public void Dispose() + { + var settings = UniversalRenderPipelineDebugDisplaySettings.Instance; + settings.renderingSettings.fullScreenDebugMode = m_FullScreenMode; + settings.renderingSettings.fullScreenDebugModeOutputSizeScreenPercent = m_FullScreenSizePercent; + settings.materialSettings.materialDebugMode = m_MaterialMode; + settings.lightingSettings.lightingDebugMode = m_LightingMode; + } + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Debug/BufferCapture/UniversalBufferCaptureTargets.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/Debug/BufferCapture/UniversalBufferCaptureTargets.cs.meta new file mode 100644 index 00000000000..d30f47a8f57 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Editor/Debug/BufferCapture/UniversalBufferCaptureTargets.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: b4532bf962a0f7a4d9d5d285b3a43858 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Fog.meta b/Packages/com.unity.render-pipelines.universal/Editor/Fog.meta new file mode 100644 index 00000000000..0cd61cc9dc0 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Editor/Fog.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 275d51228f0d4a6abad47d5978736c87 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Fog/FogVolumeEditor.cs b/Packages/com.unity.render-pipelines.universal/Editor/Fog/FogVolumeEditor.cs new file mode 100644 index 00000000000..6ebbad1b81c --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Editor/Fog/FogVolumeEditor.cs @@ -0,0 +1,97 @@ +#if VOLUMETRIC_FOG + +using UnityEngine; +using UnityEngine.Rendering; +using UnityEngine.Rendering.Universal; + +namespace UnityEditor.Rendering.Universal +{ + [CustomEditor(typeof(FogVolume))] + [CanEditMultipleObjects] + sealed class FogVolumeEditor : Editor + { + static readonly Color k_GizmoColor = new Color(180.0f / 255.0f, 180.0f / 255.0f, 180.0f / 255.0f).gamma; + + static class Styles + { + public static readonly GUIContent densityMode = EditorGUIUtility.TrTextContent("Density Mode", "How fog density is distributed inside the fog volume."); + public static readonly GUIContent density = EditorGUIUtility.TrTextContent("Density", "How thick the fog is inside the fog volume. Higher values reduce visibility."); + public static readonly GUIContent albedo = EditorGUIUtility.TrTextContent("Albedo", "The color of the light that the fog scatters."); + public static readonly GUIContent densityTexture = EditorGUIUtility.TrTextContent("Density Texture", "A 3D texture whose RGB channels tint the albedo and whose alpha channel scales the density. Alpha-only textures only scale the density."); + public static readonly GUIContent densityTextureTiling = EditorGUIUtility.TrTextContent("Tiling", "How many times the density texture repeats across the fog volume along each axis."); + public static readonly GUIContent densityTextureScrollSpeed = EditorGUIUtility.TrTextContent("Scroll Speed", "How fast the density texture moves through the fog volume along each axis, in texture repeats per second."); + public static readonly GUIContent blendMode = EditorGUIUtility.TrTextContent("Blend Mode", "How this fog volume combines with the global fog and overlapping fog volumes."); + public static readonly GUIContent blendPriority = EditorGUIUtility.TrTextContent("Blend Priority", "Overlapping fog volumes blend in order, lowest to highest."); + } + + SerializedProperty m_DensityMode; + SerializedProperty m_Density; + SerializedProperty m_Albedo; + SerializedProperty m_DensityTexture; + SerializedProperty m_DensityTextureTiling; + SerializedProperty m_DensityTextureScrollSpeed; + SerializedProperty m_BlendMode; + SerializedProperty m_BlendPriority; + + void OnEnable() + { + m_DensityMode = serializedObject.FindProperty("m_DensityMode"); + m_Density = serializedObject.FindProperty("m_Density"); + m_Albedo = serializedObject.FindProperty("m_Albedo"); + m_DensityTexture = serializedObject.FindProperty("m_DensityTexture"); + m_DensityTextureTiling = serializedObject.FindProperty("m_DensityTextureTiling"); + m_DensityTextureScrollSpeed = serializedObject.FindProperty("m_DensityTextureScrollSpeed"); + m_BlendMode = serializedObject.FindProperty("m_BlendMode"); + m_BlendPriority = serializedObject.FindProperty("m_BlendPriority"); + } + + public override void OnInspectorGUI() + { + serializedObject.Update(); + + EditorGUILayout.PropertyField(m_DensityMode, Styles.densityMode); + using (new EditorGUI.IndentLevelScope()) + { + EditorGUILayout.PropertyField(m_Density, Styles.density); + EditorGUILayout.PropertyField(m_Albedo, Styles.albedo); + + if (!m_DensityMode.hasMultipleDifferentValues && + m_DensityMode.intValue == (int)FogVolumeDensityMode.Texture) + { + TextureParameterDrawer.TextureField(m_DensityTexture, Styles.densityTexture, TextureDimension.Tex3D); + using (new EditorGUI.IndentLevelScope()) + { + EditorGUILayout.PropertyField(m_DensityTextureTiling, Styles.densityTextureTiling); + EditorGUILayout.PropertyField(m_DensityTextureScrollSpeed, Styles.densityTextureScrollSpeed); + } + } + + EditorGUILayout.PropertyField(m_BlendMode, Styles.blendMode); + using (new EditorGUI.IndentLevelScope()) + { + EditorGUILayout.PropertyField(m_BlendPriority, Styles.blendPriority); + } + } + + serializedObject.ApplyModifiedProperties(); + } + + [MenuItem("GameObject/Rendering/Fog Volume", priority = CoreUtils.Priorities.gameObjectMenuPriority)] + static void CreateFogVolume(MenuCommand menuCommand) + { + var go = CoreEditorUtils.CreateGameObject("Fog Volume", menuCommand.context); + go.AddComponent(); + } + + [DrawGizmo(GizmoType.Selected | GizmoType.Active)] + static void DrawGizmosSelected(FogVolume fogVolume, GizmoType gizmoType) + { + using (new Handles.DrawingScope(k_GizmoColor, fogVolume.transform.localToWorldMatrix)) + { + Handles.DrawWireCube(Vector3.zero, Vector3.one); + } + } + } +} + +#endif diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Fog/FogVolumeEditor.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/Fog/FogVolumeEditor.cs.meta new file mode 100644 index 00000000000..8a8e76f176e --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Editor/Fog/FogVolumeEditor.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f6e25568465c416897b50c8b1267a8d1 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Lighting/LightUnit.meta b/Packages/com.unity.render-pipelines.universal/Editor/Lighting/LightUnit.meta new file mode 100644 index 00000000000..2a0d8ea7596 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Editor/Lighting/LightUnit.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 319cc21180d240dabb78451d43e63929 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Lighting/LightUnit/LightUnitSliderUIDrawer.cs b/Packages/com.unity.render-pipelines.universal/Editor/Lighting/LightUnit/LightUnitSliderUIDrawer.cs new file mode 100644 index 00000000000..d41b7670b2e --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Editor/Lighting/LightUnit/LightUnitSliderUIDrawer.cs @@ -0,0 +1,32 @@ +using UnityEngine; + +namespace UnityEditor.Rendering.Universal +{ + class LightUnitSliderUIDrawer + { + PiecewiseLightUnitSlider m_Slider; + + public LightUnitSliderUIDrawer() + { + // Exposure is in EV100, but we load a separate due to the different icon set. + m_Slider = new PiecewiseLightUnitSlider(LightUnitSliderDescriptors.ExposureDescriptor); + } + + // Need to cache the serialized object on the slider, to add support for the preset selection context menu (need to apply changes to serialized) + public void SetSerializedObject(SerializedObject serializedObject) + { + m_Slider.SetSerializedObject(serializedObject); + } + + public void DrawExposureSlider(SerializedProperty value, Rect rect) + { + using (new EditorGUI.IndentLevelScope(-EditorGUI.indentLevel)) + { + float val = value.floatValue; + m_Slider.Draw(rect, value, ref val); + if (val != value.floatValue) + value.floatValue = val; + } + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Lighting/LightUnit/LightUnitSliderUIDrawer.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/Lighting/LightUnit/LightUnitSliderUIDrawer.cs.meta new file mode 100644 index 00000000000..6a9c49dd54a --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Editor/Lighting/LightUnit/LightUnitSliderUIDrawer.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 32dde5a88731e944a876ee77e2536877 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Lighting/LightUnit/PiecewiseLightUnitSlider.cs b/Packages/com.unity.render-pipelines.universal/Editor/Lighting/LightUnit/PiecewiseLightUnitSlider.cs new file mode 100644 index 00000000000..2bba2da96a0 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Editor/Lighting/LightUnit/PiecewiseLightUnitSlider.cs @@ -0,0 +1,129 @@ +using System.Collections.Generic; +using System.Linq; +using UnityEngine; + +namespace UnityEditor.Rendering.Universal +{ + /// + /// Formats the provided descriptor into a piece-wise linear slider with contextual slider markers, tooltips, and icons. + /// + class PiecewiseLightUnitSlider : LightUnitSlider + { + struct Piece + { + public Vector2 domain; + public Vector2 range; + + public float directM; + public float directB; + public float inverseM; + public float inverseB; + } + + // Piecewise function indexed by value ranges. + private readonly Dictionary m_PiecewiseFunctionMap = new Dictionary(); + + static void ComputeTransformationParameters(float x0, float x1, float y0, float y1, out float m, out float b) + { + m = (y0 - y1) / (x0 - x1); + b = (m * -x0) + y0; + } + + static float DoTransformation(in float x, in float m, in float b) => (m * x) + b; + + // Ensure clamping to (0,1) as sometimes the function evaluates to slightly below 0 (breaking the handle). + static float ValueToSlider(Piece p, float x) => Mathf.Clamp01(DoTransformation(x, p.inverseM, p.inverseB)); + static float SliderToValue(Piece p, float x) => DoTransformation(x, p.directM, p.directB); + + // Ideally we want a continuous, monotonically increasing function, but this is useful as we can easily fit a + // distribution to a set of (huge) value ranges onto a slider. + public PiecewiseLightUnitSlider(LightUnitSliderUIDescriptor descriptor) : base(descriptor) + { + // Sort the ranges into ascending order + var sortedRanges = m_Descriptor.valueRanges.OrderBy(x => x.value.x).ToArray(); + var sliderDistribution = m_Descriptor.sliderDistribution; + + // Compute the transformation for each value range. + for (int i = 0; i < sortedRanges.Length; i++) + { + var r = sortedRanges[i].value; + + var x0 = sliderDistribution[i + 0]; + var x1 = sliderDistribution[i + 1]; + var y0 = r.x; + var y1 = r.y; + + Piece piece; + piece.domain = new Vector2(x0, x1); + piece.range = new Vector2(y0, y1); + + ComputeTransformationParameters(x0, x1, y0, y1, out piece.directM, out piece.directB); + + // Compute the inverse + ComputeTransformationParameters(y0, y1, x0, x1, out piece.inverseM, out piece.inverseB); + + m_PiecewiseFunctionMap.Add(sortedRanges[i].value, piece); + } + } + + protected override float GetPositionOnSlider(float value, Vector2 valueRange) + { + if (!m_PiecewiseFunctionMap.TryGetValue(valueRange, out var piecewise)) + return -1f; + + return ValueToSlider(piecewise, value); + } + + // Search for the corresponding piece-wise function to a value on the domain and update the input piece to it. + // Returns true if search was successful and an update was made, false otherwise. + bool UpdatePiece(ref Piece piece, float x) + { + foreach (var pair in m_PiecewiseFunctionMap) + { + var p = pair.Value; + + if (x >= p.domain.x && x <= p.domain.y) + { + piece = p; + + return true; + } + } + + return false; + } + + void SliderOutOfBounds(Rect rect, ref float value) + { + EditorGUI.BeginChangeCheck(); + var internalValue = GUI.HorizontalSlider(rect, value, 0f, 1f); + if (EditorGUI.EndChangeCheck()) + { + Piece p = new Piece(); + UpdatePiece(ref p, internalValue); + value = SliderToValue(p, internalValue); + } + } + + protected override void DoSlider(Rect rect, ref float value, Vector2 sliderRange, Vector2 valueRange) + { + // Map the internal slider value to the current piecewise function + if (!m_PiecewiseFunctionMap.TryGetValue(valueRange, out var piece)) + { + // Assume that if the piece is not found, that means the unit value is out of bounds. + SliderOutOfBounds(rect, ref value); + return; + } + + // Maintain an internal value to support a single linear continuous function + EditorGUI.BeginChangeCheck(); + var internalValue = GUI.HorizontalSlider(rect, ValueToSlider(piece, value), 0f, 1f); + if (EditorGUI.EndChangeCheck()) + { + // Ensure that the current function piece is being used to transform the value + UpdatePiece(ref piece, internalValue); + value = SliderToValue(piece, internalValue); + } + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Lighting/LightUnit/PiecewiseLightUnitSlider.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/Lighting/LightUnit/PiecewiseLightUnitSlider.cs.meta new file mode 100644 index 00000000000..5eaaafe9b60 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Editor/Lighting/LightUnit/PiecewiseLightUnitSlider.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 54c1e503c971a254f88b8bf54ee0a57d \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Lighting/ShadowCascadeSplitGUI.cs b/Packages/com.unity.render-pipelines.universal/Editor/Lighting/ShadowCascadeSplitGUI.cs new file mode 100644 index 00000000000..d67091d8940 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Editor/Lighting/ShadowCascadeSplitGUI.cs @@ -0,0 +1,128 @@ +using UnityEngine; + +namespace UnityEditor.Rendering.Universal +{ + internal static class ShadowCascadeSplitGUI + { + const float k_SplitBias = 0.001f; + + internal static Vector4 SortSplits(Vector4 splits, int splitCount) + { + Debug.Assert(splitCount >= 0 && splitCount < 4); + + splits[splitCount] = 1f; + for (int i = 0; i < splitCount; ++i) + splits[i] = Mathf.Max(splits[i], i == 0 ? 0f : splits[i - 1] + k_SplitBias); + for (int i = splitCount - 1; i >= 0; --i) + splits[i] = Mathf.Min(splits[i], splits[i + 1] - k_SplitBias); + + return splits; + } + + internal static float SplitScale(bool useMetric, float maxDistance) + { + return useMetric ? maxDistance : 100f; + } + + internal static float SplitFromSliderValue(float scaledValue, Vector4 splits, int index, int splitCount, float scale) + { + float minimum = index == 0 ? 0f : splits[index - 1] + k_SplitBias; + float maximum = index == splitCount - 1 ? 1f : splits[index + 1] - k_SplitBias; + float invScale = scale == 0f ? 0f : 1f / scale; + return Mathf.Clamp(scaledValue * invScale, minimum, maximum); + } + + internal static float LastBorderScale(Vector4 splits, int splitCount, bool useMetric, float maxDistance) + { + if (!useMetric) + return 100f; + + return splitCount == 0 ? maxDistance : (1f - splits[splitCount - 1]) * maxDistance; + } + + internal static float LastBorderFromSliderValue(float scaledValue, float scale) + { + return scale == 0f ? 0f : scaledValue / scale; + } + + internal static ShadowCascadeGUI.Cascade[] ToCascades(Vector4 splits, float border, int cascadeCount, bool[] splitHandlesEnabled, bool borderHandleEnabled) + { + var cascades = new ShadowCascadeGUI.Cascade[cascadeCount]; + + float previousSplit = 0f; + for (int i = 0; i < cascadeCount - 1; ++i) + { + cascades[i] = new ShadowCascadeGUI.Cascade() + { + size = splits[i] - previousSplit, + borderSize = 0f, + cascadeHandleState = splitHandlesEnabled[i] ? ShadowCascadeGUI.HandleState.Enabled : ShadowCascadeGUI.HandleState.Disabled, + borderHandleState = ShadowCascadeGUI.HandleState.Hidden, + }; + previousSplit = splits[i]; + } + + cascades[cascadeCount - 1] = new ShadowCascadeGUI.Cascade() + { + size = 1f - previousSplit, + borderSize = border, + cascadeHandleState = ShadowCascadeGUI.HandleState.Hidden, + borderHandleState = borderHandleEnabled ? ShadowCascadeGUI.HandleState.Enabled : ShadowCascadeGUI.HandleState.Disabled, + }; + + return cascades; + } + + internal static void FromCascades(ShadowCascadeGUI.Cascade[] cascades, ref Vector4 splits, out float border) + { + int lastCascade = cascades.Length - 1; + + float split = 0f; + for (int i = 0; i < lastCascade; ++i) + { + split += cascades[i].size; + splits[i] = split; + } + border = cascades[lastCascade].borderSize; + } + + internal static bool SplitSlider(Rect rect, GUIContent label, ref Vector4 splits, int index, int splitCount, bool useMetric, float maxDistance) + { + float scale = SplitScale(useMetric, maxDistance); + + EditorGUI.BeginChangeCheck(); + float scaledValue = EditorGUI.Slider(rect, label, splits[index] * scale, 0f, scale); + if (!EditorGUI.EndChangeCheck()) + return false; + + splits[index] = SplitFromSliderValue(scaledValue, splits, index, splitCount, scale); + return true; + } + + internal static bool LastBorderSlider(Rect rect, GUIContent label, ref float border, Vector4 splits, int splitCount, bool useMetric, float maxDistance) + { + float scale = LastBorderScale(splits, splitCount, useMetric, maxDistance); + + EditorGUI.BeginChangeCheck(); + float scaledValue = EditorGUI.Slider(rect, label, border * scale, 0f, scale); + if (!EditorGUI.EndChangeCheck()) + return false; + + border = LastBorderFromSliderValue(scaledValue, scale); + return true; + } + + internal static bool DrawCascades(ref Vector4 splits, ref float border, int cascadeCount, bool useMetric, float maxDistance, bool[] splitHandlesEnabled, bool borderHandleEnabled) + { + var cascades = ToCascades(splits, border, cascadeCount, splitHandlesEnabled, borderHandleEnabled); + + EditorGUI.BeginChangeCheck(); + ShadowCascadeGUI.DrawCascades(ref cascades, useMetric, maxDistance); + if (!EditorGUI.EndChangeCheck()) + return false; + + FromCascades(cascades, ref splits, out border); + return true; + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Lighting/ShadowCascadeSplitGUI.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/Lighting/ShadowCascadeSplitGUI.cs.meta new file mode 100644 index 00000000000..1cbc7ae3a4c --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Editor/Lighting/ShadowCascadeSplitGUI.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c1d9d97974e34555b09c911c1834603c diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Lighting/UniversalRenderPipelineLightUI.Drawers.cs b/Packages/com.unity.render-pipelines.universal/Editor/Lighting/UniversalRenderPipelineLightUI.Drawers.cs index ae2404efc35..2e49d3e3ea9 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/Lighting/UniversalRenderPipelineLightUI.Drawers.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/Lighting/UniversalRenderPipelineLightUI.Drawers.cs @@ -2,10 +2,11 @@ using System.Linq; using System.Linq.Expressions; using System.Reflection; +using UnityEditor.Inspector.GraphicsSettingsInspectors; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Rendering.Universal; -#if XR_MANAGEMENT_4_0_1_OR_NEWER +#if XR_MANAGEMENT_4_0_1_OR_NEWER || XR_FOUNDATION_7_0_0_OR_NEWER using UnityEditor.XR.Management; #endif @@ -171,6 +172,10 @@ static void DrawGeneralContentInternal(UniversalRenderPipelineSerializedLight se { s_SetGizmosDirty(); serializedLight.settings.lightType.intValue = type; + // Validate and reset light unit when light type changes + UpdateLightIntensityUnit(serializedLight, owner); + // Apply changes immediately so the Light component is updated before DrawIntensity + serializedLight.Apply(); } EditorGUI.EndProperty(); @@ -248,7 +253,19 @@ static void DrawAreaShapeContent(UniversalRenderPipelineSerializedLight serializ static void DrawEmissionContent(UniversalRenderPipelineSerializedLight serializedLight, Editor owner) { - serializedLight.settings.DrawIntensity(); + if (serializedLight.settings.lightType.hasMultipleDifferentValues || + serializedLight.settings.lightUnit.hasMultipleDifferentValues) + { + DrawMixedLightIntensity(serializedLight); + } + else + { + LightUI.DrawIntensity(serializedLight, owner); + LightUI.DrawIntensityModifiers(serializedLight); + } + + DrawHighIntensityWithoutExposureWarning(serializedLight); + serializedLight.settings.DrawBounceIntensity(); if (!serializedLight.settings.lightType.hasMultipleDifferentValues) @@ -267,6 +284,90 @@ static void DrawEmissionContent(UniversalRenderPipelineSerializedLight serialize DrawLightCookieContent(serializedLight, owner); } + // LightUI.DrawIntensity converts with the first selected light, so convert per light when types or units differ. + static void DrawMixedLightIntensity(UniversalRenderPipelineSerializedLight serializedLight) + { + const int k_ValueUnitSeparator = 2; + const int k_UnitWidth = 100; + + var lights = serializedLight.serializedObject.targetObjects.OfType().ToArray(); + bool unitIsMixed = serializedLight.settings.lightUnit.hasMultipleDifferentValues; + LightUnit unit = serializedLight.settings.lightUnit.GetEnumValue(); + + Rect rect = EditorGUILayout.GetControlRect(); + Rect unitRect = rect; + unitRect.xMin = rect.xMax - k_UnitWidth; + Rect valueRect = rect; + valueRect.xMax = unitRect.xMin - k_ValueUnitSeparator; + + // Converting to a unit a light type doesn't support throws, so only convert when every light supports it. + bool canConvert = !unitIsMixed && lights.All(light => LightUnitUtils.IsLightUnitSupported(light.type, unit)); + var values = canConvert + ? lights.Select(light => LightUnitUtils.ConvertIntensity(light, light.intensity, LightUnitUtils.GetNativeLightUnit(light.type), unit)).ToArray() + : new[] { 0f }; + + var label = EditorGUI.BeginProperty(valueRect, LightUI.Styles.lightIntensity, serializedLight.settings.intensity); + using (new EditorGUI.DisabledScope(!canConvert)) + { + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = !canConvert || values.Any(value => !Mathf.Approximately(value, values[0])); + float newValue = EditorGUI.FloatField(valueRect, label, values[0]); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + serializedLight.Apply(); + foreach (var light in lights) + { + using (var lightObject = new SerializedObject(light)) + { + LightUnit nativeUnit = LightUnitUtils.GetNativeLightUnit(light.type); + lightObject.FindProperty("m_Intensity").floatValue = + Mathf.Max(0f, LightUnitUtils.ConvertIntensity(light, newValue, unit, nativeUnit)); + lightObject.ApplyModifiedProperties(); + } + } + serializedLight.Update(); + } + } + EditorGUI.EndProperty(); + + // Only offer units that every selected light type supports. + EditorGUI.BeginProperty(unitRect, GUIContent.none, serializedLight.settings.lightUnit); + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = unitIsMixed; + var newUnit = (LightUnit)EditorGUI.EnumPopup(unitRect, GUIContent.none, unit, + candidate => lights.All(light => LightUnitUtils.IsLightUnitSupported(light.type, (LightUnit)candidate))); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + serializedLight.settings.lightUnit.SetEnumValue(newUnit); + EditorGUI.EndProperty(); + } + + // Warn the user when a light is too bright to display correctly because exposure is disabled. + static void DrawHighIntensityWithoutExposureWarning(UniversalRenderPipelineSerializedLight serializedLight) + { + // Roughly the brightest value URP's default colour format can store. + const float k_MaxUnexposedIntensity = 65000f; + + var intensity = serializedLight.settings.intensity; + if (intensity.hasMultipleDifferentValues) + return; + + // light.color is LDR, so intensity alone is a conservative upper bound on what reaches the shader. + if (intensity.floatValue <= k_MaxUnexposedIntensity) + return; + + if (GraphicsSettings.TryGetRenderPipelineSettings(out var exposureSetting) + && exposureSetting.UseExposure) + return; + + CoreEditorUtils.DrawFixMeBox(Styles.HighIntensityNoExposure, "Open", () => + { + GraphicsSettingsInspectorUtility.OpenAndScrollTo( + nameof(URPExposureSettings.UseExposure)); + }); + } + #if VOLUMETRIC_FOG static void DrawVolumetricsContent(UniversalRenderPipelineSerializedLight serializedLight, Editor owner) { @@ -308,6 +409,123 @@ static void DrawRenderingContent(UniversalRenderPipelineSerializedLight serializ } } + static void DrawPCSSContent(UniversalRenderPipelineSerializedLight serializedLight) + { + Light light = serializedLight.settings.light; + UniversalRenderPipelineAsset asset = UniversalRenderPipeline.asset; + if (!ShadowUtils.IsPCSSAvailableForLight(light, asset)) + return; + + bool isDirectional = light.type == LightType.Directional; + bool isPunctual = light.type == LightType.Spot || light.type == LightType.Point; + if (!isDirectional && !isPunctual) + return; + + EditorGUILayout.LabelField(Styles.PCSSHeader, EditorStyles.boldLabel); + using (new EditorGUI.IndentLevelScope()) + { + bool enabledInAsset = isDirectional ? asset.mainLightShadowsPCSS : asset.additionalLightShadowsPCSS; + if (!enabledInAsset) + { + // The asset lists the toggle only at High quality, so below it the quality is what to change first + bool isToggleListed = asset.softShadowQuality >= SoftShadowQuality.High; + GUIContent toggle = isDirectional ? UniversalRenderPipelineAssetUI.Styles.mainLightShadowsPCSS : UniversalRenderPipelineAssetUI.Styles.additionalLightShadowsPCSS; + GUIContent message = isToggleListed ? Styles.PCSSNotEnabledInAsset : Styles.PCSSNotListedBelowHighQuality; + string propertyPath = isToggleListed ? (isDirectional ? "m_MainLightShadowsPCSS" : "m_AdditionalLightShadowsPCSS") : "m_SoftShadowQuality"; + EditorUtils.QualitySettingsHelpBox(string.Format(message.text, toggle.text), MessageType.Info, UniversalRenderPipelineAssetUI.Expandable.Shadows, propertyPath); + } + else if (!UniversalRenderPipelineAssetUI.ValidateGraphicsAPIsForPCSS(out var unsupportedGraphicsApisMessage)) + { + EditorGUILayout.HelpBox(UniversalRenderPipelineAssetUI.Styles.pcssUnsupportedMessage.text + unsupportedGraphicsApisMessage, MessageType.Info); + } + + using (new EditorGUI.DisabledScope(!enabledInAsset)) + { + if (isDirectional) + { + EditorGUILayout.PropertyField(serializedLight.softShadowAngularDiameterProp, Styles.PCSSAngularDiameter); + EditorGUILayout.PropertyField(serializedLight.softShadowScaleProp, Styles.PCSSSoftnessScale); + EditorGUILayout.PropertyField(serializedLight.softShadowMinFilterSizeTexelsProp, Styles.PCSSMinFilterSizeTexels); + DrawPCSSSampleQuality(serializedLight); + if (IsPCSSCustomSelected(serializedLight)) + { + using (new EditorGUI.IndentLevelScope()) + { + EditorGUILayout.PropertyField(serializedLight.softShadowBlockerSampleCountProp, Styles.PCSSBlockerSampleCount); + EditorGUILayout.PropertyField(serializedLight.softShadowFilterSampleCountProp, Styles.PCSSFilterSampleCount); + EditorGUILayout.PropertyField(serializedLight.softShadowMaxPenumbraSizeProp, Styles.PCSSMaxPenumbraSize); + EditorGUILayout.PropertyField(serializedLight.softShadowMaxSamplingDistanceProp, Styles.PCSSMaxSamplingDistance); + EditorGUILayout.PropertyField(serializedLight.softShadowMinFilterMaxAngularDiameterProp, Styles.PCSSMinFilterMaxAngularDiameter); + EditorGUILayout.PropertyField(serializedLight.softShadowBlockerSearchAngularDiameterProp, Styles.PCSSBlockerSearchAngularDiameter); + EditorGUILayout.PropertyField(serializedLight.softShadowBlockerSamplingClumpExponentProp, Styles.PCSSBlockerSamplingClumpExponent); + } + } + } + else + { + // Baked and mixed lights already draw the shape radius above + if (!serializedLight.settings.isBakedOrMixed) + serializedLight.settings.DrawShapeRadius(); + EditorGUILayout.PropertyField(serializedLight.softShadowScaleProp, Styles.PCSSSoftnessScale); + EditorGUILayout.PropertyField(serializedLight.softShadowMinFilterSizeProp, Styles.PCSSMinFilterSize); + DrawPCSSSampleQuality(serializedLight); + if (IsPCSSCustomSelected(serializedLight)) + { + using (new EditorGUI.IndentLevelScope()) + { + EditorGUILayout.PropertyField(serializedLight.softShadowBlockerSampleCountProp, Styles.PCSSBlockerSampleCount); + EditorGUILayout.PropertyField(serializedLight.softShadowFilterSampleCountProp, Styles.PCSSFilterSampleCount); + } + } + } + } + } + } + + static void DrawPCSSSampleQuality(UniversalRenderPipelineSerializedLight serializedLight) + { + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(serializedLight.softShadowPCSSSampleQualityProp, Styles.PCSSSampleQuality); + if (!EditorGUI.EndChangeCheck() || !IsPCSSCustomSelected(serializedLight)) + return; + + UniversalAdditionalLightData[] lightsAdditionalData = serializedLight.lightsAdditionalData; + var presets = new PCSSSampleQuality[lightsAdditionalData.Length]; + for (int i = 0; i < lightsAdditionalData.Length; ++i) + { + presets[i] = lightsAdditionalData[i].softShadowPCSSSampleQuality; + } + + // Apply the serialized copy first, or its stale values would overwrite the direct writes below + serializedLight.serializedAdditionalDataObject.ApplyModifiedProperties(); + + Undo.RecordObjects(lightsAdditionalData, "Set PCSS Samples to Custom"); + for (int i = 0; i < lightsAdditionalData.Length; ++i) + { + if (presets[i] == PCSSSampleQuality.Custom) + continue; + + UniversalAdditionalLightData additionalLightData = lightsAdditionalData[i]; + ShadowUtils.GetPCSSPresetSampleCounts(presets[i], out int blockerSampleCount, out int filterSampleCount); + additionalLightData.softShadowBlockerSampleCount = blockerSampleCount; + additionalLightData.softShadowFilterSampleCount = filterSampleCount; + additionalLightData.softShadowMaxPenumbraSize = UniversalAdditionalLightData.k_DefaultSoftShadowMaxPenumbraSize; + additionalLightData.softShadowMaxSamplingDistance = UniversalAdditionalLightData.k_DefaultSoftShadowMaxSamplingDistance; + additionalLightData.softShadowMinFilterMaxAngularDiameter = UniversalAdditionalLightData.k_DefaultSoftShadowMinFilterMaxAngularDiameter; + additionalLightData.softShadowBlockerSearchAngularDiameter = UniversalAdditionalLightData.k_DefaultSoftShadowBlockerSearchAngularDiameter; + additionalLightData.softShadowBlockerSamplingClumpExponent = UniversalAdditionalLightData.k_DefaultSoftShadowBlockerSamplingClumpExponent; + PrefabUtility.RecordPrefabInstancePropertyModifications(additionalLightData); + } + + serializedLight.serializedAdditionalDataObject.Update(); + } + + static bool IsPCSSCustomSelected(UniversalRenderPipelineSerializedLight serializedLight) + { + SerializedProperty qualityProp = serializedLight.softShadowPCSSSampleQualityProp; + return !qualityProp.hasMultipleDifferentValues && qualityProp.intValue == (int)PCSSSampleQuality.Custom; + } + static void DrawShadowsContent(UniversalRenderPipelineSerializedLight serializedLight, Editor owner) { if (serializedLight.settings.lightType.hasMultipleDifferentValues) @@ -364,7 +582,7 @@ static void DrawShadowsContent(UniversalRenderPipelineSerializedLight serialized float nearPlaneMinBound = Mathf.Min(0.01f * serializedLight.settings.range.floatValue, 0.1f); EditorGUILayout.Slider(serializedLight.settings.shadowsNearPlane, nearPlaneMinBound, 10.0f, Styles.ShadowNearPlane); var isQuest = false; -#if XR_MANAGEMENT_4_0_1_OR_NEWER +#if XR_MANAGEMENT_4_0_1_OR_NEWER || XR_FOUNDATION_7_0_0_OR_NEWER var buildTargetGroup = BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget); var buildTargetSettings = XRGeneralSettingsPerBuildTarget.XRGeneralSettingsForBuildTarget(buildTargetGroup); if (buildTargetSettings != null && buildTargetSettings.Manager != null && buildTargetSettings.Manager.activeLoaders.Count > 0) @@ -377,6 +595,8 @@ static void DrawShadowsContent(UniversalRenderPipelineSerializedLight serialized if (serializedLight.settings.light.shadows == LightShadows.Soft) EditorGUILayout.PropertyField(serializedLight.softShadowQualityProp, Styles.SoftShadowQuality); + DrawPCSSContent(serializedLight); + if (isQuest) { EditorGUILayout.HelpBox( @@ -518,5 +738,31 @@ static void DrawLightCookieContent(UniversalRenderPipelineSerializedLight serial } } } + + /// + /// Validates that the current light unit is supported by the light type. + /// If not supported, resets to the native unit for that light type. + /// This prevents invalid unit states when switching between light types. + /// + static void UpdateLightIntensityUnit(UniversalRenderPipelineSerializedLight serializedLight, Editor owner) + { + LightType lightType = serializedLight.settings.lightType.GetEnumValue(); + LightUnit currentUnit = serializedLight.settings.lightUnit.GetEnumValue(); + + // Check if current unit is supported by new light type + if (!LightUnitUtils.IsLightUnitSupported(lightType, currentUnit)) + { + // Reset to native unit for this light type + LightUnit nativeUnit = LightUnitUtils.GetNativeLightUnit(lightType); + serializedLight.settings.lightUnit.SetEnumValue(nativeUnit); + + // For directional lights, reset luxAtDistance to neutral value + // This ensures the first display value is correct + if (lightType == LightType.Directional) + { + serializedLight.settings.luxAtDistance.floatValue = 1.0f; + } + } + } } } diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Lighting/UniversalRenderPipelineLightUI.Skin.cs b/Packages/com.unity.render-pipelines.universal/Editor/Lighting/UniversalRenderPipelineLightUI.Skin.cs index 6ecbd0885de..d604e738c64 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/Lighting/UniversalRenderPipelineLightUI.Skin.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/Lighting/UniversalRenderPipelineLightUI.Skin.cs @@ -52,6 +52,25 @@ internal static class Styles public static GUIContent SoftShadowQuality = L10n.TextContent("Soft Shadows Quality", "Controls the filtering quality of soft shadows. Higher quality has lower performance.", null, null); + // PCSS + public static GUIContent PCSSHeader = L10n.TextContent("Soft Shadows", "Settings for Percentage-Closer Soft Shadows (PCSS), which widen the penumbra with the distance between the caster and the receiver. These settings apply when PCSS is enabled in the URP Asset and the resolved soft shadow quality is High.", null, null); + public static GUIContent PCSSAngularDiameter = L10n.TextContent("Angular Diameter", "Controls the angular diameter of the light in degrees, which sets how wide the PCSS penumbra grows with distance. The sun is roughly 0.5 degrees.", null, null); + public static GUIContent PCSSSoftnessScale = L10n.TextContent("Softness Scale", "Controls the multiplier applied to the PCSS penumbra size, so shadows can be softened without changing the size of the light.", null, null); + public static GUIContent PCSSSampleQuality = L10n.TextContent("PCSS Samples", "Controls how many shadow map samples PCSS takes per pixel. Higher quality reduces noise but has lower performance. Lower settings rely on temporal anti-aliasing to hide noise. Select Custom to set the sample counts and tuning values yourself.", null, null); + public static GUIContent PCSSBlockerSampleCount = L10n.TextContent("Blocker Sample Count", "Controls the number of samples the PCSS blocker search takes. Higher values reduce noise but have lower performance.", null, null); + public static GUIContent PCSSFilterSampleCount = L10n.TextContent("Filter Sample Count", "Controls the number of samples the PCSS filtering phase takes. Higher values reduce noise but have lower performance.", null, null); + public static GUIContent PCSSMaxPenumbraSize = L10n.TextContent("Max Penumbra Size", "Controls the world-space upper bound on the PCSS penumbra size. This acts as a safety clamp.", null, null); + public static GUIContent PCSSMaxSamplingDistance = L10n.TextContent("Max Sampling Distance", "Controls the world-space distance, at most, that PCSS moves the depth each sample compares against towards the light. This does not move the samples across the shadow map. Useful for reducing light bleeding.", null, null); + public static GUIContent PCSSMinFilterSizeTexels = L10n.TextContent("Min Filter Size (Texels)", "Controls the smallest PCSS filter radius in shadow map texels. Useful for hiding flickering at shadow contact points.", null, null); + public static GUIContent PCSSMinFilterSize = L10n.TextContent("Min Filter Size", "Controls the smallest PCSS filter radius. The range 0 to 1 maps to 0 to about 4 shadow map texels. Useful for hiding flickering at shadow contact points.", null, null); + public static GUIContent PCSSMinFilterMaxAngularDiameter = L10n.TextContent("Min Filter Max Angle", "Controls the angle in degrees the minimum PCSS filter cone widens to. Values below Blocker Search Angle, or below Angular Diameter multiplied by Softness Scale, are raised to the larger of the two.", null, null); + public static GUIContent PCSSBlockerSearchAngularDiameter = L10n.TextContent("Blocker Search Angle", "Controls the angle in degrees of the PCSS blocker search cone. Wider angles reduce light bleeding. Values below Angular Diameter multiplied by Softness Scale are raised to it.", null, null); + public static GUIContent PCSSBlockerSamplingClumpExponent = L10n.TextContent("Blocker Clumping", "Controls how strongly the PCSS blocker search samples clump towards the center of the search cone.", null, null); + + // {0} is the URP Asset toggle label + public static GUIContent PCSSNotEnabledInAsset = L10n.TextContent("These parameters only take effect once {0} is enabled in the Shadows section of the active URP Asset.", null, null, null); + public static GUIContent PCSSNotListedBelowHighQuality = L10n.TextContent("These parameters only take effect once {0} is enabled in the Shadows section of the active URP Asset, which lists it once Soft Shadows Quality there is set to High.", null, null, null); + // Bias (default or custom) public static GUIContent shadowBias = L10n.TextContent("Bias", "Select if the Bias should use the settings from the Pipeline Asset or Custom settings.", null, null); public static int[] optionDefaultValues = { 0, 1 }; @@ -76,6 +95,7 @@ internal static class Styles /// Title with "Rendering Layer" public static readonly GUIContent RenderingLayers = L10n.TextContent("Rendering Layers", "Select the Rendering Layers that the Light affects. This Light affects objects where at least one Rendering Layer value matches.", null, null); public static readonly GUIContent RenderingLayersHelpBox = L10n.TextContentWithIcon("Rendering Layers are disabled by default because they have a small GPU performance cost. Enable them in the active Universal Render Pipeline Asset, under Lighting -> Use Rendering Layers.", MessageType.Info, null); + public static readonly GUIContent HighIntensityNoExposure = L10n.TextContentWithIcon("This intensity is too high to display without exposure. Values above ~65,000 overflow URP's colour target. Enable Use Exposure and set an Exposure override to work with physical light units.", MessageType.Warning, null); } } } diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Lighting/UniversalRenderPipelineSerializedLight.cs b/Packages/com.unity.render-pipelines.universal/Editor/Lighting/UniversalRenderPipelineSerializedLight.cs index fb24283b12e..3bf86fd303b 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/Lighting/UniversalRenderPipelineSerializedLight.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/Lighting/UniversalRenderPipelineSerializedLight.cs @@ -21,6 +21,20 @@ internal class UniversalRenderPipelineSerializedLight : ISerializedLight public SerializedProperty useAdditionalDataProp { get; } // Does light use shadow bias settings defined in UniversalRP asset file? public SerializedProperty additionalLightsShadowResolutionTierProp { get; } // Index of the AdditionalLights ShadowResolution Tier public SerializedProperty softShadowQualityProp { get; } // Per light soft shadow filtering quality. + + // PCSS. The scale and sample counts apply to every light, Min Filter Size to spot and point lights, and the rest to the main directional light. + public SerializedProperty softShadowAngularDiameterProp { get; } + public SerializedProperty softShadowScaleProp { get; } + public SerializedProperty softShadowPCSSSampleQualityProp { get; } + public SerializedProperty softShadowBlockerSampleCountProp { get; } + public SerializedProperty softShadowFilterSampleCountProp { get; } + public SerializedProperty softShadowMaxPenumbraSizeProp { get; } + public SerializedProperty softShadowMaxSamplingDistanceProp { get; } + public SerializedProperty softShadowMinFilterSizeTexelsProp { get; } + public SerializedProperty softShadowMinFilterMaxAngularDiameterProp { get; } + public SerializedProperty softShadowBlockerSearchAngularDiameterProp { get; } + public SerializedProperty softShadowBlockerSamplingClumpExponentProp { get; } + public SerializedProperty softShadowMinFilterSizeProp { get; } public SerializedProperty lightCookieSizeProp { get; } // Multi dimensional light cookie size replacing `cookieSize` in legacy light. public SerializedProperty lightCookieOffsetProp { get; } // Multi dimensional light cookie offset. #if VOLUMETRIC_FOG @@ -69,6 +83,18 @@ public UniversalRenderPipelineSerializedLight(SerializedObject serializedObject, useAdditionalDataProp = serializedAdditionalDataObject.FindProperty("m_UsePipelineSettings"); additionalLightsShadowResolutionTierProp = serializedAdditionalDataObject.FindProperty("m_AdditionalLightsShadowResolutionTier"); softShadowQualityProp = serializedAdditionalDataObject.FindProperty("m_SoftShadowQuality"); + softShadowAngularDiameterProp = serializedAdditionalDataObject.FindProperty("m_SoftShadowAngularDiameter"); + softShadowScaleProp = serializedAdditionalDataObject.FindProperty("m_SoftShadowScale"); + softShadowPCSSSampleQualityProp = serializedAdditionalDataObject.FindProperty("m_SoftShadowPCSSSampleQuality"); + softShadowBlockerSampleCountProp = serializedAdditionalDataObject.FindProperty("m_SoftShadowBlockerSampleCount"); + softShadowFilterSampleCountProp = serializedAdditionalDataObject.FindProperty("m_SoftShadowFilterSampleCount"); + softShadowMaxPenumbraSizeProp = serializedAdditionalDataObject.FindProperty("m_SoftShadowMaxPenumbraSize"); + softShadowMaxSamplingDistanceProp = serializedAdditionalDataObject.FindProperty("m_SoftShadowMaxSamplingDistance"); + softShadowMinFilterSizeTexelsProp = serializedAdditionalDataObject.FindProperty("m_SoftShadowMinFilterSizeTexels"); + softShadowMinFilterMaxAngularDiameterProp = serializedAdditionalDataObject.FindProperty("m_SoftShadowMinFilterMaxAngularDiameter"); + softShadowBlockerSearchAngularDiameterProp = serializedAdditionalDataObject.FindProperty("m_SoftShadowBlockerSearchAngularDiameter"); + softShadowBlockerSamplingClumpExponentProp = serializedAdditionalDataObject.FindProperty("m_SoftShadowBlockerSamplingClumpExponent"); + softShadowMinFilterSizeProp = serializedAdditionalDataObject.FindProperty("m_SoftShadowMinFilterSize"); lightCookieSizeProp = serializedAdditionalDataObject.FindProperty("m_LightCookieSize"); lightCookieOffsetProp = serializedAdditionalDataObject.FindProperty("m_LightCookieOffset"); #if VOLUMETRIC_FOG diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Overrides/ExposureVolumeEditor.cs b/Packages/com.unity.render-pipelines.universal/Editor/Overrides/ExposureVolumeEditor.cs index 3af01ce2f61..fadf282ebff 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/Overrides/ExposureVolumeEditor.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/Overrides/ExposureVolumeEditor.cs @@ -10,14 +10,18 @@ namespace UnityEditor.Rendering.Universal sealed class ExposureVolumeEditor : VolumeComponentEditor { SerializedDataParameter m_Mode; - SerializedDataParameter m_FixedExposure; + SerializedDataParameter m_FixedExposureValue; + private LightUnitSliderUIDrawer m_LightUnitSlider; + public override void OnEnable() { var o = new PropertyFetcher(serializedObject); m_Mode = Unpack(o.Find(x => x.mode)); - m_FixedExposure = Unpack(o.Find(x => x.fixedExposure)); + m_FixedExposureValue = Unpack(o.Find(x => x.fixedExposure)); + + m_LightUnitSlider = new LightUnitSliderUIDrawer(); } public override void OnInspectorGUI() @@ -35,7 +39,38 @@ public override void OnInspectorGUI() if (m_Mode.value.intValue == (int)ExposureVolume.Mode.Fixed) { - PropertyField(m_FixedExposure); + DoExposurePropertyField(m_FixedExposureValue); + } + } + + void DoExposurePropertyField(SerializedDataParameter exposureProperty) + { + using (var scope = new OverridablePropertyScope(exposureProperty, exposureProperty.displayName, this)) + { + if (!scope.displayed) + return; + + using (new EditorGUILayout.VerticalScope()) + { + EditorGUILayout.LabelField(scope.label); + + var xOffset = EditorGUIUtility.labelWidth + 2; + + var lineRect = EditorGUILayout.GetControlRect(); + lineRect.x += xOffset; + lineRect.width -= xOffset; + + var sliderRect = lineRect; + sliderRect.y -= EditorGUIUtility.singleLineHeight; + m_LightUnitSlider.SetSerializedObject(serializedObject); + m_LightUnitSlider.DrawExposureSlider(exposureProperty.value, sliderRect); + + // Draw the numeric field below the slider + lineRect.x -= EditorGUIUtility.labelWidth + 2; + lineRect.y += EditorGUIUtility.standardVerticalSpacing; + lineRect.width += EditorGUIUtility.labelWidth + 2; + EditorGUI.PropertyField(lineRect, exposureProperty.value, EditorGUIUtility.TrTextContent(" ", (Texture)null, null)); + } } } } diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Overrides/FogVolumeEditor.cs b/Packages/com.unity.render-pipelines.universal/Editor/Overrides/FogEditor.cs similarity index 99% rename from Packages/com.unity.render-pipelines.universal/Editor/Overrides/FogVolumeEditor.cs rename to Packages/com.unity.render-pipelines.universal/Editor/Overrides/FogEditor.cs index 125059d57f2..4824f64ec92 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/Overrides/FogVolumeEditor.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/Overrides/FogEditor.cs @@ -5,7 +5,7 @@ namespace UnityEditor.Rendering.Universal { [CustomEditor(typeof(FogVolumeComponent))] - sealed class FogVolumeEditor : VolumeComponentEditor + sealed class FogEditor : VolumeComponentEditor { SerializedDataParameter m_AnalyticFogEnabled; SerializedDataParameter m_VolumetricFogEnabled; diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Overrides/FogVolumeEditor.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/Overrides/FogEditor.cs.meta similarity index 100% rename from Packages/com.unity.render-pipelines.universal/Editor/Overrides/FogVolumeEditor.cs.meta rename to Packages/com.unity.render-pipelines.universal/Editor/Overrides/FogEditor.cs.meta diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Overrides/ShadowsVolumeOverrideEditor.cs b/Packages/com.unity.render-pipelines.universal/Editor/Overrides/ShadowsVolumeOverrideEditor.cs new file mode 100644 index 00000000000..2872acc8330 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Editor/Overrides/ShadowsVolumeOverrideEditor.cs @@ -0,0 +1,159 @@ +using UnityEngine; +using UnityEngine.Rendering.Universal; + +namespace UnityEditor.Rendering.Universal +{ + [CustomEditor(typeof(ShadowsVolumeOverride))] + sealed class ShadowsVolumeOverrideEditor : VolumeComponentEditor + { + static class Styles + { + public const string directionalLightHeader = "Directional Light"; + public static readonly GUIContent workingUnit = L10n.TextContent("Working Unit", "The unit in which Unity measures the shadow cascade distances. The exception is Max Distance, which will still be in meters.", null, null); + } + + // VolumeComponentEditor draws the override checkbox in a column this wide (checkbox 14 + offset 9 + spacing 3) + // and OverridablePropertyScope shrinks the label by one more spacing, so rows without a checkbox match these to align. + const float k_OverrideCheckboxColumnWidth = 14f + 9f + 3f; + const float k_OverridableLabelWidthReduction = k_OverrideCheckboxColumnWidth + 3f; + + SerializedDataParameter m_MaxShadowDistance; + SerializedDataParameter m_CascadeCount; + readonly SerializedDataParameter[] m_CascadeSplits = new SerializedDataParameter[3]; + SerializedDataParameter m_LastCascadeBorder; + + GUIContent m_MaxDistanceLabel; + readonly GUIContent[] m_SplitLabels = new GUIContent[3]; + GUIContent m_LastBorderLabel; + + readonly bool[] m_SplitHandlesEnabled = new bool[3]; + + EditorPrefBoolFlags m_State; + + static GUIContent Label(SerializedDataParameter property, string text) + => L10n.TextContent(text, property.GetAttribute()?.tooltip, null, null); + + public override void OnEnable() + { + var o = new PropertyFetcher(serializedObject); + + m_MaxShadowDistance = Unpack(o.Find(x => x.maxShadowDistance)); + m_CascadeCount = Unpack(o.Find(x => x.cascadeCount)); + m_CascadeSplits[0] = Unpack(o.Find(x => x.cascadeSplit0)); + m_CascadeSplits[1] = Unpack(o.Find(x => x.cascadeSplit1)); + m_CascadeSplits[2] = Unpack(o.Find(x => x.cascadeSplit2)); + m_LastCascadeBorder = Unpack(o.Find(x => x.lastCascadeBorder)); + + m_MaxDistanceLabel = Label(m_MaxShadowDistance, "Max Distance"); + for (int i = 0; i < m_CascadeSplits.Length; ++i) + m_SplitLabels[i] = Label(m_CascadeSplits[i], $"Split {i + 1}"); + m_LastBorderLabel = Label(m_LastCascadeBorder, "Last Border"); + + m_State = new EditorPrefBoolFlags("URP:ShadowsVolumeOverrideEditor:UI_State"); + } + + public override void OnInspectorGUI() + { + PropertyField(m_MaxShadowDistance, m_MaxDistanceLabel); + + DrawHeader(Styles.directionalLightHeader); + using (new IndentLevelScope()) + DrawDirectionalLightCascades(); + } + + void DrawDirectionalLightCascades() + { + bool useMetric = DrawWorkingUnit() == EditorUtils.Unit.Metric; + + EditorGUI.BeginChangeCheck(); + PropertyField(m_CascadeCount); + bool cascadeCountChanged = EditorGUI.EndChangeCheck(); + + int cascadeCount = Mathf.Clamp(m_CascadeCount.value.intValue, UniversalRenderPipelineAsset.k_ShadowCascadeMinCount, UniversalRenderPipelineAsset.k_ShadowCascadeMaxCount); + int splitCount = cascadeCount - 1; + float maxDistance = m_MaxShadowDistance.value.floatValue; + + Vector4 splits = ShadowCascadeSplitGUI.SortSplits(new Vector4( + m_CascadeSplits[0].value.floatValue, + m_CascadeSplits[1].value.floatValue, + m_CascadeSplits[2].value.floatValue, + 1f), splitCount); + + if (cascadeCountChanged) + WriteSplits(splits, splitCount); + + for (int i = 0; i < splitCount; ++i) + DrawSplit(i, ref splits, splitCount, useMetric, maxDistance); + + DrawLastBorder(splits, splitCount, useMetric, maxDistance); + + for (int i = 0; i < splitCount; ++i) + m_SplitHandlesEnabled[i] = m_CascadeSplits[i].overrideState.boolValue; + + float border = m_LastCascadeBorder.value.floatValue; + if (ShadowCascadeSplitGUI.DrawCascades(ref splits, ref border, cascadeCount, useMetric, maxDistance, m_SplitHandlesEnabled, m_LastCascadeBorder.overrideState.boolValue)) + { + WriteSplits(splits, splitCount); + if (border != m_LastCascadeBorder.value.floatValue) + m_LastCascadeBorder.value.floatValue = border; + } + } + + EditorUtils.Unit DrawWorkingUnit() + { + Rect rect = EditorGUILayout.GetControlRect(); + if (enableOverrides) + rect.xMin += k_OverrideCheckboxColumnWidth; + + EditorGUIUtility.labelWidth -= k_OverridableLabelWidthReduction; + EditorGUI.BeginChangeCheck(); + var unit = (EditorUtils.Unit)EditorGUI.EnumPopup(rect, Styles.workingUnit, m_State.value); + if (EditorGUI.EndChangeCheck()) + m_State.value = unit; + EditorGUIUtility.labelWidth += k_OverridableLabelWidthReduction; + + return unit; + } + + void DrawSplit(int index, ref Vector4 splits, int splitCount, bool useMetric, float maxDistance) + { + SerializedDataParameter split = m_CascadeSplits[index]; + using (var scope = new OverridablePropertyScope(split, m_SplitLabels[index], this)) + { + if (!scope.displayed) + return; + + Rect rect = EditorGUILayout.GetControlRect(); + GUIContent label = EditorGUI.BeginProperty(rect, scope.label, split.value); + if (ShadowCascadeSplitGUI.SplitSlider(rect, label, ref splits, index, splitCount, useMetric, maxDistance)) + split.value.floatValue = splits[index]; + EditorGUI.EndProperty(); + } + } + + void DrawLastBorder(Vector4 splits, int splitCount, bool useMetric, float maxDistance) + { + using (var scope = new OverridablePropertyScope(m_LastCascadeBorder, m_LastBorderLabel, this)) + { + if (!scope.displayed) + return; + + Rect rect = EditorGUILayout.GetControlRect(); + GUIContent label = EditorGUI.BeginProperty(rect, scope.label, m_LastCascadeBorder.value); + float border = m_LastCascadeBorder.value.floatValue; + if (ShadowCascadeSplitGUI.LastBorderSlider(rect, label, ref border, splits, splitCount, useMetric, maxDistance)) + m_LastCascadeBorder.value.floatValue = border; + EditorGUI.EndProperty(); + } + } + + void WriteSplits(Vector4 splits, int splitCount) + { + for (int i = 0; i < splitCount; ++i) + { + if (m_CascadeSplits[i].value.floatValue != splits[i]) + m_CascadeSplits[i].value.floatValue = splits[i]; + } + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Overrides/ShadowsVolumeOverrideEditor.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/Overrides/ShadowsVolumeOverrideEditor.cs.meta new file mode 100644 index 00000000000..4e915bd64a4 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Editor/Overrides/ShadowsVolumeOverrideEditor.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 4f44e7ab7d924de897319316b0f4ff94 diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Overrides/SurfaceCacheGIVolumeEditor.cs b/Packages/com.unity.render-pipelines.universal/Editor/Overrides/SurfaceCacheGIVolumeEditor.cs index 2105277aaa4..66dfc2864f5 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/Overrides/SurfaceCacheGIVolumeEditor.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/Overrides/SurfaceCacheGIVolumeEditor.cs @@ -4,13 +4,14 @@ namespace UnityEditor.Rendering.Universal { [CustomEditor(typeof(SurfaceCacheGIVolumeOverride))] - internal class SurfaceCacheGIVolumeEditor : VolumeComponentEditor + internal class SurfaceCacheGIVolumeEditor : UniversalRenderPipelineVolumeComponentEditor { protected SurfaceCacheGIVolumeOverride.PresetQuality m_Quality; private bool m_QualityDirty = true; protected SerializedDataParameter m_Enabled; protected SerializedDataParameter m_Intensity; + protected SerializedDataParameter m_TransparencyMode; protected SerializedDataParameter m_LightTransportMultiBounce; protected SerializedDataParameter m_LightTransportBouncePatchAllocation; @@ -19,6 +20,7 @@ internal class SurfaceCacheGIVolumeEditor : VolumeComponentEditor protected SerializedDataParameter m_LightTransportRenderingLayerMask; protected SerializedDataParameter m_LightTransportWarmUpSampleMultiplier; protected SerializedDataParameter m_LightTransportPunctualLightCandidateCount; + protected SerializedDataParameter m_LightTransportRayTracingNormalBias; protected SerializedDataParameter m_PatchFilteringTemporalSmoothing; protected SerializedDataParameter m_PatchFilteringSpatialEnabled; @@ -35,6 +37,13 @@ internal class SurfaceCacheGIVolumeEditor : VolumeComponentEditor protected SerializedDataParameter m_VolumeDistanceFallback; protected SerializedDataParameter m_VolumePatchWarpingEnabled; + protected SerializedDataParameter m_EntityCullingSphereMode; + protected SerializedDataParameter m_EntityCullingDistanceMargin; + protected SerializedDataParameter m_EntityCullingDistance; + protected SerializedDataParameter m_EntityCullingSmallObjectUnit; + protected SerializedDataParameter m_EntityCullingMinScreenSize; + protected SerializedDataParameter m_EntityCullingMinSolidAngle; + // The Focus Target is serialized on the owning Volume's GameObject (Volume.m_SceneObjectReference), not in // the profile, so it is edited through this SerializedObject rather than a SerializedDataParameter. const string k_ReferenceProp = "m_SceneObjectReference"; @@ -47,11 +56,13 @@ internal class SurfaceCacheGIVolumeEditor : VolumeComponentEditor static GUIContent s_State = L10n.TextContent("State", "When Enabled, Surface Cache Global Illumination calculates indirect lighting at any Intensity value. When Disabled, it does not.", null, null); static GUIContent s_Intensity = L10n.TextContent("Intensity", "Scales the indirect lighting from Surface Cache Global Illumination. At 0 it adds no indirect lighting to the scene.", null, null); + static GUIContent s_TransparencyMode = L10n.TextContent("Transparency Mode", "Controls which geometry blocks rays. Opaques And Cutouts makes rays pass through fully transparent texels of alpha-cutout materials, such as foliage. Opaques Only is faster.", null, null); static GUIContent s_Quality = L10n.TextContent("Quality", "Quality preset for Surface Cache GI. Select Custom to manually adjust individual parameters.", null, null); static GUIContent s_LightTransportMultiBounce = L10n.TextContent("Multi Bounce", "Enable multi-bounce global illumination for more accurate light propagation.", null, null); static GUIContent s_LightTransportBouncePatchAllocation = L10n.TextContent("Bounce Patch Allocation", "When enabled, new patches are allocated at ray hit locations when multi-bounce cache lookups fail", null, null); static GUIContent s_LightTransportSampleCount = L10n.TextContent("Sample Count", "Number of samples used for GI estimation. Higher values improve quality at performance cost.", null, null); static GUIContent s_LightTransportWarmUpSampleMultiplier = L10n.TextContent("Warm-up Sample Multiplier", "Boosts the initial sample count on newly revealed surfaces if needed. This stabilizes the image faster when geometry or camera is moving.", null, null); + static GUIContent s_LightTransportRayTracingNormalBias = L10n.TextContent("Ray Tracing Normal Bias", "Offsets ray origins along the surface normal, in world units. Increase this to fix dark artifacts when the ray tracing geometry differs from the rasterized geometry, for example when an object is rasterized with a less detailed mesh LOD, because ray tracing always uses mesh LOD 0. High values can cause light leaking.", null, null); static GUIContent s_LightTransportPunctualLightCandidateCount = L10n.TextContent("Punctual Light Candidate Count", "Number of punctual light candidates considered for each punctual light sample. Higher values reduce noise at a minor performance cost.", null, null); static GUIContent s_PatchFilteringTemporalSmoothing = L10n.TextContent("Temporal Smoothing", "Temporal smoothing for patch data. Higher values produce more stable results but slower response to lighting changes.", null, null); static GUIContent s_PatchFilteringSpatialEnabled = L10n.TextContent("Spatial Filtering", "Enables spatial filtering across patches. This reduces noise but may also increase leaking.", null, null); @@ -65,6 +76,12 @@ internal class SurfaceCacheGIVolumeEditor : VolumeComponentEditor static GUIContent s_VolumeCascadeCount = L10n.TextContent("Cascade Count", "Controls how patch density changes with distance. Higher values result in greater lighting detail up close and lower far away. Lower values evens out the distribution.", null, null); static GUIContent s_VolumeDistanceFallback = L10n.TextContent("Distance Fallback", "When enabled, a realtime global probe calculated from the environment light will be applied in the far distance.", null, null); static GUIContent s_PatchWarping = L10n.TextContent("Patch Warping", "Reduces flickering on flat surfaces lined up with the voxel grid (e.g. a floor at height 0). When off, no warping is applied.", null, null); + static GUIContent s_EntityCullingSphereMode = L10n.TextContent("Sphere Culling", "Leave out entities beyond a distance from every camera, following the Surface Cache volume plus a margin or at a fixed distance.", null, null); + static GUIContent s_EntityCullingDistanceMargin = L10n.TextContent("Margin", "How far beyond the Surface Cache volume entities are kept.", null, null); + static GUIContent s_EntityCullingDistance = L10n.TextContent("Distance", "Entities farther than this from every camera are left out.", null, null); + static GUIContent s_EntityCullingSmallObjectUnit = L10n.TextContent("Small Object Culling", "Leave out entities smaller than a minimum size for every camera, in pixels on screen or in degrees.", null, null); + static GUIContent s_EntityCullingMinScreenSize = L10n.TextContent("Min Screen Size", "Entities smaller than this many pixels on screen for every camera are left out.", null, null); + static GUIContent s_EntityCullingMinSolidAngle = L10n.TextContent("Min Solid Angle", "Entities covering a smaller angle than this, in degrees, for every camera are left out.", null, null); static GUIContent s_FocusTarget = L10n.TextContent("Focus Target", "GameObject the Surface Cache GI cascades center on. When unset, cascades follow the active camera. Stored on the Volume component, not in the shared Volume Profile.", null, null); static GUIContent s_FocusTargetProfile = L10n.TextContent("Focus Target", "GameObject the Surface Cache GI cascades center on. When unset, cascades follow the active camera. Requires a scene object reference, so it cannot be stored in the Volume Profile. Assign it on the Volume component in your scene.", null, null); static GUIContent s_FocusTargetProfileValue = L10n.TextContent("Scene object, set per Volume", null, null, null); @@ -73,16 +90,20 @@ internal class SurfaceCacheGIVolumeEditor : VolumeComponentEditor static GUIContent s_LightTransportHeader = L10n.TextContent("Light Transport", "Controls how many rays are cast per patch to estimate indirect lighting. More samples reduce variance but increase GPU cost per frame.", null, null); static GUIContent s_PatchFilteringHeader = L10n.TextContent("Patch Filtering", "Controls how patch irradiance data is filtered over time and space. These settings trade temporal stability and spatial smoothness against responsiveness to lighting changes and light leaking.", null, null); static GUIContent s_ScreenFilteringHeader = L10n.TextContent("Screen Filtering", "Controls how the low-resolution patch irradiance is resolved and upsampled to full screen resolution. These settings affect the final image quality and sharpness of the GI contribution.", null, null); + static GUIContent s_EntityCullingHeader = L10n.TextContent("Entity Culling", "Leaves entities (ECS) that contribute little to the indirect lighting out of the Surface Cache world, which makes it cheaper to update. An entity is kept while any camera keeps it.", null, null); static GUIContent s_VolumeHeader = L10n.TextContent("Volume", "Defines the spatial extent and grid density of the surface cache volume. Size can be changed freely at runtime. Resolution and cascade count changes reallocate internal buffers, which may cause a brief hitch.", null, null); static GUIContent s_DefragCount = L10n.TextContent("Defrag Count", "Number of surface cache patches to defragment per frame. Higher values reduce memory fragmentation at a small per-frame cost.", null, null); static GUIContent s_RenderingLayerMask = L10n.TextContent("Rendering Layer Mask", "Only renderers whose Rendering Layer Mask intersects this mask contribute to Surface Cache GI.", null, null); public override void OnEnable() { + base.OnEnable(); + var o = new PropertyFetcher(serializedObject); m_Enabled = Unpack(o.Find(obj => obj.enabled)); m_Intensity = Unpack(o.Find(obj => obj.intensity)); + m_TransparencyMode = Unpack(o.Find(obj => obj.transparencyMode)); m_LightTransportMultiBounce = Unpack(o.Find(obj => obj.lightTransportMultiBounce)); m_LightTransportBouncePatchAllocation = Unpack(o.Find(obj => obj.lightTransportBouncePatchAllocation)); m_LightTransportDefragCount = Unpack(o.Find(obj => obj.lightTransportDefragCount)); @@ -90,6 +111,7 @@ public override void OnEnable() m_LightTransportSampleCount = Unpack(o.Find(obj => obj.lightTransportSampleCount)); m_LightTransportWarmUpSampleMultiplier = Unpack(o.Find(obj => obj.lightTransportWarmupSampleMultiplier)); m_LightTransportPunctualLightCandidateCount = Unpack(o.Find(obj => obj.lightTransportPunctualLightCandidateCount)); + m_LightTransportRayTracingNormalBias = Unpack(o.Find(obj => obj.lightTransportRayTracingNormalBias)); m_PatchFilteringTemporalSmoothing = Unpack(o.Find(obj => obj.patchFilteringTemporalSmoothing)); m_PatchFilteringSpatialEnabled = Unpack(o.Find(obj => obj.patchFilteringSpatialEnabled)); m_PatchFilteringSpatialSampleCount = Unpack(o.Find(obj => obj.patchFilteringSpatialSampleCount)); @@ -102,6 +124,12 @@ public override void OnEnable() m_VolumeCascadeCount = Unpack(o.Find(obj => obj.volumeCascadeCount)); m_VolumePatchWarpingEnabled = Unpack(o.Find(obj => obj.volumePatchWarpingEnabled)); m_VolumeDistanceFallback = Unpack(o.Find(obj => obj.volumeDistanceFallback)); + m_EntityCullingSphereMode = Unpack(o.Find(obj => obj.entityCullingSphereMode)); + m_EntityCullingDistanceMargin = Unpack(o.Find(obj => obj.entityCullingDistanceMargin)); + m_EntityCullingDistance = Unpack(o.Find(obj => obj.entityCullingDistance)); + m_EntityCullingSmallObjectUnit = Unpack(o.Find(obj => obj.entityCullingSmallObjectUnit)); + m_EntityCullingMinScreenSize = Unpack(o.Find(obj => obj.entityCullingMinScreenSize)); + m_EntityCullingMinSolidAngle = Unpack(o.Find(obj => obj.entityCullingMinSolidAngle)); // Re-detect preset when property changed ((SurfaceCacheGIVolumeOverride)target).propertyChanged += MarkQualityDirty; @@ -116,15 +144,22 @@ public override void OnDisable() m_VolumeSerializedObject.Dispose(); m_VolumeSerializedObject = null; } + + base.OnDisable(); } public override void OnInspectorGUI() { + if (SceneView.lastActiveSceneView && !SceneView.lastActiveSceneView.sceneViewState.alwaysRefreshEnabled) + EditorGUILayout.HelpBox("Enable \"Always Refresh\" in the Scene View to see realtime updates in the Scene View.", MessageType.Info); + PropertyField(m_Enabled, s_State); if (showAdditionalProperties) PropertyField(m_Intensity, s_Intensity); + PropertyField(m_TransparencyMode, s_TransparencyMode); + // Quality preset dropdown. Switching to a named preset writes its values into the // backing fields so users can see the preset values and make fine adjustments from there. var quality = (SurfaceCacheGIVolumeOverride.PresetQuality)EditorGUILayout.EnumPopup(s_Quality, m_Quality, (e) => (SurfaceCacheGIVolumeOverride.PresetQuality)e != SurfaceCacheGIVolumeOverride.PresetQuality.Custom, false); @@ -165,6 +200,7 @@ public override void OnInspectorGUI() if (showAdditionalProperties) { PropertyField(m_LightTransportPunctualLightCandidateCount, s_LightTransportPunctualLightCandidateCount); + PropertyField(m_LightTransportRayTracingNormalBias, s_LightTransportRayTracingNormalBias); PropertyField(m_LightTransportRenderingLayerMask, s_RenderingLayerMask); PropertyField(m_LightTransportDefragCount, s_DefragCount); } @@ -187,6 +223,37 @@ public override void OnInspectorGUI() EditorGUILayout.LabelField(s_ScreenFilteringHeader, EditorStyles.boldLabel); PropertyField(m_ScreenFilteringLookupSampleCount, s_ScreenFilteringLookupSampleCount); PropertyField(m_ScreenFilteringDenoisingPassCount, s_ScreenFilteringDenoisingPassCount); + + if (showAdditionalProperties) + { + EditorGUILayout.Space(); + EditorGUILayout.LabelField(s_EntityCullingHeader, EditorStyles.boldLabel); + PropertyField(m_EntityCullingSphereMode, s_EntityCullingSphereMode); + var sphereMode = (SurfaceCacheGIVolumeOverride.EntityCullingSphereMode)m_EntityCullingSphereMode.value.intValue; + if (sphereMode != SurfaceCacheGIVolumeOverride.EntityCullingSphereMode.None) + { + using (new IndentLevelScope()) + { + if (sphereMode == SurfaceCacheGIVolumeOverride.EntityCullingSphereMode.Fixed) + PropertyField(m_EntityCullingDistance, s_EntityCullingDistance); + else + PropertyField(m_EntityCullingDistanceMargin, s_EntityCullingDistanceMargin); + } + } + + PropertyField(m_EntityCullingSmallObjectUnit, s_EntityCullingSmallObjectUnit); + var smallObjectUnit = (SurfaceCacheGIVolumeOverride.EntityCullingSmallObjectUnit)m_EntityCullingSmallObjectUnit.value.intValue; + if (smallObjectUnit != SurfaceCacheGIVolumeOverride.EntityCullingSmallObjectUnit.None) + { + using (new IndentLevelScope()) + { + if (smallObjectUnit == SurfaceCacheGIVolumeOverride.EntityCullingSmallObjectUnit.Degrees) + PropertyField(m_EntityCullingMinSolidAngle, s_EntityCullingMinSolidAngle); + else + PropertyField(m_EntityCullingMinScreenSize, s_EntityCullingMinScreenSize); + } + } + } } // Focus Target is bound to the owning Volume's GameObject instead of the shared profile. When editing diff --git a/Packages/com.unity.render-pipelines.universal/Editor/RendererFeatures/OnTilePostProcessFeatureEditor.cs b/Packages/com.unity.render-pipelines.universal/Editor/RendererFeatures/OnTilePostProcessFeatureEditor.cs index 3ee8c26fb39..2bcfa0753ae 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/RendererFeatures/OnTilePostProcessFeatureEditor.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/RendererFeatures/OnTilePostProcessFeatureEditor.cs @@ -11,7 +11,8 @@ internal class OnTilePostProcessFeatureEditor : Editor, IOwningRendererDataConsu static class Styles { - public static readonly string k_NoSettingsHelpBox = L10n.Tr("Only pixel local post-processing effects are supported. For example color adjustments, vignette or film grain. There are currently no available settings.", null); + public static readonly string k_NoSettingsHelpBox = L10n.Tr("Only pixel local post-processing effects are supported (for example color adjustments, vignette or film grain). There are currently no additional settings.", null); + public static readonly string k_BuiltInPostProcessingIncompatible = L10n.Tr("The UniversalRendererData has post processing enabled, which conflicts with this feature. Only one form of post processing should be enabled. This feature will not be added.", null); public static readonly string k_TileOnlyModeOffWarning = L10n.Tr("Tile-Only Mode is not enabled on this Renderer. This feature will fallback to texture sampling mode. This uses more GPU bandwidth and can reduce performance.", null); } @@ -28,8 +29,14 @@ public override void OnInspectorGUI() { var rendererData = (this as IOwningRendererDataConsumer).owningRendererData as UniversalRendererData; if (rendererData == null || !rendererData.tileOnlyMode) - EditorGUILayout.HelpBox(Styles.k_TileOnlyModeOffWarning, MessageType.Warning); - EditorGUILayout.HelpBox(Styles.k_NoSettingsHelpBox, MessageType.Info); + { + if (rendererData != null && rendererData.postProcessData != null) + EditorGUILayout.HelpBox(Styles.k_BuiltInPostProcessingIncompatible + "\n\n" + Styles.k_NoSettingsHelpBox, MessageType.Error); + else + EditorGUILayout.HelpBox(Styles.k_TileOnlyModeOffWarning + "\n\n" + Styles.k_NoSettingsHelpBox, MessageType.Warning); + } + else + EditorGUILayout.HelpBox(Styles.k_NoSettingsHelpBox, MessageType.Info); } } } diff --git a/Packages/com.unity.render-pipelines.universal/Editor/RendererFeatures/SurfaceCacheGIEditor.cs b/Packages/com.unity.render-pipelines.universal/Editor/RendererFeatures/SurfaceCacheGIEditor.cs index 88eb42078d3..e544220f1c2 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/RendererFeatures/SurfaceCacheGIEditor.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/RendererFeatures/SurfaceCacheGIEditor.cs @@ -11,6 +11,12 @@ internal class SurfaceCacheGIEditor : Editor { private const string k_UnsupportedRayTracingBackendMessage = "Surface Cache GI will not run on this device because it does not support hardware ray tracing or compute shaders."; + private static class Styles + { + public static readonly GUIContent materialResolution = L10n.TextContent("Material Resolution", + "Resolution at which each material's albedo, emission and transmission are captured for Surface Cache GI. Lower values fit more materials into the GPU texture atlas; GI is low-frequency, so Medium is usually indistinguishable from Very High.", null, null); + } + private static bool SceneHasSurfaceCacheGIVolume() { Volume[] volumes = Object.FindObjectsByType(FindObjectsInactive.Exclude); @@ -58,6 +64,10 @@ public override void OnInspectorGUI() { EditorGUILayout.HelpBox("Many Surface Cache settings are controlled via the Volume system. Add a 'Surface Cache Global Illumination' volume override to your scene to adjust these settings per-scene.", MessageType.Info); } + + serializedObject.Update(); + EditorGUILayout.PropertyField(serializedObject.FindProperty("m_MaterialResolution"), Styles.materialResolution); + serializedObject.ApplyModifiedProperties(); } } } diff --git a/Packages/com.unity.render-pipelines.universal/Editor/SceneTemplates/Materials/Black.mat b/Packages/com.unity.render-pipelines.universal/Editor/SceneTemplates/Materials/Black.mat index 63bc48d96a1..b0ea8003c9b 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/SceneTemplates/Materials/Black.mat +++ b/Packages/com.unity.render-pipelines.universal/Editor/SceneTemplates/Materials/Black.mat @@ -116,7 +116,7 @@ Material: - _ZWrite: 1 m_Colors: - _BaseColor: {r: 0.103999995, g: 0.103999995, b: 0.10053333, a: 1} - - _Color: {r: 0.10399995, g: 0.10399995, b: 0.1005333, a: 1} + - _Color: {r: 0.103999995, g: 0.103999995, b: 0.10053333, a: 1} - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} - _SpecColor: {r: 0.19999996, g: 0.19999996, b: 0.19999996, a: 1} m_BuildTextureStacks: [] diff --git a/Packages/com.unity.render-pipelines.universal/Editor/SceneTemplates/Materials/Emissive.mat b/Packages/com.unity.render-pipelines.universal/Editor/SceneTemplates/Materials/Emissive.mat index 640a51f8490..90f24a53d6a 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/SceneTemplates/Materials/Emissive.mat +++ b/Packages/com.unity.render-pipelines.universal/Editor/SceneTemplates/Materials/Emissive.mat @@ -11,7 +11,8 @@ Material: m_Shader: {fileID: 4800000, guid: 933532a4fcc9baf4fa0491de14d08ed7, type: 3} m_Parent: {fileID: 0} m_ModifiedSerializedProperties: 0 - m_ValidKeywords: [] + m_ValidKeywords: + - _EMISSION m_InvalidKeywords: [] m_LightmapFlags: 10 m_EnableInstancingVariants: 0 @@ -106,9 +107,11 @@ Material: - _OcclusionStrength: 1 - _Parallax: 0.005 - _QueueOffset: 0 + - _ReceiveFog: 1 - _ReceiveShadows: 1 - _SampleGI: 0 - _ScreenSpaceReflections: 1 + - _ScreenSpaceReflectionsContributeTransparent: 1 - _Smoothness: 0.5 - _SmoothnessTextureChannel: 0 - _SpecularHighlights: 1 diff --git a/Packages/com.unity.render-pipelines.universal/Editor/SceneTemplates/Materials/Ground.mat b/Packages/com.unity.render-pipelines.universal/Editor/SceneTemplates/Materials/Ground.mat index 799afff962f..ee34e57d739 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/SceneTemplates/Materials/Ground.mat +++ b/Packages/com.unity.render-pipelines.universal/Editor/SceneTemplates/Materials/Ground.mat @@ -117,7 +117,7 @@ Material: - _ZWrite: 1 m_Colors: - _BaseColor: {r: 0.65099996, g: 0.65099996, b: 0.65099996, a: 1} - - _Color: {r: 0.6509999, g: 0.6509999, b: 0.6509999, a: 1} + - _Color: {r: 0.65099996, g: 0.65099996, b: 0.65099996, a: 1} - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} - _SpecColor: {r: 0.19999996, g: 0.19999996, b: 0.19999996, a: 1} m_BuildTextureStacks: [] diff --git a/Packages/com.unity.render-pipelines.universal/Editor/SceneTemplates/Materials/Metal_Black.mat b/Packages/com.unity.render-pipelines.universal/Editor/SceneTemplates/Materials/Metal_Black.mat index f9a57702f32..592c2d47d4e 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/SceneTemplates/Materials/Metal_Black.mat +++ b/Packages/com.unity.render-pipelines.universal/Editor/SceneTemplates/Materials/Metal_Black.mat @@ -130,7 +130,7 @@ Material: - _ZWrite: 1 m_Colors: - _BaseColor: {r: 0.2509804, g: 0.2509804, b: 0.2509804, a: 1} - - _Color: {r: 0.25098038, g: 0.25098038, b: 0.25098038, a: 1} + - _Color: {r: 0.2509804, g: 0.2509804, b: 0.2509804, a: 1} - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} - _SpecColor: {r: 0.19999996, g: 0.19999996, b: 0.19999996, a: 1} m_BuildTextureStacks: [] diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Settings/GlobalConstantBufferShaderDefine.cs b/Packages/com.unity.render-pipelines.universal/Editor/Settings/GlobalConstantBufferShaderDefine.cs deleted file mode 100644 index 82dac73f37d..00000000000 --- a/Packages/com.unity.render-pipelines.universal/Editor/Settings/GlobalConstantBufferShaderDefine.cs +++ /dev/null @@ -1,93 +0,0 @@ -using UnityEditor.Build.Profile; -using UnityEditor.Shaders; -using UnityEngine.Rendering; -using UnityEngine.Rendering.Universal; - -namespace UnityEditor.Rendering.Universal -{ - // Keeps the URP_GLOBAL_CONSTANT_BUFFER shader define in sync with - // RenderingCapabilitiesSettings.useGlobalConstantBuffer. GlobalShaderVariables.hlsl declares the - // GlobalShaderVariables cbuffer only when that define is present, so the two must never disagree: a shader - // declaring loose uniforms while the pipeline pushes a cbuffer leaves those uniforms unwritten. - static class GlobalConstantBufferShaderDefine - { - const string k_Identifier = "URP_GLOBAL_CONSTANT_BUFFER"; - const string k_Value = "1"; - const string k_Define = k_Identifier + " " + k_Value; - - [InitializeOnLoadMethod] - static void Initialize() - { - // The property setter and the Project Settings UI both notify, but with different property names - // (useGlobalConstantBuffer vs m_UseGlobalConstantBuffer), so react to any change on the - // type rather than filtering. Reconcile only writes when something differs. - GraphicsSettings.Unsubscribe(OnSettingsChanged); - GraphicsSettings.Subscribe(OnSettingsChanged); - - // The effective ShaderBuildSettings is the active build profile's when there is one. - BuildProfile.activeProfileChanged -= OnActiveProfileChanged; - BuildProfile.activeProfileChanged += OnActiveProfileChanged; - - // The setting is [SupportedOnRenderPipeline(URP)], so Reconcile's lookup only resolves while URP is - // active, and swapping pipeline changes that without a domain reload or a settings notification. Without - // this, leaving URP and coming back leaves a stale define. RenderPipelineManager defers the event until - // currentPipeline matches, so Reconcile sees the pipeline we switched to. - RenderPipelineManager.activeRenderPipelineTypeChanged -= OnActiveRenderPipelineTypeChanged; - RenderPipelineManager.activeRenderPipelineTypeChanged += OnActiveRenderPipelineTypeChanged; - - Reconcile(); - } - - static void OnSettingsChanged(RenderingCapabilitiesSettings settings, string propertyName) => Reconcile(); - - static void OnActiveProfileChanged(BuildProfile previous, BuildProfile current) => Reconcile(); - - static void OnActiveRenderPipelineTypeChanged() => Reconcile(); - - static void Reconcile() - { - // Bail out rather than treating an unresolved setting as off, which would strip the define and - // reimport every shader in the project. - if (!GraphicsSettings.TryGetRenderPipelineSettings(out var capabilities)) - return; - - // As an internal define, it stays out of the Shader Constant Defines UI and nobody can - // edit it out of sync with the setting. - ShaderBuildSettings buildSettings = EditorGraphicsSettings.GetShaderBuildSettings(); - bool hasDefine = ShaderBuildSettingsBridge.HasInternalDefine(ref buildSettings, k_Identifier); - - switch (Decide(capabilities.useGlobalConstantBuffer, hasDefine)) - { - case DefineAction.Add: - ShaderBuildSettingsBridge.AddInternalDefine(ref buildSettings, k_Define); - break; - - case DefineAction.Remove: - ShaderBuildSettingsBridge.RemoveInternalDefine(ref buildSettings, k_Identifier); - break; - - default: - return; - } - - // This reimports every shader in the project, which is why Decide gates it. - EditorGraphicsSettings.SetShaderBuildSettings(buildSettings); - } - - internal enum DefineAction - { - None, - Add, - Remove, - } - - // Kept apart from the state it reads so it can be tested: acting on the result reimports every shader. - internal static DefineAction Decide(bool wanted, bool hasDefine) - { - if (wanted == hasDefine) - return DefineAction.None; - - return wanted ? DefineAction.Add : DefineAction.Remove; - } - } -} diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Settings/GlobalConstantBufferShaderDefine.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/Settings/GlobalConstantBufferShaderDefine.cs.meta deleted file mode 100644 index 96e6aed8ee3..00000000000 --- a/Packages/com.unity.render-pipelines.universal/Editor/Settings/GlobalConstantBufferShaderDefine.cs.meta +++ /dev/null @@ -1,2 +0,0 @@ -fileFormatVersion: 2 -guid: 2e9061e497f364e7c9364737b6281e36 diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderBuildPreprocessor.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderBuildPreprocessor.cs index 002bbd13ae4..81fb5aa6eaa 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderBuildPreprocessor.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderBuildPreprocessor.cs @@ -5,7 +5,7 @@ using UnityEngine; using UnityEngine.Rendering.Universal; using UnityEngine.Rendering; -#if XR_MANAGEMENT_4_0_1_OR_NEWER +#if XR_MANAGEMENT_4_0_1_OR_NEWER || XR_FOUNDATION_7_0_0_OR_NEWER using UnityEditor.XR.Management; using UnityEngine.XR.Management; #endif @@ -79,6 +79,8 @@ enum ShaderFeatures : long RenderObjectDepthInputAttachment = (1L << 56), VolumetricFog = (1L << 57), LightFalloffQuadratic = (1L << 58), + ShadowsPCSS = (1L << 59), + ShadowReceiverNormalBias = (1L << 60), All = ~0 } @@ -199,7 +201,7 @@ private PlatformBuildTimeDetect() isSwitch = buildTargetGroup == BuildTargetGroup.Switch; isSwitch2 = buildTargetGroup == BuildTargetGroup.Switch2; -#if XR_MANAGEMENT_4_0_1_OR_NEWER +#if XR_MANAGEMENT_4_0_1_OR_NEWER || XR_FOUNDATION_7_0_0_OR_NEWER var buildTargetSettings = XRGeneralSettingsPerBuildTarget.XRGeneralSettingsForBuildTarget(buildTargetGroup); if (buildTargetSettings != null && buildTargetSettings.Manager != null && buildTargetSettings.Manager.activeLoaders.Count > 0) { @@ -232,6 +234,7 @@ internal struct RendererRequirements public bool needsAdditionalLightShadows; public bool needsSoftShadows; public bool needsSoftShadowsQualityLevels; + public bool needsShadowsPCSS; public bool needsShadowsOff; public bool needsAdditionalLightsOff; public bool needsGBufferRenderingLayers; @@ -393,7 +396,7 @@ private static void GetGlobalAndPlatformSettings() s_UseSHPerVertexForSHAuto = true; // XR Stripping - #if XR_MANAGEMENT_4_0_1_OR_NEWER + #if XR_MANAGEMENT_4_0_1_OR_NEWER || XR_FOUNDATION_7_0_0_OR_NEWER BuildTargetGroup buildTargetGroup = BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget); XRGeneralSettings generalSettings = XRGeneralSettingsPerBuildTarget.XRGeneralSettingsForBuildTarget(buildTargetGroup); s_StripXRVariants = generalSettings == null || generalSettings.Manager == null || generalSettings.Manager.activeLoaders.Count <= 0; @@ -451,19 +454,26 @@ internal static void GetSupportedFeaturesFromVolumes(List volumeP if (asset.TryGet(out var lensDistortion) && lensDistortion.IsActive()) volumeFeatures |= VolumeFeatures.LensDistortion; - if (asset.TryGet(out var bloom) && bloom.IsActive()) + bool hasBloom = asset.TryGet(out var bloom); + + // Screen Space Lens Flare runs bloom as a dependency even when bloom is inactive + bool lensFlareRequiresBloom = asset.TryGet(out var lensFlare) && lensFlare.IsActive(); + + if ((hasBloom && bloom.IsActive()) || lensFlareRequiresBloom) { + bool hasBloomDirt = hasBloom && bloom.dirtIntensity.value > 0f && bloom.dirtTexture.value != null; + //strip unused bloom variants. #pragma multi_compile_local_fragment _ _BLOOM_LQ _BLOOM_HQ _BLOOM_LQ_DIRT _BLOOM_HQ_DIRT - if (bloom.highQualityFiltering.value) + if (hasBloom && bloom.highQualityFiltering.value) { - if (bloom.dirtIntensity.value > 0f && bloom.dirtTexture.value != null) + if (hasBloomDirt) volumeFeatures |= VolumeFeatures.BloomHQDirt; else volumeFeatures |= VolumeFeatures.BloomHQ; } else { - if (bloom.dirtIntensity.value > 0f && bloom.dirtTexture.value != null) + if (hasBloomDirt) volumeFeatures |= VolumeFeatures.BloomLQDirt; else volumeFeatures |= VolumeFeatures.BloomLQ; @@ -677,6 +687,9 @@ internal static ShaderFeatures GetSupportedShaderFeaturesFromAsset( if (UniversalRenderPipeline.IsQuadraticFalloffEnabled()) urpAssetShaderFeatures |= ShaderFeatures.LightFalloffQuadratic; + if (ShadowUtils.IsShadowReceiverNormalBiasEnabled()) + urpAssetShaderFeatures |= ShaderFeatures.ShadowReceiverNormalBias; + if (urpAsset.supportScreenSpaceLensFlare) urpAssetShaderFeatures |= ShaderFeatures.ScreenSpaceLensFlare; @@ -788,6 +801,8 @@ internal static RendererRequirements GetRendererRequirements(ref UniversalRender rsd.needsAdditionalLightShadows = urpAsset.supportsAdditionalLightShadows && (urpAsset.additionalLightsRenderingMode == LightRenderingMode.PerPixel || rsd.renderingMode == RenderingMode.ForwardPlus); rsd.needsSoftShadows = urpAsset.supportsSoftShadows && (rsd.needsMainLightShadows || rsd.needsAdditionalLightShadows); rsd.needsSoftShadowsQualityLevels = rsd.needsSoftShadows && s_UseSoftShadowQualityLevelKeywords; + // PCSS needs the per-light soft shadow quality, which the quality level keywords replace + rsd.needsShadowsPCSS = rsd.needsSoftShadows && !rsd.needsSoftShadowsQualityLevels && ((urpAsset.mainLightShadowsPCSS && rsd.needsMainLightShadows) || (urpAsset.additionalLightShadowsPCSS && rsd.needsAdditionalLightShadows)); rsd.needsShadowsOff = !rendererData.stripShadowsOffVariants; rsd.needsAdditionalLightsOff = s_KeepOffVariantForAdditionalLights || !rendererData.stripAdditionalLightOffVariants; rsd.needsGBufferRenderingLayers = (rsd.isUniversalRenderer && rsd.needsDeferredLighting && urpAsset.useRenderingLayers); @@ -868,6 +883,9 @@ internal static ShaderFeatures GetSupportedShaderFeaturesFromRenderer(ref Render if (rendererRequirements.needsSoftShadows && !rendererRequirements.needsSoftShadowsQualityLevels) shaderFeatures |= ShaderFeatures.SoftShadows; + if (rendererRequirements.needsShadowsPCSS) + shaderFeatures |= ShaderFeatures.ShadowsPCSS; + if (rendererRequirements.needsSoftShadowsQualityLevels) { if (UniversalRenderPipeline.asset?.softShadowQuality == SoftShadowQuality.Low) @@ -944,7 +962,8 @@ internal static ShaderFeatures GetSupportedShaderFeaturesFromRendererFeatures(re if (sssFeature != null) { // The feature is active (Tested a few lines above) - shaderFeatures |= ShaderFeatures.ScreenSpaceShadows; + if (rendererRequirements.needsMainLightShadows) + shaderFeatures |= ShaderFeatures.ScreenSpaceShadows; continue; } @@ -1129,6 +1148,7 @@ ref List ssaoRendererFeatures spd.stripSoftShadowsQualityLow = !IsFeatureEnabled(shaderFeatures, ShaderFeatures.SoftShadowsLow); spd.stripSoftShadowsQualityMedium = !IsFeatureEnabled(shaderFeatures, ShaderFeatures.SoftShadowsMedium); spd.stripSoftShadowsQualityHigh = !IsFeatureEnabled(shaderFeatures, ShaderFeatures.SoftShadowsHigh); + spd.stripShadowsPCSS = !IsFeatureEnabled(shaderFeatures, ShaderFeatures.ShadowsPCSS); spd.stripHDRKeywords = stripHDR; spd.stripAlphaOutputKeywords = !IsFeatureEnabled(shaderFeatures, ShaderFeatures.AlphaOutput); spd.stripDebugDisplay = stripDebug; @@ -1143,6 +1163,7 @@ ref List ssaoRendererFeatures spd.stripWriteSmoothness = !IsFeatureEnabled(shaderFeatures, ShaderFeatures.ScreenSpaceReflection); spd.stripVolumetricFog = !IsFeatureEnabled(shaderFeatures, ShaderFeatures.VolumetricFog); spd.stripLightFalloffQuadratic = !IsFeatureEnabled(shaderFeatures, ShaderFeatures.LightFalloffQuadratic); + spd.stripShadowReceiverNormalBias = !IsFeatureEnabled(shaderFeatures, ShaderFeatures.ShadowReceiverNormalBias); // Rendering Modes // Check if only Deferred is being used diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/BaseShaderGUI.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/BaseShaderGUI.cs index 414f9c9bd93..54cb53fd271 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/BaseShaderGUI.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/BaseShaderGUI.cs @@ -166,6 +166,25 @@ public enum QueueControl UserOverride = 1 } + /// + /// The options for controlling the Emission Intensity Unit. + /// + public enum EmissionUnits + { + /// + /// Nits. + /// + Nits = 0, + + /// + /// EV100. + /// + EV100 = 1 + } + + // Max EV Value. + private const float k_MaxEvValue = 130.0f; + /// /// Container for the text and tooltips used to display the shader. /// @@ -547,6 +566,26 @@ protected internal class Styles /// protected MaterialProperty emissionColorProp { get; set; } + /// + /// The MaterialProperty for emission intensity on/off. + /// + protected MaterialProperty useEmissionIntensityProp { get; set; } + + /// + /// The MaterialProperty for emission color with intensity. + /// + protected MaterialProperty emissionColorLDRProp { get; set; } + + /// + /// The MaterialProperty for emission intensity value. + /// + protected MaterialProperty emissionIntensityProp { get; set; } + + /// + /// The MaterialProperty for emission intensity units. + /// + protected MaterialProperty emissionIntensityUnitProp { get; set; } + /// /// The MaterialProperty for queue offset. /// @@ -637,6 +676,11 @@ public virtual void FindProperties(MaterialProperty[] properties) emissionMapProp = FindProperty(Property.EmissionMap, properties, false); emissionColorProp = FindProperty(Property.EmissionColor, properties, false); queueOffsetProp = FindProperty(Property.QueueOffset, properties, false); + + useEmissionIntensityProp = FindProperty(Property.UseEmissionIntensity, properties, false); + emissionColorLDRProp = FindProperty(Property.EmissionColorLDR, properties, false); + emissionIntensityProp = FindProperty(Property.EmissionIntensity, properties, false); + emissionIntensityUnitProp = FindProperty(Property.EmissionIntensityUnit, properties, false); } /// @@ -1117,10 +1161,190 @@ private void DrawEmissionTextureProperty() { if ((emissionMapProp == null) || (emissionColorProp == null)) return; + // Fallback: old behavior if new properties don't exist (backward compatibility) + if (useEmissionIntensityProp == null || emissionColorLDRProp == null || + emissionIntensityProp == null || emissionIntensityUnitProp == null) + { + using (new EditorGUI.IndentLevelScope(2)) + { + materialEditor.TexturePropertyWithHDRColor(Styles.emissionMap, emissionMapProp, emissionColorProp, false); + } + return; + } + + + // Emission with intensity control + EditorGUI.BeginChangeCheck(); + materialEditor.ShaderProperty(useEmissionIntensityProp, "Use Emission Intensity"); + bool updateEmissionColor = EditorGUI.EndChangeCheck(); + + // Convert HDR -> LDR when switching to intensity mode + if (updateEmissionColor && useEmissionIntensityProp.floatValue > 0.5f) + { + ConvertHDRColorToLDR(emissionColorProp.colorValue, out Color ldr, out float intensity); + emissionColorLDRProp.colorValue = ldr.gamma; + emissionIntensityProp.floatValue = intensity; + } + + // Draw emission controls (indented) + EditorGUI.BeginChangeCheck(); using (new EditorGUI.IndentLevelScope(2)) { - materialEditor.TexturePropertyWithHDRColor(Styles.emissionMap, emissionMapProp, emissionColorProp, false); + if (useEmissionIntensityProp.floatValue == 0) + { + // HDR Color Mode + materialEditor.TexturePropertyWithHDRColor(Styles.emissionMap, emissionMapProp, emissionColorProp, false); + EditorGUILayout.HelpBox("Emission intensity is derived from the HDR color picker in luminance", MessageType.Info, true); + } + else + { + // LDR color + Intensity + materialEditor.TexturePropertySingleLine(Styles.emissionMap, emissionMapProp, emissionColorLDRProp); + DoEmissionIntensityGUI(materialEditor, emissionIntensityProp, emissionIntensityUnitProp); + } + } + + // Update _EmissionColor when properties change + if (EditorGUI.EndChangeCheck() || updateEmissionColor) + { + ValidateEmission(); + } + } + + internal static void DoEmissionIntensityGUI(MaterialEditor materialEditor, MaterialProperty emissionIntensity, MaterialProperty emissionIntensityUnit) + { + const int k_ValueUnitSeparator = 2; + const int k_UnitWidth = 100; + + MaterialEditor.BeginProperty(emissionIntensity); + MaterialEditor.BeginProperty(emissionIntensityUnit); + + bool unitIsMixed = emissionIntensityUnit.hasMixedValue; + bool intensityIsMixed = unitIsMixed || emissionIntensity.hasMixedValue; + + float indent = 15 * EditorGUI.indentLevel; + Rect valueRect = EditorGUILayout.GetControlRect(); + valueRect.width += indent - k_ValueUnitSeparator - k_UnitWidth; + + Rect unitRect = valueRect; + unitRect.x += valueRect.width - indent + k_ValueUnitSeparator; + unitRect.width = k_UnitWidth + .5f; + + EditorGUI.showMixedValue = intensityIsMixed; + EmissionUnits unit = (EmissionUnits)emissionIntensityUnit.floatValue; + + if (unitIsMixed) + { + using (new EditorGUI.DisabledScope(true)) + materialEditor.ShaderProperty(valueRect, emissionIntensity, "Emission Intensity"); + } + else + { + if (!intensityIsMixed && unit == EmissionUnits.EV100) + { + EditorGUI.BeginChangeCheck(); + float evValue = LightUnitUtils.NitsToEv100(emissionIntensity.floatValue); + evValue = EditorGUI.FloatField(valueRect, "Emission Intensity", evValue); + if (EditorGUI.EndChangeCheck()) + { + evValue = Mathf.Clamp(evValue, 0, k_MaxEvValue); + emissionIntensity.floatValue = LightUnitUtils.Ev100ToNits(evValue); + } + } + else + { + EditorGUI.BeginChangeCheck(); + materialEditor.ShaderProperty(valueRect, emissionIntensity, "Emission Intensity"); + if (EditorGUI.EndChangeCheck()) + emissionIntensity.floatValue = Mathf.Clamp(emissionIntensity.floatValue, 0, float.MaxValue); + } + } + + EditorGUI.showMixedValue = emissionIntensityUnit.hasMixedValue; + EditorGUI.BeginChangeCheck(); + var newUnit = (EmissionUnits)EditorGUI.EnumPopup(unitRect, unit); + if (EditorGUI.EndChangeCheck()) + emissionIntensityUnit.floatValue = (float)newUnit; + + EditorGUI.showMixedValue = false; + + MaterialEditor.EndProperty(); + MaterialEditor.EndProperty(); + } + + private static void ConvertHDRColorToLDR(Color hdr, out Color ldr, out float intensity) + { + const float k_MaxByteForOverexposedColor = 191; + + hdr.a = 1.0f; + ldr = hdr; + intensity = 1.0f; + + var maxColorComponent = hdr.maxColorComponent; + if (maxColorComponent != 0f) + { + var scaleFactor = k_MaxByteForOverexposedColor / maxColorComponent; + + ldr.r = Mathf.Min(k_MaxByteForOverexposedColor, scaleFactor * hdr.r) / 255f; + ldr.g = Mathf.Min(k_MaxByteForOverexposedColor, scaleFactor * hdr.g) / 255f; + ldr.b = Mathf.Min(k_MaxByteForOverexposedColor, scaleFactor * hdr.b) / 255f; + + intensity = 255f / scaleFactor; + } + } + + /// + /// Updates the final HDR emission color based on LDR color + intensity settings. + /// Called whenever emission properties change to keep _EmissionColor in sync. + /// + /// The material to update. + protected virtual void UpdateEmissionColor(Material material) + { + if (material == null) + return; + + // Only update if the material has the intensity properties + if (!material.HasProperty(Property.UseEmissionIntensity)) + return; + + float useIntensity = material.GetFloat(Property.UseEmissionIntensity); + + if (useIntensity > 0.5f) + { + // Intensity mode: Calculate HDR color from LDR + intensity + if (material.HasProperty(Property.EmissionColorLDR) && + material.HasProperty(Property.EmissionIntensity) && + material.HasProperty(Property.EmissionIntensityUnit)) + { + Color ldrColor = material.GetColor(Property.EmissionColorLDR); + float intensity = material.GetFloat(Property.EmissionIntensity); + + // Calculate final HDR color: LDR.linear × intensity + Color hdrColor = ldrColor.linear * intensity; + hdrColor.a = 1.0f; + + material.SetColor("_EmissionColor", hdrColor); + } + } + // else: HDR mode - _EmissionColor is set directly by user, don't touch it + } + + /// + /// Validates and updates emission properties for all selected materials. + /// Ensures _EmissionColor stays in sync with LDR + intensity settings. + /// + protected void ValidateEmission() + { + if (materialEditor == null || materialEditor.targets == null) + return; + + foreach (var obj in materialEditor.targets) + { + if (obj is Material material) + { + UpdateEmissionColor(material); + } } } diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/ShaderGraphUnlitGUI.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/ShaderGraphUnlitGUI.cs index 792a59144af..fa0c51df2d7 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/ShaderGraphUnlitGUI.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/ShaderGraphUnlitGUI.cs @@ -43,6 +43,7 @@ public static void UpdateMaterial(Material material, MaterialUpdateType updateTy public override void ValidateMaterial(Material material) { UpdateMaterial(material, MaterialUpdateType.ModifiedMaterial); + UpdateEmissionColor(material); } // material main surface inputs diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/LitShader.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/LitShader.cs index d5b90039cdc..cad5ccf9800 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/LitShader.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/LitShader.cs @@ -29,6 +29,7 @@ public override void FindProperties(MaterialProperty[] properties) public override void ValidateMaterial(Material material) { SetMaterialKeywords(material, LitGUI.SetMaterialKeywords, LitDetailGUI.SetMaterialKeywords); + UpdateEmissionColor(material); } // material main surface options diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/ParticlesLitShader.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/ParticlesLitShader.cs index 9e8df9a249d..4bb177a2d7c 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/ParticlesLitShader.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/ParticlesLitShader.cs @@ -23,6 +23,7 @@ public override void FindProperties(MaterialProperty[] properties) public override void ValidateMaterial(Material material) { SetMaterialKeywords(material, LitGUI.SetMaterialKeywords, ParticleGUI.SetMaterialKeywords); + UpdateEmissionColor(material); } public override void DrawSurfaceOptions(Material material) diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/ParticlesSimpleLitShader.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/ParticlesSimpleLitShader.cs index 28299ec6eb3..f241914d6cb 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/ParticlesSimpleLitShader.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/ParticlesSimpleLitShader.cs @@ -23,6 +23,7 @@ public override void FindProperties(MaterialProperty[] properties) public override void ValidateMaterial(Material material) { SetMaterialKeywords(material, SimpleLitGUI.SetMaterialKeywords, ParticleGUI.SetMaterialKeywords); + UpdateEmissionColor(material); } public override void DrawSurfaceOptions(Material material) diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/ParticlesUnlitShader.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/ParticlesUnlitShader.cs index c8c0f0061f1..8d7628dbb7c 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/ParticlesUnlitShader.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/ParticlesUnlitShader.cs @@ -23,6 +23,7 @@ public override void FindProperties(MaterialProperty[] properties) public override void ValidateMaterial(Material material) { SetMaterialKeywords(material, null, ParticleGUI.SetMaterialKeywords); + UpdateEmissionColor(material); } public override void DrawSurfaceOptions(Material material) diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/SimpleLitShader.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/SimpleLitShader.cs index 4bbf57bf2d8..d3aade45406 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/SimpleLitShader.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/SimpleLitShader.cs @@ -19,6 +19,7 @@ public override void FindProperties(MaterialProperty[] properties) public override void ValidateMaterial(Material material) { SetMaterialKeywords(material, SimpleLitGUI.SetMaterialKeywords); + UpdateEmissionColor(material); } // material main surface options diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Filter/FilterFunctionDefinitionGenerator.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Filter/FilterFunctionDefinitionGenerator.cs index cc598942531..aaeb2e03279 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Filter/FilterFunctionDefinitionGenerator.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Filter/FilterFunctionDefinitionGenerator.cs @@ -84,35 +84,22 @@ internal static FilterFunctionDefinition Generate(GraphData graph, Material mate var bindingsArray = bindings.ToArray(); + // The pass of many elements draws in one instanced draw, each element with its own parameters + material.enableInstancing = true; + var definition = ScriptableObject.CreateInstance(); definition.name = filterName; definition.filterName = filterName; definition.parameters = parameters.ToArray(); definition.passes = new[] { + // No settings callback: a pass with one draws one element at a time. UI Toolkit writes each binding's + // parameter itself, converted to the pass's color space. new PostProcessingPass { material = material, passIndex = 0, parameterBindings = bindingsArray, - // parameterBindings alone is metadata; only this callback pushes values at runtime. - applySettingsCallback = (mpb, context) => - { - var func = context.filterFunction; - foreach (var binding in bindingsArray) - { - // Missing parameters keep the material's own defaults. - if (binding.index >= func.parameterCount) - continue; - - var param = func.parameters[binding.index]; - if (param.type == FilterParameterType.Color) - // SetColor converts to the active color space, wrong for a gamma-reading pass. - mpb.SetVector(binding.name, context.readsGamma ? (Vector4)param.colorValue : (Vector4)param.colorValue.linear); - else - mpb.SetFloat(binding.name, param.floatValue); - } - }, readMargins = readMargins, writeMargins = writeMargins, } diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Filter/FilterInputNode.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Filter/FilterInputNode.cs index 9de8582153b..f437ccc86c1 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Filter/FilterInputNode.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Filter/FilterInputNode.cs @@ -6,7 +6,7 @@ namespace UnityEditor.Rendering.Universal.ShaderGraph { - // Atlas samples directly; Local remaps 0-1 UVs into the atlas rect (unity_uie_UVRect) first. + // Atlas samples directly; Local remaps 0-1 UVs into the atlas rect (GetFilterUVRect) first. enum FilterUVSpace { Atlas, @@ -87,7 +87,7 @@ static string Unity_FilterInput_Local( #if defined(SHADERGRAPH_PREVIEW) || defined(SHADERGRAPH_PREVIEW_MAIN) " + kPreviewCheckerboard + @" #else - float4 uvRect = unity_uie_UVRect[0]; + float4 uvRect = GetFilterUVRect(0); // Distortion pushing UV outside 0-1 would read a neighboring element's atlas region, whose // contents vary per platform; the half-texel inset keeps the bilinear taps inside the rect too. float2 halfTexel = 0.5 * _MainTex_TexelSize.xy; @@ -101,7 +101,8 @@ static string Unity_FilterInput_Local( } } - // Surfaces _MainTex_TexelSize for aspect-correct local-space math. + // The texel size of the filtered area, the local 0-1 space of Normalize Filter UV: (1 / width, 1 / height, width, + // height). The filter margins inflate the area and clipping can cut it. _MainTex_TexelSize is the whole atlas page. [SubTargetFilter(typeof(UniversalFilterSubTarget))] [Title("Input", "Filter", "Filter Texel Size")] sealed class FilterTexelSizeNode : CodeFunctionNode @@ -109,7 +110,7 @@ sealed class FilterTexelSizeNode : CodeFunctionNode public FilterTexelSizeNode() { name = "Filter Texel Size"; - synonyms = new string[] { "main tex texel size", "atlas texel size" }; + synonyms = new string[] { "filtered area size", "local texel size" }; UpdateNodeAfterDeserialization(); } @@ -131,7 +132,8 @@ static string Unity_FilterTexelSize( // 1x1 is a neutral preview stand-in. Out = float4(1, 1, 1, 1); #else - Out = _MainTex_TexelSize; + float2 size = GetFilterUVRect(0).zw * _MainTex_TexelSize.zw; + Out = float4(1.0 / size, size); #endif } "; diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Filter/FilterProperties.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Filter/FilterProperties.cs index a7f13688dab..e30e71ec9a8 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Filter/FilterProperties.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Filter/FilterProperties.cs @@ -1,3 +1,5 @@ +using System; +using System.Collections.Generic; using UnityEditor.ShaderGraph; using UnityEditor.ShaderGraph.Internal; @@ -10,4 +12,77 @@ static class FilterProperties { public static readonly Texture2DShaderProperty MainTex = CanvasProperties.MainTex; } + + // Declares the filter parameters a second time, per instance, in the INSTANCING_ON variant, where UI Toolkit draws the + // pass of many elements together. The graph code keeps reading the parameters by name: the defines redirect each name + // to the instance, as URP's hand-written shaders do for DOTS instancing. Shader Graph's own Hybrid Per Instance + // declaration can't be used: it is a setting of each property, which a filter graph doesn't get by default. + sealed class FilterInstancedParametersProperty : AbstractShaderProperty + { + const string k_BufferName = "UIEFilterParameters"; + + readonly List m_GraphProperties; + + public FilterInstancedParametersProperty(IEnumerable graphProperties) + { + m_GraphProperties = new List(graphProperties); + displayName = k_BufferName; + overrideReferenceName = k_BufferName; + generatePropertyBlock = false; + overrideHLSLDeclaration = true; + hlslDeclarationOverride = HLSLDeclaration.Global; + } + + public override PropertyType propertyType => PropertyType.Float; + internal override ConcreteSlotValueType concreteShaderValueType => ConcreteSlotValueType.Vector1; + internal override bool isExposable => false; + internal override bool isRenamable => false; + + internal override void ForeachHLSLProperty(GenerationMode mode, Action action) + { + var parameters = new List<(string type, string name)>(); + foreach (var property in m_GraphProperties) + { + // Another declaration (Hybrid Per Instance, Global) keeps Shader Graph's own access macro, which a define would break + if (!property.isExposed || property.ResolveHLSLDeclaration(mode) != HLSLDeclaration.UnityPerMaterial) + continue; + + var type = GetInstancedType(property); + if (type != null) + parameters.Add((type, property.referenceName)); + } + + if (parameters.Count == 0) + return; + + var declaration = new HLSLProperty(HLSLType._CUSTOM, k_BufferName, HLSLDeclaration.Global); + declaration.customDeclaration = builder => + { + builder.AppendLine("#if defined(UNITY_INSTANCING_ENABLED)"); + builder.AppendLine($"UNITY_INSTANCING_BUFFER_START({k_BufferName})"); + foreach (var (type, name) in parameters) + builder.AppendLine($" UNITY_DEFINE_INSTANCED_PROP({type}, {name})"); + builder.AppendLine($"UNITY_INSTANCING_BUFFER_END({k_BufferName})"); + foreach (var (_, name) in parameters) + builder.AppendLine($"#define {name} UNITY_ACCESS_INSTANCED_PROP({k_BufferName}, {name})"); + builder.AppendLine("#endif"); + }; + action(declaration); + } + + // Every number a writeParametersCallback can write per element. Textures are set once per draw. + static string GetInstancedType(AbstractShaderProperty property) => property switch + { + Vector1ShaderProperty or BooleanShaderProperty => "float", + Vector2ShaderProperty => "float2", + Vector3ShaderProperty => "float3", + Vector4ShaderProperty or ColorShaderProperty => "float4", + _ => null, + }; + + internal override string GetPropertyAsArgumentString(string precisionString) => string.Empty; + internal override AbstractMaterialNode ToConcreteNode() => null; + internal override PreviewProperty GetPreviewMaterialProperty() => default; + internal override ShaderInput Copy() => new FilterInstancedParametersProperty(m_GraphProperties); + } } diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Filter/FilterStructs.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Filter/FilterStructs.cs index feb5d947d85..be554d89bde 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Filter/FilterStructs.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Filter/FilterStructs.cs @@ -5,17 +5,22 @@ namespace UnityEditor.Rendering.Universal.ShaderGraph // Fullscreen-quad vertex/varying contract for a filter pass: no per-element mesh fields (clip // rect, tint, normal/tangent, packed IDs) like UISubTarget, and no rectIndex like // UnityUIEFilter.cginc's FilterVertexInput -- the atlas rect is always read via - // unity_uie_UVRect[0] (FilterUVRect.hlsl), never per-vertex. + // GetFilterUVRect(0) (UnityUIEFilter.cginc, through FilterShim.hlsl), never per-vertex. internal static class FilterStructs { + // The instanced draw has no vertex buffer: UIEGetFilterVertex builds each quad from SV_VertexID + const string kWithoutInstancing = "!defined(UNITY_INSTANCING_ENABLED)"; + public static FieldDescriptor positionOS = new FieldDescriptor(StructFields.Attributes.name, "positionOS", "", ShaderValueType.Float3, "POSITION", kWithoutInstancing); + public static FieldDescriptor uv0 = new FieldDescriptor(StructFields.Attributes.name, "uv0", "", ShaderValueType.Float4, "TEXCOORD0", kWithoutInstancing); + public static StructDescriptor Attributes = new StructDescriptor() { name = "Attributes", packFields = false, fields = new FieldDescriptor[] { - StructFields.Attributes.positionOS, - StructFields.Attributes.uv0, + positionOS, + uv0, StructFields.Attributes.instanceID, StructFields.Attributes.vertexID, } diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Filter/FilterUVRectNodes.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Filter/FilterUVRectNodes.cs index f36c622302e..96bee3281b0 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Filter/FilterUVRectNodes.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Filter/FilterUVRectNodes.cs @@ -6,7 +6,7 @@ namespace UnityEditor.Rendering.Universal.ShaderGraph { // Companion to Filter Input for filters that manipulate UV before sampling (multi-tap blur, swirl // distortion). Filter Input's UV is already positioned in this element's sub-rect of the shared - // atlas (unity_uie_UVRect, see FilterUVRect.hlsl), so manipulating it directly risks bleeding into + // atlas (GetFilterUVRect in UnityUIEFilter.cginc), so manipulating it directly risks bleeding into // a neighboring element's region once an atlas holds more than one element. This node exposes only // the "normalize to local 0-1 space" half; feed the distorted result into Filter Input's UV socket // with "UV Space" set to Local, which remaps back to atlas space internally (FilterInputNode.cs). @@ -41,7 +41,7 @@ static string Unity_NormalizeFilterUV( // same convention as Filter Input's own preview fallback. Out = UV; #else - float4 uvRect = unity_uie_UVRect[0]; + float4 uvRect = GetFilterUVRect(0); Out = (UV - uvRect.xy) / uvRect.zw; #endif } diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Filter/UniversalFilterSubTarget.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Filter/UniversalFilterSubTarget.cs index b74ac862c1b..eb6ef82e803 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Filter/UniversalFilterSubTarget.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Filter/UniversalFilterSubTarget.cs @@ -58,14 +58,14 @@ ScriptableObject IHasImportArtifact.GetImportArtifact(GraphData graph, Material => FilterFunctionDefinitionGenerator.Generate(graph, material, assetName); static readonly string kFilterPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/FilterPass.hlsl"; - static readonly string kFilterUVRect = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/FilterUVRect.hlsl"; + static readonly string kFilterShim = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/FilterShim.hlsl"; IncludeCollection pregraphIncludes => new IncludeCollection { { CoreIncludes.CorePregraph }, { kInstancing, IncludeLocation.Pregraph }, { CoreIncludes.ShaderGraphPregraph }, - { kFilterUVRect, IncludeLocation.Pregraph }, + { kFilterShim, IncludeLocation.Pregraph }, }; IncludeCollection postgraphIncludes => new IncludeCollection @@ -98,6 +98,10 @@ public override void CollectShaderProperties(PropertyCollector collector, Genera base.CollectShaderProperties(collector, generationMode); CollectRenderStateShaderProperties(collector, generationMode); + + // Previews aren't instanced, and declare every property in UnityPerMaterial + if (!generationMode.IsPreview()) + collector.AddShaderProperty(new FilterInstancedParametersProperty(collector.properties)); } public void CollectRenderStateShaderProperties(PropertyCollector collector, GenerationMode generationMode) @@ -207,18 +211,10 @@ public virtual IncludeCollection SRPPostGraphIncludes() protected virtual DefineCollection GetPassDefines() => new DefineCollection(); - // Same gamma-correction multi_compile as the built-in filter shaders. - static readonly KeywordDescriptor s_OutputLinear = new KeywordDescriptor() - { - displayName = "UIE Output Linear", - referenceName = "_UIE_OUTPUT_LINEAR", - type = KeywordType.Boolean, - definition = KeywordDefinition.MultiCompile, - scope = KeywordScope.Local, - }; - + // No _UIE_OUTPUT_LINEAR keyword: an instanced draw can't switch keywords per element, so FilterPass.hlsl reads + // UIEFilterOutputsLinear(), like the built-in filter shaders. protected virtual KeywordCollection GetPassKeywords() - => new KeywordCollection { s_OutputLinear }; + => new KeywordCollection(); public virtual PassDescriptor GenerateFilterPassDescriptor(bool isSRP) { @@ -368,8 +364,8 @@ static class FilterRequiredFields { StructFields.Varyings.positionCS, StructFields.Varyings.texCoord0, - StructFields.Attributes.positionOS, - StructFields.Attributes.uv0, // the filter's own MainTex UV + FilterStructs.positionOS, + FilterStructs.uv0, // the filter's own MainTex UV StructFields.Attributes.instanceID, StructFields.Attributes.vertexID, }; @@ -403,6 +399,9 @@ static class FilterPragmas {Pragma.Target(ShaderModel.Target35)}, {Pragma.Vertex("vert")}, {Pragma.Fragment("frag")}, + // UI Toolkit draws the pass of many elements together; the quads carry no object matrix + {Pragma.MultiCompileInstancing}, + {Pragma.InstancingOptions(InstancingOptions.NoMatrices)}, }; } #endregion diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/CanvasPass.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/CanvasPass.hlsl index d8c40d75a1f..0f6195c9c44 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/CanvasPass.hlsl +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/CanvasPass.hlsl @@ -77,9 +77,9 @@ Varyings BuildVaryings(Attributes input) float2 pixelSize = output.positionCS.w; pixelSize /= float2(1, 1) * abs(mul((float2x2)UNITY_MATRIX_P, _ScreenParams.xy)); - float4 clampedRect = clamp(_ClipRect, -2e10, 2e10); - float2 maskUV = (input.positionOS.xy - clampedRect.xy) / (clampedRect.zw - clampedRect.xy); - output.texCoord1 = float4(input.positionOS.xy * 2 - clampedRect.xy - clampedRect.zw, 0.25 / (0.25 * float2(_UIMaskSoftnessX, _UIMaskSoftnessY) + abs(pixelSize.xy))); + // Canvas position and pixel size, both linear in the vertex so they interpolate exactly under perspective. + // The fragment turns them into each edge's fade, so tilted masks keep their edges. + output.texCoord1 = float4(input.positionOS.xy, abs(pixelSize.xy)); #else output.texCoord1 = input.uv1; #endif @@ -154,12 +154,13 @@ half4 frag(PackedVaryings packedInput) : SV_TARGET #ifdef UNITY_UI_CLIP_RECT //mask = Uv2 - float2 softness = float2(_UIMaskSoftnessX, _UIMaskSoftnessY); - float2 halfPixelBias = 0.5 - 0.5 * softness * unpacked.texCoord1.zw; - half2 m = saturate((_ClipRect.zw - _ClipRect.xy - abs(unpacked.texCoord1.xy)) * unpacked.texCoord1.zw + halfPixelBias); - half2 hardThreshold = 0.5 + 1e-3 * step(0, unpacked.texCoord1.xy); - m = lerp(m, step(hardThreshold, m), step(softness, 0)); - color.a *= m.x * m.y; + // Each edge fades over its own distance and softness: left, bottom, right, top. + float4 clampedRect = clamp(_ClipRect, -2e10, 2e10); + float4 edgeDistance = float4(unpacked.texCoord1.xy - clampedRect.xy, clampedRect.zw - unpacked.texCoord1.xy); + half4 soft = saturate((edgeDistance + unpacked.texCoord1.zwzw) / (0.5 * _UIMaskSoftness + 2 * unpacked.texCoord1.zwzw)); + half4 hard = half4(edgeDistance.xy >= 0, edgeDistance.zw > 0); + half4 m = _UIMaskSoftness > 0 ? soft : hard; + color.a *= min(m.x, m.z) * min(m.y, m.w); #endif #if _ALPHATEST_ON diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/FilterPass.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/FilterPass.hlsl index 18323cb41ca..b4480661b2e 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/FilterPass.hlsl +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/FilterPass.hlsl @@ -9,12 +9,22 @@ Varyings BuildVaryings(Attributes input) Varyings output = (Varyings)0; UNITY_SETUP_INSTANCE_ID(input); + UNITY_TRANSFER_INSTANCE_ID(input, output); UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output); - output.positionCS = TransformObjectToHClip(input.positionOS); + UIEFilterAppData filterInput = (UIEFilterAppData)0; + UNITY_TRANSFER_INSTANCE_ID(input, filterInput); + #if defined(UNITY_INSTANCING_ENABLED) + filterInput.vertexID = input.vertexID; + #else + filterInput.vertex = float4(input.positionOS, 1); + filterInput.uv = input.uv0.xy; + #endif + UIEFilterVertex filterVertex = UIEGetFilterVertex(filterInput); + output.positionCS = filterVertex.position; #if defined(VARYINGS_NEED_TEXCOORD0) || defined(VARYINGS_DS_NEED_TEXCOORD0) - output.texCoord0 = input.uv0; + output.texCoord0 = float4(filterVertex.uv, 0, 0); #endif return output; @@ -38,10 +48,9 @@ half4 frag(PackedVaryings packedInput) : SV_Target half4 color = half4(surfaceDescription.BaseColor, surfaceDescription.Alpha); - #if _UIE_OUTPUT_LINEAR // SRGBToLinear is SRP Core's equivalent of the legacy GammaToLinearSpace. - color.rgb = SRGBToLinear(color.rgb); - #endif + if (UIEFilterOutputsLinear()) + color.rgb = SRGBToLinear(color.rgb); return color; } diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/FilterShim.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/FilterShim.hlsl new file mode 100644 index 00000000000..5aa0f277d41 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/FilterShim.hlsl @@ -0,0 +1,8 @@ +#ifndef UNITY_FILTER_SHIM_INCLUDED +#define UNITY_FILTER_SHIM_INCLUDED + +// The engine's filter include, as for hand-written filters: it declares what the renderer sets for each quad and the +// functions that read it (GetFilterUVRect...). Pregraph, after the SRP instancing macros and matrices. +#include "UnityUIEFilter.cginc" + +#endif diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/FilterUVRect.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/FilterShim.hlsl.meta similarity index 100% rename from Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/FilterUVRect.hlsl.meta rename to Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/FilterShim.hlsl.meta diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/FilterUVRect.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/FilterUVRect.hlsl deleted file mode 100644 index e1562c9331a..00000000000 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/FilterUVRect.hlsl +++ /dev/null @@ -1,11 +0,0 @@ -#ifndef UNITY_FILTER_UVRECT_INCLUDED -#define UNITY_FILTER_UVRECT_INCLUDED - -// The atlas sub-rect this element's filter input occupies (xy = origin, zw = size, atlas 0-1 UV space). -// Set per draw call via MaterialPropertyBlock (UIRRenderTreeCompositor.cs's s_UVRects) -- the same -// property Shaders/Includes/UnityUIEFilter.cginc declares for hand-authored filters, redeclared here -// since ShaderGraph can't reach that engine-only include. Declared pregraph since NormalizeFilterUVNode -// and Filter Input's Local UV Space reference it directly by name, not through a Slot. -float4 unity_uie_UVRect[1]; - -#endif diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBRForwardPass.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBRForwardPass.hlsl index f213c2b5a31..3f203322974 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBRForwardPass.hlsl +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBRForwardPass.hlsl @@ -2,9 +2,8 @@ #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/DistanceFog.hlsl" #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/LODCrossFade.hlsl" #include "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/VolumetricFogBlendMode.hlsl" -#include "Packages/com.unity.render-pipelines.universal/Shaders/Utils/SurfaceType.hlsl" -void InitializeInputData(Varyings input, SurfaceDescription surfaceDescription, out InputData inputData) +void InitializeInputData(Varyings input, SurfaceDescription surfaceDescription, out InputData inputData, bool isSurfaceTypeTransparent) { inputData = (InputData)0; @@ -28,12 +27,13 @@ void InitializeInputData(Varyings input, SurfaceDescription surfaceDescription, inputData.normalWS = input.normalWS; #endif inputData.normalWS = NormalizeNormalPerPixel(inputData.normalWS); + inputData.geometricNormalWS = input.normalWS; inputData.viewDirectionWS = GetWorldSpaceNormalizeViewDir(input.positionWS); #if USE_VERTEX_SHADOW_COORD_INTERPOLATOR - inputData.shadowCoord = ShadowCoordInterpolatorAvailable() ? input.shadowCoord : TransformWorldToShadowCoord(inputData.positionWS, IsSurfaceTypeTransparent(), input.normalWS); + inputData.shadowCoord = ShadowCoordInterpolatorAvailable() ? input.shadowCoord : TransformWorldToShadowCoord(inputData.positionWS, isSurfaceTypeTransparent, input.normalWS); #else - inputData.shadowCoord = MainLightShadowsAvailable() ? TransformWorldToShadowCoord(inputData.positionWS, IsSurfaceTypeTransparent(), input.normalWS) : float4(0, 0, 0, 0); + inputData.shadowCoord = MainLightShadowsAvailable() ? TransformWorldToShadowCoord(inputData.positionWS, isSurfaceTypeTransparent, input.normalWS) : float4(0, 0, 0, 0); #endif inputData.vertexLighting = input.fogFactorAndVertexLight.yzw; @@ -124,7 +124,7 @@ void frag( LODFadeCrossFade(unpacked.positionCS); InputData inputData; - InitializeInputData(unpacked, surfaceDescription, inputData); + InitializeInputData(unpacked, surfaceDescription, inputData, isSurfaceTypeTransparent); #ifdef VARYINGS_NEED_TEXCOORD0 SETUP_DEBUG_TEXTURE_DATA(inputData, unpacked.texCoord0); #else @@ -169,7 +169,7 @@ void frag( InitializeBakedGIData(unpacked, inputData, isSurfaceTypeTransparent); - URP_LIGHT_ACCUM4 color = UniversalFragmentPBR(inputData, surface, unpacked.normalWS); + URP_LIGHT_ACCUM4 color = UniversalFragmentPBR(inputData, surface); color.rgb = ClampExposed(inputData.preExposureMultiplier * BlendDistanceFog(color.rgb, unpacked.positionCS)); #if defined(_SURFACE_TYPE_TRANSPARENT) && defined(_TRANSPARENT_RECEIVE_FOG) color.rgb = MixVolumetricFog(color.rgb, color.a, VolumetricFogBlendModeFromDefines(), false, unpacked.positionCS); diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBRGBufferPass.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBRGBufferPass.hlsl index 0da48983f13..15294034af2 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBRGBufferPass.hlsl +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBRGBufferPass.hlsl @@ -1,8 +1,7 @@ #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/LODCrossFade.hlsl" -#include "Packages/com.unity.render-pipelines.universal/Shaders/Utils/SurfaceType.hlsl" -void InitializeInputData(Varyings input, SurfaceDescription surfaceDescription, out InputData inputData) +void InitializeInputData(Varyings input, SurfaceDescription surfaceDescription, out InputData inputData, bool isSurfaceTypeTransparent) { inputData = (InputData)0; @@ -28,7 +27,7 @@ void InitializeInputData(Varyings input, SurfaceDescription surfaceDescription, inputData.normalWS = NormalizeNormalPerPixel(inputData.normalWS); inputData.viewDirectionWS = GetWorldSpaceNormalizeViewDir(input.positionWS); - inputData.shadowCoord = MainLightShadowsAvailable() ? TransformWorldToShadowCoord(inputData.positionWS, IsSurfaceTypeTransparent(), input.normalWS) : float4(0, 0, 0, 0); + inputData.shadowCoord = MainLightShadowsAvailable() ? TransformWorldToShadowCoord(inputData.positionWS, isSurfaceTypeTransparent, input.normalWS) : float4(0, 0, 0, 0); inputData.vertexLighting = input.fogFactorAndVertexLight.yzw; @@ -93,6 +92,12 @@ GBufferFragOutput frag(PackedVaryings packedInput) UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked); SurfaceDescription surfaceDescription = BuildSurfaceDescription(unpacked); + #if defined(_SURFACE_TYPE_TRANSPARENT) + bool isSurfaceTypeTransparent = true; + #else + bool isSurfaceTypeTransparent = false; + #endif + #if defined(_ALPHATEST_ON) half alpha = surfaceDescription.Alpha; clip(alpha - surfaceDescription.AlphaClipThreshold); @@ -105,7 +110,7 @@ GBufferFragOutput frag(PackedVaryings packedInput) LODFadeCrossFade(unpacked.positionCS); InputData inputData; - InitializeInputData(unpacked, surfaceDescription, inputData); + InitializeInputData(unpacked, surfaceDescription, inputData, isSurfaceTypeTransparent); #ifdef VARYINGS_NEED_TEXCOORD0 SETUP_DEBUG_TEXTURE_DATA(inputData, unpacked.texCoord0); #else diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/ShaderPassDecal.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/ShaderPassDecal.hlsl index 50a1351af25..497392a89f1 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/ShaderPassDecal.hlsl +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/ShaderPassDecal.hlsl @@ -76,6 +76,7 @@ void InitializeInputData(Varyings input, float3 positionWS, half3 normalWS, half inputData.positionWS = positionWS; inputData.positionCS = input.positionCS; inputData.normalWS = normalWS; + inputData.geometricNormalWS = normalWS; inputData.viewDirectionWS = viewDirectionWS; inputData.preExposureMultiplier = GetPreExposureMultiplier(); @@ -345,7 +346,7 @@ void Frag(PackedVaryings packedInput, SurfaceData surface = (SurfaceData)0; GetSurface(surfaceData, surface); - URP_LIGHT_ACCUM4 color = UniversalFragmentPBR(inputData, surface, surfaceData.normalWS.xyz); + URP_LIGHT_ACCUM4 color = UniversalFragmentPBR(inputData, surface); float linearEyeDepth = dot(GetViewForwardDir(), positionWS - GetCameraPositionWS()); color.rgb = ClampExposed(inputData.preExposureMultiplier * BlendDistanceFogFromEyeDepth(color.rgb, linearEyeDepth)); diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SixWayForwardPass.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SixWayForwardPass.hlsl index 47f88776694..5f5a5302647 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SixWayForwardPass.hlsl +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SixWayForwardPass.hlsl @@ -1,9 +1,8 @@ #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/DistanceFog.hlsl" #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/LODCrossFade.hlsl" #include "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/VolumetricFogBlendMode.hlsl" -#include "Packages/com.unity.render-pipelines.universal/Shaders/Utils/SurfaceType.hlsl" -void InitializeInputData(Varyings input, bool frontFace, out InputData inputData, out float3 geometricNormalWS) +void InitializeInputData(Varyings input, bool frontFace, out InputData inputData, bool isSurfaceTypeTransparent) { inputData = (InputData)0; @@ -20,14 +19,14 @@ void InitializeInputData(Varyings input, bool frontFace, out InputData inputData inputData.viewDirectionWS = GetWorldSpaceNormalizeViewDir(input.positionWS); - geometricNormalWS = signNormal * input.normalWS; + inputData.geometricNormalWS = signNormal * input.normalWS; #if USE_VERTEX_SHADOW_COORD_INTERPOLATOR // The interpolated shadow coord biases along the front-face normal, which points the wrong way on back faces inputData.shadowCoord = (ShadowCoordInterpolatorAvailable() && frontFace) ? input.shadowCoord - : TransformWorldToShadowCoord(inputData.positionWS, IsSurfaceTypeTransparent(), geometricNormalWS); + : TransformWorldToShadowCoord(inputData.positionWS, isSurfaceTypeTransparent, inputData.geometricNormalWS); #else - inputData.shadowCoord = MainLightShadowsAvailable() ? TransformWorldToShadowCoord(inputData.positionWS, IsSurfaceTypeTransparent(), geometricNormalWS) : float4(0, 0, 0, 0); + inputData.shadowCoord = MainLightShadowsAvailable() ? TransformWorldToShadowCoord(inputData.positionWS, isSurfaceTypeTransparent, inputData.geometricNormalWS) : float4(0, 0, 0, 0); #endif inputData.vertexLighting = input.fogFactorAndVertexLight.yzw; @@ -92,8 +91,7 @@ void frag( LODFadeCrossFade(unpacked.positionCS); InputData inputData; - float3 geometricNormalWS; - InitializeInputData(unpacked, frontFace, inputData, geometricNormalWS); + InitializeInputData(unpacked, frontFace, inputData, isSurfaceTypeTransparent); #ifdef VARYINGS_NEED_TEXCOORD0 SETUP_DEBUG_TEXTURE_DATA(inputData, unpacked.texCoord0); @@ -117,7 +115,7 @@ void frag( surfaceData.absorptionRange = INV_PI + saturate(surfaceDescription.AbsorptionStrength) * (1 - INV_PI); #endif - URP_LIGHT_ACCUM4 color = UniversalFragmentSixWay(inputData, surfaceData, geometricNormalWS); + URP_LIGHT_ACCUM4 color = UniversalFragmentSixWay(inputData, surfaceData); color.rgb = ClampExposed(inputData.preExposureMultiplier * BlendDistanceFog(color.rgb, unpacked.positionCS)); #if defined(_SURFACE_TYPE_TRANSPARENT) && defined(_TRANSPARENT_RECEIVE_FOG) color.rgb = MixVolumetricFog(color.rgb, color.a, VolumetricFogBlendModeFromDefines(), false, unpacked.positionCS); diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/PBRForwardPass.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/PBRForwardPass.hlsl index 2267de67085..e039263118b 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/PBRForwardPass.hlsl +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/PBRForwardPass.hlsl @@ -2,9 +2,8 @@ #define SG_TERRAIN_PBRFORWARDPASS_INC #include "TerrainVert.hlsl" -#include "Packages/com.unity.render-pipelines.universal/Shaders/Utils/SurfaceType.hlsl" -void InitializeInputData(Varyings input, SurfaceDescription surfaceDescription, out InputData inputData, out half3 geometricNormalWS) +void InitializeInputData(Varyings input, SurfaceDescription surfaceDescription, out InputData inputData, bool isSurfaceTypeTransparent) { inputData = (InputData)0; @@ -12,12 +11,12 @@ void InitializeInputData(Varyings input, SurfaceDescription surfaceDescription, inputData.positionCS = input.positionCS; inputData.preExposureMultiplier = GetPreExposureMultiplier(); - CalculateTerrainNormalWS(input, surfaceDescription, inputData, geometricNormalWS); + CalculateTerrainNormalWS(input, surfaceDescription, inputData); #if USE_VERTEX_SHADOW_COORD_INTERPOLATOR - inputData.shadowCoord = ShadowCoordInterpolatorAvailable() ? input.shadowCoord : TransformWorldToShadowCoord(inputData.positionWS, IsSurfaceTypeTransparent(), geometricNormalWS); + inputData.shadowCoord = ShadowCoordInterpolatorAvailable() ? input.shadowCoord : TransformWorldToShadowCoord(inputData.positionWS, isSurfaceTypeTransparent, inputData.geometricNormalWS); #else - inputData.shadowCoord = MainLightShadowsAvailable() ? TransformWorldToShadowCoord(inputData.positionWS, IsSurfaceTypeTransparent(), geometricNormalWS) : float4(0, 0, 0, 0); + inputData.shadowCoord = MainLightShadowsAvailable() ? TransformWorldToShadowCoord(inputData.positionWS, isSurfaceTypeTransparent, inputData.geometricNormalWS) : float4(0, 0, 0, 0); #endif inputData.vertexLighting = input.fogFactorAndVertexLight.yzw; @@ -91,9 +90,14 @@ void frag(PackedVaryings packedInput, AlphaDiscard(surfaceDescription.Alpha, surfaceDescription.AlphaClipThreshold); #endif + #if defined(_SURFACE_TYPE_TRANSPARENT) + bool isSurfaceTypeTransparent = true; + #else + bool isSurfaceTypeTransparent = false; + #endif + InputData inputData; - half3 geometricNormalWS; - InitializeInputData(unpacked, surfaceDescription, inputData, geometricNormalWS); + InitializeInputData(unpacked, surfaceDescription, inputData, isSurfaceTypeTransparent); SETUP_DEBUG_TEXTURE_DATA(inputData, unpacked.texCoord0.xy); float3 specular = 0; @@ -122,7 +126,7 @@ void frag(PackedVaryings packedInput, ApplyDecalToSurfaceData(unpacked.positionCS, surface, inputData); #endif - URP_LIGHT_ACCUM4 finalColor = UniversalFragmentPBR(inputData, surface, geometricNormalWS); + URP_LIGHT_ACCUM4 finalColor = UniversalFragmentPBR(inputData, surface); SplatmapFinalColor(finalColor, unpacked.positionCS); #ifdef _WRITE_RENDERING_LAYERS diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/PBRGBufferPass.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/PBRGBufferPass.hlsl index 08413b06800..54d35cd6b7f 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/PBRGBufferPass.hlsl +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/PBRGBufferPass.hlsl @@ -2,9 +2,8 @@ #define SG_TERRAIN_PBRGBUFFERPASS_INC #include "TerrainVert.hlsl" -#include "Packages/com.unity.render-pipelines.universal/Shaders/Utils/SurfaceType.hlsl" -void InitializeInputData(Varyings input, SurfaceDescription surfaceDescription, out InputData inputData) +void InitializeInputData(Varyings input, SurfaceDescription surfaceDescription, out InputData inputData, bool isSurfaceTypeTransparent) { inputData = (InputData)0; @@ -13,13 +12,12 @@ void InitializeInputData(Varyings input, SurfaceDescription surfaceDescription, inputData.preExposureMultiplier = GetPreExposureMultiplier(); - half3 geometricNormalWS; - CalculateTerrainNormalWS(input, surfaceDescription, inputData, geometricNormalWS); + CalculateTerrainNormalWS(input, surfaceDescription, inputData); #if USE_VERTEX_SHADOW_COORD_INTERPOLATOR - inputData.shadowCoord = ShadowCoordInterpolatorAvailable() ? input.shadowCoord : TransformWorldToShadowCoord(inputData.positionWS, IsSurfaceTypeTransparent(), geometricNormalWS); + inputData.shadowCoord = ShadowCoordInterpolatorAvailable() ? input.shadowCoord : TransformWorldToShadowCoord(inputData.positionWS, isSurfaceTypeTransparent, inputData.geometricNormalWS); #else - inputData.shadowCoord = MainLightShadowsAvailable() ? TransformWorldToShadowCoord(inputData.positionWS, IsSurfaceTypeTransparent(), geometricNormalWS) : float4(0, 0, 0, 0); + inputData.shadowCoord = MainLightShadowsAvailable() ? TransformWorldToShadowCoord(inputData.positionWS, isSurfaceTypeTransparent, inputData.geometricNormalWS) : float4(0, 0, 0, 0); #endif inputData.vertexLighting = input.fogFactorAndVertexLight.yzw; @@ -94,8 +92,14 @@ GBufferFragOutput frag(PackedVaryings packedInput) half alpha = splatWeight; #endif +#if defined(_SURFACE_TYPE_TRANSPARENT) + bool isSurfaceTypeTransparent = true; +#else + bool isSurfaceTypeTransparent = false; +#endif + InputData inputData; - InitializeInputData(unpacked, surfaceDescription, inputData); + InitializeInputData(unpacked, surfaceDescription, inputData, isSurfaceTypeTransparent); SETUP_DEBUG_TEXTURE_DATA(inputData, unpacked.texCoord0); float3 specular = 0; diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Varyings.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Varyings.hlsl index dc943201b16..d6ae529e161 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Varyings.hlsl +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Varyings.hlsl @@ -1,5 +1,3 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/Utils/SurfaceType.hlsl" - #if (SHADERPASS == SHADERPASS_SHADOWCASTER) // Shadow Casting Light geometric parameters. These variables are used when applying the shadow Normal Bias and are set by UnityEngine.Rendering.Universal.ShadowUtils.SetupShadowCasterConstantBuffer in com.unity.render-pipelines.universal/Runtime/ShadowUtils.cs // For Directional lights, _LightDirection is used when applying shadow Normal Bias. @@ -291,7 +289,12 @@ Varyings BuildVaryings(Attributes input #endif #if defined(VARYINGS_NEED_SHADOW_COORD) && USE_VERTEX_SHADOW_COORD_INTERPOLATOR - output.shadowCoord = ShadowCoordInterpolatorAvailable() ? GetShadowCoord(vertexInput, IsSurfaceTypeTransparent(), normalWS) : float4(0, 0, 0, 0); + #if defined(_SURFACE_TYPE_TRANSPARENT) + bool isSurfaceTypeTransparent = true; + #else + bool isSurfaceTypeTransparent = false; + #endif + output.shadowCoord = ShadowCoordInterpolatorAvailable() ? GetShadowCoord(vertexInput, isSurfaceTypeTransparent, normalWS) : float4(0, 0, 0, 0); #endif #if defined(VARYINGS_NEED_SIX_WAY_DIFFUSE_GI_DATA) diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalDecalSubTarget.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalDecalSubTarget.cs index 8bcd529f76c..9ff1638628c 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalDecalSubTarget.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalDecalSubTarget.cs @@ -1030,10 +1030,12 @@ static class Descriptors { CoreKeywordDescriptors.ReflectionProbeRotation }, { CoreKeywordDescriptors.Exposure }, { CoreKeywordDescriptors.MainLightShadows }, + { CoreKeywordDescriptors.ShadowReceiverNormalBias }, { CoreKeywordDescriptors.AdditionalLights }, { CoreKeywordDescriptors.LightFalloffQuadratic }, { CoreKeywordDescriptors.AdditionalLightShadows }, { CoreKeywordDescriptors.ShadowsSoft }, + { CoreKeywordDescriptors.ShadowsPCSS }, { CoreKeywordDescriptors.LightmapShadowMixing }, { CoreKeywordDescriptors.ShadowsShadowmask }, { CoreKeywordDescriptors.ClusterLightLoop }, @@ -1053,11 +1055,13 @@ static class Descriptors { { CoreKeywordDescriptors.Exposure }, { CoreKeywordDescriptors.MainLightShadows }, + { CoreKeywordDescriptors.ShadowReceiverNormalBias }, { CoreKeywordDescriptors.ScreenSpaceIrradiance }, { CoreKeywordDescriptors.AdditionalLights }, { CoreKeywordDescriptors.LightFalloffQuadratic }, { CoreKeywordDescriptors.AdditionalLightShadows }, { CoreKeywordDescriptors.ShadowsSoft }, + { CoreKeywordDescriptors.ShadowsPCSS }, { CoreKeywordDescriptors.ClusterLightLoop }, { CoreKeywordDescriptors.LightCookies }, { CoreKeywordDescriptors.VolumetricFog }, @@ -1076,6 +1080,7 @@ static class Descriptors { CoreKeywordDescriptors.LightmapBicubicSampling }, { CoreKeywordDescriptors.ReflectionProbeRotation }, { CoreKeywordDescriptors.MainLightShadows }, + { CoreKeywordDescriptors.ShadowReceiverNormalBias }, { CoreKeywordDescriptors.ShadowsSoft }, { CoreKeywordDescriptors.LightmapShadowMixing }, { CoreKeywordDescriptors.ShadowsShadowmask }, @@ -1090,6 +1095,7 @@ static class Descriptors { { CoreKeywordDescriptors.Exposure }, { CoreKeywordDescriptors.MainLightShadows }, + { CoreKeywordDescriptors.ShadowReceiverNormalBias }, { CoreKeywordDescriptors.ShadowsSoft }, { Descriptors.DecalsNormalBlend }, { Descriptors.DecalLayers }, diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalLitSubTarget.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalLitSubTarget.cs index 6a64374662e..44a584a27a3 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalLitSubTarget.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalLitSubTarget.cs @@ -1010,6 +1010,7 @@ internal static class LitKeywords { CoreKeywordDescriptors.LightmapBicubicSampling }, { CoreKeywordDescriptors.ReflectionProbeRotation }, { CoreKeywordDescriptors.MainLightShadows }, + { CoreKeywordDescriptors.ShadowReceiverNormalBias }, { CoreKeywordDescriptors.AdditionalLights }, { CoreKeywordDescriptors.LightFalloffQuadratic }, { CoreKeywordDescriptors.AdditionalLightShadows }, @@ -1017,6 +1018,7 @@ internal static class LitKeywords { CoreKeywordDescriptors.ReflectionProbeBoxProjection }, { CoreKeywordDescriptors.ReflectionProbeAtlas }, { CoreKeywordDescriptors.ShadowsSoft }, + { CoreKeywordDescriptors.ShadowsPCSS }, { CoreKeywordDescriptors.LightmapShadowMixing }, { CoreKeywordDescriptors.ShadowsShadowmask }, { CoreKeywordDescriptors.DBuffer }, @@ -1041,6 +1043,7 @@ internal static class LitKeywords { CoreKeywordDescriptors.LightmapBicubicSampling }, { CoreKeywordDescriptors.ReflectionProbeRotation }, { CoreKeywordDescriptors.MainLightShadows }, + { CoreKeywordDescriptors.ShadowReceiverNormalBias }, { CoreKeywordDescriptors.ReflectionProbeBlending }, { CoreKeywordDescriptors.ReflectionProbeBoxProjection }, { CoreKeywordDescriptors.ShadowsSoft }, diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalSixWaySubTarget.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalSixWaySubTarget.cs index 1dd62d8420c..bbde9e8240a 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalSixWaySubTarget.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalSixWaySubTarget.cs @@ -505,10 +505,12 @@ static class SixWayKeywords { { CoreKeywordDescriptors.Exposure }, { CoreKeywordDescriptors.MainLightShadows }, + { CoreKeywordDescriptors.ShadowReceiverNormalBias }, { CoreKeywordDescriptors.AdditionalLights }, { CoreKeywordDescriptors.LightFalloffQuadratic }, { CoreKeywordDescriptors.AdditionalLightShadows }, { CoreKeywordDescriptors.ShadowsSoft }, + { CoreKeywordDescriptors.ShadowsPCSS }, { CoreKeywordDescriptors.ShadowsShadowmask }, { CoreKeywordDescriptors.LightLayers }, { CoreKeywordDescriptors.DebugDisplay }, diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalTarget.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalTarget.cs index 27c1537e53e..d1d86ba014e 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalTarget.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalTarget.cs @@ -1504,7 +1504,7 @@ public static PassDescriptor ShadowCaster(UniversalTarget target) // Conditional State renderStates = CoreRenderStates.ShadowCaster(target), pragmas = CorePragmas.Instanced, - defines = new DefineCollection(), + defines = new DefineCollection { { CoreKeywordDescriptors.ShadowCasterZClip, 1 } }, keywords = new KeywordCollection { CoreKeywords.ShadowCaster }, includes = new IncludeCollection { CoreIncludes.ShadowCaster }, @@ -2154,6 +2154,7 @@ public static RenderStateCollection ShadowCaster(UniversalTarget target) { { UberSwitchedCullRenderState(target) }, { RenderState.ColorMask("ColorMask 0") }, + { RenderState.ZClip("[_ZClip]") }, }; if (!target.depthStencilPassMask.Has(DepthStencilPassMask.ShadowPass)) @@ -2659,6 +2660,13 @@ static class CoreKeywordDescriptors stages = KeywordShaderStage.Vertex, }; + public static readonly KeywordDescriptor ShadowCasterZClip = new KeywordDescriptor() + { + displayName = "Shadow Caster ZClip", + referenceName = "_SHADOW_CASTER_ZCLIP", + type = KeywordType.Boolean, + }; + public static readonly KeywordDescriptor AutomaticTimeBasedMotionVectors = new KeywordDescriptor() { displayName = "Automatic Time-Based Motion Vectors", @@ -2752,6 +2760,16 @@ static class CoreKeywordDescriptors } }; + public static readonly KeywordDescriptor ShadowsPCSS = new KeywordDescriptor() + { + displayName = "Shadows PCSS", + referenceName = ShaderKeywordStrings.ShadowsPCSS, + type = KeywordType.Boolean, + definition = KeywordDefinition.MultiCompile, + scope = KeywordScope.Global, + stages = KeywordShaderStage.Fragment, + }; + public static readonly KeywordDescriptor LightmapShadowMixing = new KeywordDescriptor() { displayName = "Lightmap Shadow Mixing", @@ -2953,6 +2971,15 @@ static class CoreKeywordDescriptors scope = KeywordScope.Global, }; + public static readonly KeywordDescriptor ShadowReceiverNormalBias = new KeywordDescriptor() + { + displayName = "Shadow Receiver Normal Bias", + referenceName = "_SHADOW_RECEIVER_NORMAL_BIAS", + type = KeywordType.Boolean, + definition = KeywordDefinition.MultiCompile, + scope = KeywordScope.Global, + }; + public static readonly KeywordDescriptor ClusterLightLoop = new KeywordDescriptor() { displayName = "Cluster Light Loop", diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalTerrainLitSubTarget.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalTerrainLitSubTarget.cs index 5164e3e6663..696e14af36c 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalTerrainLitSubTarget.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalTerrainLitSubTarget.cs @@ -943,7 +943,7 @@ public static PassDescriptor ShadowCaster(UniversalTarget target) // Conditional State renderStates = CoreRenderStates.ShadowCaster(target), pragmas = TerrainCorePragmas.Instanced, - defines = new DefineCollection(), + defines = new DefineCollection { { CoreKeywordDescriptors.ShadowCasterZClip, 1 } }, keywords = new KeywordCollection() { CoreKeywords.ShadowCaster, }, includes = TerrainCoreIncludes.ShadowCaster, @@ -1445,12 +1445,14 @@ static class TerrainLitKeywords { CoreKeywordDescriptors.DynamicLightmap }, { CoreKeywordDescriptors.DirectionalLightmapCombined }, { CoreKeywordDescriptors.MainLightShadows }, + { CoreKeywordDescriptors.ShadowReceiverNormalBias }, { CoreKeywordDescriptors.AdditionalLights }, { CoreKeywordDescriptors.LightFalloffQuadratic }, { CoreKeywordDescriptors.AdditionalLightShadows }, { CoreKeywordDescriptors.ReflectionProbeBlending }, { CoreKeywordDescriptors.ReflectionProbeBoxProjection }, { CoreKeywordDescriptors.ShadowsSoft }, + { CoreKeywordDescriptors.ShadowsPCSS }, { CoreKeywordDescriptors.LightmapShadowMixing }, { CoreKeywordDescriptors.ShadowsShadowmask }, { CoreKeywordDescriptors.ClusterLightLoop }, @@ -1468,6 +1470,7 @@ static class TerrainLitKeywords { CoreKeywordDescriptors.DynamicLightmap }, { CoreKeywordDescriptors.DirectionalLightmapCombined }, { CoreKeywordDescriptors.MainLightShadows }, + { CoreKeywordDescriptors.ShadowReceiverNormalBias }, { CoreKeywordDescriptors.ShadowsSoft }, { CoreKeywordDescriptors.LightmapShadowMixing }, { CoreKeywordDescriptors.ShadowsShadowmask }, diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalUnlitSubTarget.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalUnlitSubTarget.cs index b85e3156ff8..a20d88d5bbf 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalUnlitSubTarget.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalUnlitSubTarget.cs @@ -710,6 +710,7 @@ static class UnlitKeywords public static readonly KeywordCollection LightingVariants = new KeywordCollection() { { CoreKeywordDescriptors.MainLightShadows }, + { CoreKeywordDescriptors.ShadowReceiverNormalBias }, { CoreKeywordDescriptors.AdditionalLights }, { CoreKeywordDescriptors.LightFalloffQuadratic }, { CoreKeywordDescriptors.AdditionalLightShadows }, diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/UniversalProperties.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/UniversalProperties.cs index 3bf49719d96..30265983a72 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/UniversalProperties.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/UniversalProperties.cs @@ -71,5 +71,9 @@ internal static class Property // Global Illumination requires some properties to be named specifically: public static readonly string EmissionMap = "_EmissionMap"; public static readonly string EmissionColor = "_EmissionColor"; + public static readonly string UseEmissionIntensity = "_UseEmissionIntensity"; + public static readonly string EmissionColorLDR = "_EmissionColorLDR"; + public static readonly string EmissionIntensity = "_EmissionIntensity"; + public static readonly string EmissionIntensityUnit = "_EmissionIntensityUnit"; } } diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderScriptableStripper.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderScriptableStripper.cs index d3b8aa53db2..abe562907b3 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderScriptableStripper.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderScriptableStripper.cs @@ -162,6 +162,7 @@ public bool IsKeywordDynamic(LocalKeyword keyword) Shader m_CameraMotionBlur = Shader.Find("Hidden/Universal Render Pipeline/CameraMotionBlur"); Shader m_PaniniProjection = Shader.Find("Hidden/Universal Render Pipeline/PaniniProjection"); Shader m_Bloom = Shader.Find("Hidden/Universal Render Pipeline/Bloom"); + Shader m_ScreenSpaceAmbientOcclusion = Shader.Find("Hidden/Universal Render Pipeline/ScreenSpaceAmbientOcclusion"); Shader m_TerrainLit = Shader.Find("Universal Render Pipeline/Terrain/Lit"); Shader m_TerrainLitAddPass = Shader.Find("Hidden/Universal Render Pipeline/Terrain/Lit (Add Pass)"); Shader m_TerrainLitBasePass = Shader.Find("Hidden/Universal Render Pipeline/Terrain/Lit (Base Pass)"); @@ -188,6 +189,7 @@ public bool IsKeywordDynamic(LocalKeyword keyword) public static readonly string kPassNameXRMotionVectors = "XRMotionVectors"; public static readonly string kPassNameXRUberPost = "UberPostXR"; public static readonly string kPassNameXRFinalPost = "FinalPostXR"; + public static readonly string kPassNameRenderingLayerMask2D = "Rendering Layer Mask"; // Keywords LocalKeyword m_MainLightShadows; @@ -206,6 +208,7 @@ public bool IsKeywordDynamic(LocalKeyword keyword) LocalKeyword m_SoftShadowsLow; LocalKeyword m_SoftShadowsMedium; LocalKeyword m_SoftShadowsHigh; + LocalKeyword m_ShadowsPCSS; LocalKeyword m_MixedLightingSubtractive; LocalKeyword m_LightmapShadowMixing; LocalKeyword m_ShadowsShadowMask; @@ -217,6 +220,11 @@ public bool IsKeywordDynamic(LocalKeyword keyword) LocalKeyword m_ScreenSpaceOcclusion; LocalKeyword m_ScreenSpaceIrradiance; LocalKeyword m_ScreenSpaceReflection; + LocalKeyword m_GTAOMode; + LocalKeyword m_GTAODepthPyramid; + LocalKeyword m_SourceDepthLow; + LocalKeyword m_SourceDepthMedium; + LocalKeyword m_SourceDepthHigh; LocalKeyword m_WriteSmoothness; LocalKeyword m_UseFastSRGBLinearConversion; LocalKeyword m_LightLayers; @@ -241,6 +249,7 @@ public bool IsKeywordDynamic(LocalKeyword keyword) LocalKeyword m_TransparentReceiveFog; LocalKeyword m_SurfaceTypeTransparent; LocalKeyword m_LightFalloffQuadratic; + LocalKeyword m_ShadowReceiverNormalBias; LocalKeyword m_LensDistortion; LocalKeyword m_ChromaticAberration; LocalKeyword m_BloomLQ; @@ -290,6 +299,7 @@ private void InitializeLocalShaderKeywords([DisallowNull] Shader shader) m_SoftShadowsLow = TryGetLocalKeyword(shader, ShaderKeywordStrings.SoftShadowsLow); m_SoftShadowsMedium = TryGetLocalKeyword(shader, ShaderKeywordStrings.SoftShadowsMedium); m_SoftShadowsHigh = TryGetLocalKeyword(shader, ShaderKeywordStrings.SoftShadowsHigh); + m_ShadowsPCSS = TryGetLocalKeyword(shader, ShaderKeywordStrings.ShadowsPCSS); m_MixedLightingSubtractive = TryGetLocalKeyword(shader, ShaderKeywordStrings.MixedLightingSubtractive); m_LightmapShadowMixing = TryGetLocalKeyword(shader, ShaderKeywordStrings.LightmapShadowMixing); m_ShadowsShadowMask = TryGetLocalKeyword(shader, ShaderKeywordStrings.ShadowsShadowMask); @@ -301,6 +311,11 @@ private void InitializeLocalShaderKeywords([DisallowNull] Shader shader) m_ScreenSpaceOcclusion = TryGetLocalKeyword(shader, ShaderKeywordStrings.ScreenSpaceOcclusion); m_ScreenSpaceIrradiance = TryGetLocalKeyword(shader, ShaderKeywordStrings.ScreenSpaceIrradiance); m_ScreenSpaceReflection = TryGetLocalKeyword(shader, ShaderKeywordStrings.ScreenSpaceReflection); + m_GTAOMode = TryGetLocalKeyword(shader, ScreenSpaceAmbientOcclusionKeywords.k_GTAOModeKeyword); + m_GTAODepthPyramid = TryGetLocalKeyword(shader, ScreenSpaceAmbientOcclusionKeywords.k_GTAODepthPyramidKeyword); + m_SourceDepthLow = TryGetLocalKeyword(shader, ScreenSpaceAmbientOcclusionKeywords.k_SourceDepthLowKeyword); + m_SourceDepthMedium = TryGetLocalKeyword(shader, ScreenSpaceAmbientOcclusionKeywords.k_SourceDepthMediumKeyword); + m_SourceDepthHigh = TryGetLocalKeyword(shader, ScreenSpaceAmbientOcclusionKeywords.k_SourceDepthHighKeyword); m_WriteSmoothness = TryGetLocalKeyword(shader, ShaderKeywordStrings.WriteSmoothness); m_UseFastSRGBLinearConversion = TryGetLocalKeyword(shader, ShaderKeywordStrings.UseFastSRGBLinearConversion); m_LightLayers = TryGetLocalKeyword(shader, ShaderKeywordStrings.LightLayers); @@ -325,6 +340,7 @@ private void InitializeLocalShaderKeywords([DisallowNull] Shader shader) m_TransparentReceiveFog = TryGetLocalKeyword(shader, ShaderKeywordStrings.TransparentReceiveFog); m_SurfaceTypeTransparent = TryGetLocalKeyword(shader, ShaderKeywordStrings._SURFACE_TYPE_TRANSPARENT); m_LightFalloffQuadratic = TryGetLocalKeyword(shader, ShaderKeywordStrings.LightFalloffQuadratic); + m_ShadowReceiverNormalBias = TryGetLocalKeyword(shader, ShaderKeywordStrings.ShadowReceiverNormalBias); m_DepthAsInputAttachment = TryGetLocalKeyword(shader, ShaderKeywordStrings.DEPTH_AS_INPUT_ATTACHMENT); m_DepthAsInputAttachmentMSAA = TryGetLocalKeyword(shader, ShaderKeywordStrings.DEPTH_AS_INPUT_ATTACHMENT_MSAA); @@ -506,7 +522,7 @@ internal bool StripUnusedFeatures_BicubicLightmapSampling(ref IShaderScriptableS internal bool StripUnusedFeatures_ReflectionProbeRotation(ref IShaderScriptableStrippingData strippingData) { - if (strippingData.PassHasKeyword(m_ReflectionProbeRotation)) + if (strippingData.PassHasKeyword(m_ReflectionProbeRotation) && !strippingData.IsKeywordDynamic(m_ReflectionProbeRotation)) { bool useRotation = !strippingData.stripReflectionProbeRotationVariants; return useRotation != strippingData.IsKeywordEnabled(m_ReflectionProbeRotation); @@ -647,6 +663,21 @@ internal bool StripUnusedFeatures_SoftShadowsQualityLevels(ref IShaderScriptable m_SoftShadowsHigh, ShaderFeatures.SoftShadowsHigh)); } + internal bool StripUnusedFeatures_PCSS(ref IShaderScriptableStrippingData strippingData, ref ShaderStripTool stripTool) + { + if (stripTool.StripMultiCompileKeepOffVariant(m_ShadowsPCSS, ShaderFeatures.ShadowsPCSS)) + return true; + + // Matches ShadowUtils.SupportsPCSS + if (strippingData.isGLDevice && strippingData.IsKeywordEnabled(m_ShadowsPCSS)) + return true; + + // URP only sets PCSS with the per-light soft shadow keyword + return strippingData.IsKeywordEnabled(m_ShadowsPCSS) + && !strippingData.IsKeywordEnabled(m_SoftShadows) + && !strippingData.IsKeywordDynamic(m_SoftShadows); + } + internal bool StripUnusedFeatures_HDRGrading(ref ShaderStripTool stripTool) { return stripTool.StripMultiCompileKeepOffVariant(m_HdrGrading, ShaderFeatures.HdrGrading); @@ -901,6 +932,11 @@ internal bool StripUnusedFeatures_LightFalloffQuadratic(ref ShaderStripTool stripTool) + { + return stripTool.StripMultiCompile(m_ShadowReceiverNormalBias, ShaderFeatures.ShadowReceiverNormalBias); + } + internal bool StripUnusedFeatures_ProbesVolumes(ref ShaderStripTool stripTool) { return stripTool.StripMultiCompileKeepOffVariant(m_ProbeVolumesL1, ShaderFeatures.ProbeVolumeL1, m_ProbeVolumesL2, ShaderFeatures.ProbeVolumeL2); @@ -1057,6 +1093,9 @@ internal bool StripUnusedFeatures(ref IShaderScriptableStrippingData strippingDa if (StripUnusedFeatures_SoftShadowsQualityLevels(ref strippingData, ref stripTool)) return true; + if (StripUnusedFeatures_PCSS(ref strippingData, ref stripTool)) + return true; + if (StripUnusedFeatures_HDRGrading(ref stripTool)) return true; @@ -1114,6 +1153,9 @@ internal bool StripUnusedFeatures(ref IShaderScriptableStrippingData strippingDa if (StripUnusedFeatures_LightFalloffQuadratic(ref stripTool)) return true; + if (StripUnusedFeatures_ShadowReceiverNormalBias(ref stripTool)) + return true; + if (StripUnusedFeatures_ProbesVolumes(ref stripTool)) return true; @@ -1257,6 +1299,21 @@ internal bool StripInvalidVariants_AdditionalLights(ref IShaderScriptableStrippi return false; } + internal bool StripInvalidVariants_GTAODepthSource(ref IShaderScriptableStrippingData strippingData) + { + if (strippingData.shader != m_ScreenSpaceAmbientOcclusion) + return false; + + // GTAO always reads the normals texture, so it is never paired with a reconstructed normals source. + bool isGTAO = strippingData.IsKeywordEnabled(m_GTAOMode) || + strippingData.IsKeywordEnabled(m_GTAODepthPyramid); + bool reconstructsNormals = strippingData.IsKeywordEnabled(m_SourceDepthLow) || + strippingData.IsKeywordEnabled(m_SourceDepthMedium) || + strippingData.IsKeywordEnabled(m_SourceDepthHigh); + + return isGTAO && reconstructsNormals; + } + internal bool StripInvalidVariants(ref IShaderScriptableStrippingData strippingData) { if (StripInvalidVariants_HDR(ref strippingData)) @@ -1271,6 +1328,9 @@ internal bool StripInvalidVariants(ref IShaderScriptableStrippingData strippingD if (StripInvalidVariants_AdditionalLights(ref strippingData)) return true; + if (StripInvalidVariants_GTAODepthSource(ref strippingData)) + return true; + return false; } @@ -1368,6 +1428,14 @@ internal bool StripUnusedPass_XRFinalPost(ref IShaderScriptableStrippingData str return false; } + internal bool StripUnusedPass_RenderingLayerMask2D(ref IShaderScriptableStrippingData strippingData) + { + // Strip the Sprite Lit and Sprite Custom Lit Rendering Layer Mask pass (including VFX Graph outputs) if rendering layers are disabled + if (strippingData.passName == kPassNameRenderingLayerMask2D && !strippingData.IsShaderFeatureEnabled(ShaderFeatures.LightLayers)) + return true; + return false; + } + internal bool StripUnusedPass(ref IShaderScriptableStrippingData strippingData) { if (StripUnusedPass_2D(ref strippingData)) @@ -1390,6 +1458,9 @@ internal bool StripUnusedPass(ref IShaderScriptableStrippingData strippingData) if (StripUnusedPass_XRFinalPost(ref strippingData)) return true; + + if (StripUnusedPass_RenderingLayerMask2D(ref strippingData)) + return true; return false; } diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Terrain/BuildTerrainSurfaceDescriptionInputs.template.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/BuildTerrainSurfaceDescriptionInputs.template.hlsl index 8665b4c420f..b84098026bb 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/Terrain/BuildTerrainSurfaceDescriptionInputs.template.hlsl +++ b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/BuildTerrainSurfaceDescriptionInputs.template.hlsl @@ -76,7 +76,7 @@ SurfaceDescriptionInputs BuildSurfaceDescriptionInputs(Varyings input) #if SHADERPASS == SHADERPASS_FORWARD || SHADERPASS == SHADERPASS_GBUFFER -void CalculateTerrainNormalWS(Varyings input, inout SurfaceDescription surfaceDescription, inout InputData inputData, out half3 geometricNormalWS) +void CalculateTerrainNormalWS(Varyings input, inout SurfaceDescription surfaceDescription, inout InputData inputData) { $SurfaceDescription.NormalTS: half3 normalTS = surfaceDescription.NormalTS; $SurfaceDescription.NormalOS: half3 NormalOS = surfaceDescription.NormalOS; @@ -84,21 +84,21 @@ void CalculateTerrainNormalWS(Varyings input, inout SurfaceDescription surfaceDe #if defined(_NORMALMAP) && !defined(ENABLE_TERRAIN_PERPIXEL_NORMAL) half3 viewDirWS = half3(input.normalViewDir.w, input.tangentViewDir.w, input.bitangentViewDir.w); - geometricNormalWS = input.normalViewDir.xyz; + inputData.geometricNormalWS = input.normalViewDir.xyz; $SurfaceDescription.NormalTS: inputData.tangentToWorld = half3x3(-input.tangentViewDir.xyz, input.bitangentViewDir.xyz, input.normalViewDir.xyz); $SurfaceDescription.NormalTS: half3 normalWS = TransformTangentToWorld(normalTS, inputData.tangentToWorld); $SurfaceDescription.NormalOS: half3 normalWS = TransformObjectToWorldNormal(NormalOS); #elif defined(ENABLE_TERRAIN_PERPIXEL_NORMAL) half3 viewDirWS = GetWorldSpaceNormalizeViewDir(input.positionWS); - geometricNormalWS = input.normalWS; + inputData.geometricNormalWS = input.normalWS; $SurfaceDescription.NormalTS: half3 tangentWS = cross(GetObjectToWorldMatrix()._13_23_33, input.normalWS); $SurfaceDescription.NormalTS: half3 normalWS = TransformTangentToWorld(normalTS, half3x3(-tangentWS, cross(input.normalWS, tangentWS), input.normalWS)); $SurfaceDescription.NormalOS: half3 normalWS = TransformObjectToWorldNormal(NormalOS); #else half3 viewDirWS = GetWorldSpaceNormalizeViewDir(input.positionWS); - geometricNormalWS = input.normalWS; + inputData.geometricNormalWS = input.normalWS; $SurfaceDescription.NormalTS: half3 normalWS = input.normalWS; $SurfaceDescription.NormalOS: half3 normalWS = TransformObjectToWorldNormal(NormalOS); diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Tools/Converters/AnimationClipConverter/AnimationClipConverter.cs b/Packages/com.unity.render-pipelines.universal/Editor/Tools/Converters/AnimationClipConverter/AnimationClipConverter.cs index f5299093027..435e81442ee 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/Tools/Converters/AnimationClipConverter/AnimationClipConverter.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/Tools/Converters/AnimationClipConverter/AnimationClipConverter.cs @@ -108,96 +108,95 @@ void OnSearchFinish() onScanFinish?.Invoke(results); } - using (UnityEngine.Pool.DictionaryPool>.Get(out var animatorUsingClip)) - using (UnityEngine.Pool.HashSetPool<(string,string)>.Get(out var animatorReferences)) - { - void OnAnimationClipDependenciesSearchFinish() - { - var query = new List<(string, string)>(animatorReferences); - SearchServiceUtils.RunQueuedSearch - ( - SearchServiceUtils.IndexingOptions.DeepSearch, - query, - (item, path) => - { - var unityObject = item.ToObject(); - - if (unityObject == null) - return; - - var gid = GlobalObjectId.GetGlobalObjectIdSlow(unityObject); - int type = gid.identifierType; // 1=Asset, 2=SceneObject - - var assetItem = new RenderPipelineConverterAssetItem(gid.ToString()) - { - name = unityObject.name, - info = path, - }; - - if (animatorUsingClip.TryGetValue(path, out var list)) - { - foreach (var i in list) - { - i.dependencies.Add(assetItem); - } - } - }, - OnSearchFinish // Invoked when all queued searches complete - ); - } + var animatorUsingClip = new Dictionary>(); + var animatorReferences = new HashSet<(string, string)>(); + void OnAnimationClipDependenciesSearchFinish() + { + var query = new List<(string, string)>(animatorReferences); SearchServiceUtils.RunQueuedSearch ( SearchServiceUtils.IndexingOptions.DeepSearch, - GetAnimationClipsSearchList(), - (searchItem, animationClipPath) => + query, + (item, path) => { - // Search callback invoked for each asset that references an animation clip. - // The queued search processes results grouped by animation clip. When we encounter - // a different animationClipPath than the current one, it indicates we've started - // processing dependencies for a new animation clip. - // - // This batching approach efficiently groups all dependencies (prefabs, GameObjects, etc.) - // under their respective animation clips without requiring separate searches per clip. - - // Create a new converter item when we encounter a different animation clip - if (currentAnimationClipItem == null || - !currentAnimationClipItem.assetPath.Equals(animationClipPath)) - { - currentAnimationClipItem = new AnimationClipConverterItem( - GlobalObjectId.GetGlobalObjectIdSlow(AssetDatabase.LoadAssetAtPath(animationClipPath)), - animationClipPath); - assets.Add(currentAnimationClipItem); - } + var unityObject = item.ToObject(); - // Add the dependent asset (prefab, GameObject, etc.) to the current clip's dependency list - var assetItem = new RenderPipelineConverterAssetItem(searchItem.id); - - // If the animation clip is being referenced by a controller, we need to enqueue where this controller is being used - // Handle everything at the end and fill clip dependencies, with controller dependencies. - if (assetItem.assetPath.EndsWith(".controller")) + if (unityObject == null) + return; + + var gid = GlobalObjectId.GetGlobalObjectIdSlow(unityObject); + int type = gid.identifierType; // 1=Asset, 2=SceneObject + + var assetItem = new RenderPipelineConverterAssetItem(gid.ToString()) { - var controller = assetItem.LoadObject(); - string formattedId = $"<$object:{GlobalObjectId.GetGlobalObjectIdSlow(controller)},UnityEngine.Object$>"; - animatorReferences.Add(($"ref={formattedId}", AssetDatabase.GetAssetPath(controller))); + name = unityObject.name, + info = path, + }; - if (!animatorUsingClip.TryGetValue(assetItem.assetPath, out var list)) + if (animatorUsingClip.TryGetValue(path, out var list)) + { + foreach (var i in list) { - list = new (); - animatorUsingClip[assetItem.assetPath] = list; + i.dependencies.Add(assetItem); } - - list.Add(currentAnimationClipItem); - } - else - { - // A game object with an Animation component directly referencing the animation clip - currentAnimationClipItem.dependencies.Add(assetItem); } }, - OnAnimationClipDependenciesSearchFinish // Queue animators + OnSearchFinish // Invoked when all queued searches complete ); } + + SearchServiceUtils.RunQueuedSearch + ( + SearchServiceUtils.IndexingOptions.DeepSearch, + GetAnimationClipsSearchList(), + (searchItem, animationClipPath) => + { + // Search callback invoked for each asset that references an animation clip. + // The queued search processes results grouped by animation clip. When we encounter + // a different animationClipPath than the current one, it indicates we've started + // processing dependencies for a new animation clip. + // + // This batching approach efficiently groups all dependencies (prefabs, GameObjects, etc.) + // under their respective animation clips without requiring separate searches per clip. + + // Create a new converter item when we encounter a different animation clip + if (currentAnimationClipItem == null || + !currentAnimationClipItem.assetPath.Equals(animationClipPath)) + { + currentAnimationClipItem = new AnimationClipConverterItem( + GlobalObjectId.GetGlobalObjectIdSlow(AssetDatabase.LoadAssetAtPath(animationClipPath)), + animationClipPath); + assets.Add(currentAnimationClipItem); + } + + // Add the dependent asset (prefab, GameObject, etc.) to the current clip's dependency list + var assetItem = new RenderPipelineConverterAssetItem(searchItem.id); + + // If the animation clip is being referenced by a controller, we need to enqueue where this controller is being used + // Handle everything at the end and fill clip dependencies, with controller dependencies. + if (assetItem.assetPath.EndsWith(".controller")) + { + var controller = assetItem.LoadObject(); + string formattedId = $"<$object:{GlobalObjectId.GetGlobalObjectIdSlow(controller)},UnityEngine.Object$>"; + animatorReferences.Add(($"ref={formattedId}", AssetDatabase.GetAssetPath(controller))); + + if (!animatorUsingClip.TryGetValue(assetItem.assetPath, out var list)) + { + list = new (); + animatorUsingClip[assetItem.assetPath] = list; + } + + list.Add(currentAnimationClipItem); + } + else + { + // A game object with an Animation component directly referencing the animation clip + currentAnimationClipItem.dependencies.Add(assetItem); + } + }, + OnAnimationClipDependenciesSearchFinish // Queue animators + ); } /// diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Tools/Converters/BuiltInToURP3DReadonlyMaterialConverter.cs b/Packages/com.unity.render-pipelines.universal/Editor/Tools/Converters/BuiltInToURP3DReadonlyMaterialConverter.cs index 14cf7070182..b68119b5d18 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/Tools/Converters/BuiltInToURP3DReadonlyMaterialConverter.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/Tools/Converters/BuiltInToURP3DReadonlyMaterialConverter.cs @@ -28,6 +28,13 @@ public override bool isEnabled } public override string isDisabledMessage => "Converter requires URP with an Universal Renderer. Convert your project to URP to use this converter."; + public override void BeforeConvert() + { + // The replacement materials live in the global settings, which may not exist yet or be out of date + UniversalRenderPipelineGlobalSettings.Ensure(); + base.BeforeConvert(); + } + protected override Dictionary> materialMappings { get diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Tools/Converters/BuiltInToURP3DRenderSettingsConverter.cs b/Packages/com.unity.render-pipelines.universal/Editor/Tools/Converters/BuiltInToURP3DRenderSettingsConverter.cs index 1b3a1d5f8ac..dc10e6fdd52 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/Tools/Converters/BuiltInToURP3DRenderSettingsConverter.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/Tools/Converters/BuiltInToURP3DRenderSettingsConverter.cs @@ -1,4 +1,6 @@ using System; +using System.Collections.Generic; +using Unity.RenderPipelines.Core.Runtime.Shared; using UnityEditor.Rendering.Converter; using UnityEngine; using UnityEngine.Categorization; @@ -42,6 +44,7 @@ protected override RenderPipelineAsset CreateAsset(string name) } } +#pragma warning disable CS0618 // Type or member is obsolete UniversalRendererData CreateUniversalRendererDataAsset(RenderingPath renderingPath, RenderingMode renderingMode) { string path = $"Assets/{UniversalProjectSettings.projectSettingsFolderPath}/Default_{renderingMode}_Renderer.asset"; @@ -58,13 +61,16 @@ UniversalRendererData CreateUniversalRendererDataAsset(RenderingPath renderingPa return asset; } +#pragma warning restore CS0618 void GetRenderers(out ScriptableRendererData[] renderers, out int defaultIndex) { defaultIndex = 0; var targetGrp = BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget); +#pragma warning disable CS0618 // Type or member is obsolete var tier = EditorGraphicsSettings.GetTierSettings(targetGrp, GraphicsTier.Tier3); +#pragma warning restore CS0618 using (UnityEngine.Pool.ListPool.Get(out var tmp)) { @@ -93,8 +99,11 @@ protected override void SetPipelineSettings(RenderPipelineAsset asset) urpAsset.m_DefaultRendererIndex = defaultIndex; var targetGrp = BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget); +#pragma warning disable CS0618 // Type or member is obsolete var tier = EditorGraphicsSettings.GetTierSettings(targetGrp, GraphicsTier.Tier3); +#pragma warning restore CS0618 +#pragma warning disable CS0618 // Type or member is obsolete var pixelLightCount = QualitySettings.pixelLightCount; var shadows = QualitySettings.shadows; var shadowResolution = QualitySettings.shadowResolution; @@ -145,11 +154,54 @@ protected override void SetPipelineSettings(RenderPipelineAsset asset) urpAsset.reflectionProbeBoxProjection = reflectionProbeBoxProjection; // Shadows - urpAsset.shadowDistance = shadowDistance; - urpAsset.shadowCascadeCount = cascadeShadows ? shadowCascadeCount : 1; - urpAsset.cascade2Split = cascadeSplit2; - urpAsset.cascade4Split = cascadeSplit4; urpAsset.supportsSoftShadows = shadows == ShadowQuality.All; + ConvertShadowDistanceAndCascades(urpAsset, shadowDistance, cascadeShadows ? shadowCascadeCount : 1, cascadeSplit2, cascadeSplit4); +#pragma warning restore CS0618 + + WarnIfUsedElsewhere(urpAsset); + } + + static void ConvertShadowDistanceAndCascades(UniversalRenderPipelineAsset urpAsset, float shadowDistance, int cascadeCount, float cascade2Split, Vector3 cascade4Split) + { +#pragma warning disable 618 // Type or member is obsolete + var values = UniversalRenderPipelineGlobalSettings.ShadowSettingsValues.FromCascadeSplitSets( + shadowDistance, cascadeCount, cascade2Split, urpAsset.m_ObsoleteCascade3Split, cascade4Split, urpAsset.m_ObsoleteCascadeBorder); +#pragma warning restore 618 + + var source = urpAsset.volumeProfile; + var profile = UniversalRenderPipelineGlobalSettings.CreateQualityVolumeProfile(urpAsset); + if (profile == null || !UniversalRenderPipelineGlobalSettings.WriteShadowSettings(profile, values) || source == null) + return; + + EditorGraphicsSettings.TryGetRenderPipelineSettingsForPipeline(out var defaultProfileSettings); + string description = UniversalRenderPipelineGlobalSettings.DescribeVolumeProfileCopy( + new List { urpAsset }, profile, source, defaultProfileSettings?.volumeProfile); + string message = $"URP: The pipeline asset {description}, so later changes to '{AssetLinkUtils.AssetLink(source)}' no longer apply to it."; + + var remainingUsers = UniversalRenderPipelineGlobalSettings.FindPipelineAssets().FindAll(other => other.volumeProfile == source); + if (remainingUsers.Count > 0) + message += $" {UniversalRenderPipelineGlobalSettings.DescribeRemainingUsers(source, remainingUsers)}."; + + Debug.LogWarning(message); + } + + static void WarnIfUsedElsewhere(UniversalRenderPipelineAsset urpAsset) + { + var qualityLevels = new List(); + for (int i = 0; i < QualitySettings.names.Length; ++i) + { + if (QualitySettings.GetRenderPipelineAssetAt(i) == urpAsset) + qualityLevels.Add($"'{QualitySettings.names[i]}'"); + } + + string assetLink = AssetLinkUtils.AssetLink(urpAsset); + if (qualityLevels.Count == 1) + Debug.LogWarning($"URP: The pipeline asset '{assetLink}' is also used by the quality level {qualityLevels[0]}, so converting '{assetLink}' changed {qualityLevels[0]} as well."); + else if (qualityLevels.Count > 1) + Debug.LogWarning($"URP: The pipeline asset '{assetLink}' is also used by the quality levels {string.Join(", ", qualityLevels)}, so converting '{assetLink}' changed them as well."); + + if (GraphicsSettings.defaultRenderPipeline == urpAsset) + Debug.LogWarning($"URP: The pipeline asset '{assetLink}' is also used as the default render pipeline in Graphics settings, so converting '{assetLink}' changed it as well."); } #region HelperFunctions @@ -181,6 +233,7 @@ private static int GetEquivalentShadowResolution(int value) } } +#pragma warning disable CS0618 // Type or member is obsolete private RenderingMode GetEquivalentRenderMode(RenderingPath path) { switch (path) @@ -194,6 +247,7 @@ private RenderingMode GetEquivalentRenderMode(RenderingPath path) return RenderingMode.Forward; } } +#pragma warning restore CS0618 #endregion } diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/MaterialUpgraderDefinitions.cs b/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/MaterialUpgraderDefinitions.cs index 38d3480b545..847c8cec10c 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/MaterialUpgraderDefinitions.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/MaterialUpgraderDefinitions.cs @@ -19,6 +19,15 @@ internal static void DisableKeywords(Material material) // LOD fade is now controlled by the render pipeline, and not the individual material, so disable it. material.DisableKeyword("LOD_FADE_CROSSFADE"); } + + internal static void UpdateEmissionMode(Material material) + { + if ((material.globalIlluminationFlags & (MaterialGlobalIlluminationFlags.BakedEmission | MaterialGlobalIlluminationFlags.RealtimeIndirectEmission)) != MaterialGlobalIlluminationFlags.None) + { + material.globalIlluminationFlags |= MaterialGlobalIlluminationFlags.RealtimeDirectEmission; + material.EnableKeyword("_EMISSION"); + } + } } /// @@ -180,7 +189,7 @@ public static void UpdateStandardMaterialKeywords(Material material) material.SetFloat("_AlphaClip", 1.0f); } - UpdateEmissionMode(material); + MaterialUpgradeUtils.UpdateEmissionMode(material); material.SetFloat("_WorkflowMode", 1.0f); CoreUtils.SetKeyword(material, "_OCCLUSIONMAP", material.GetTexture("_OcclusionMap")); @@ -206,6 +215,8 @@ public static void UpdateStandardSpecularMaterialKeywords(Material material) else material.SetFloat("_Smoothness", material.GetFloat("_Glossiness")); + MaterialUpgradeUtils.UpdateEmissionMode(material); + material.SetFloat("_WorkflowMode", 0.0f); CoreUtils.SetKeyword(material, "_OCCLUSIONMAP", material.GetTexture("_OcclusionMap")); CoreUtils.SetKeyword(material, "_METALLICSPECGLOSSMAP", material.GetTexture("_SpecGlossMap")); @@ -254,15 +265,6 @@ static void UpdateSurfaceTypeAndBlendMode(Material material) } } - private static void UpdateEmissionMode(Material material) - { - if ((material.globalIlluminationFlags & (MaterialGlobalIlluminationFlags.BakedEmission | MaterialGlobalIlluminationFlags.RealtimeIndirectEmission)) != MaterialGlobalIlluminationFlags.None) - { - material.globalIlluminationFlags |= MaterialGlobalIlluminationFlags.RealtimeDirectEmission; - material.EnableKeyword("_EMISSION"); - } - } - /// /// Constructor for the StandardUpgrader class. /// @@ -339,15 +341,6 @@ internal static void UpdateMaterialKeywords(Material material) MaterialUpgradeUtils.DisableKeywords(material); } - private static void UpdateEmissionMode(Material material) - { - if ((material.globalIlluminationFlags & (MaterialGlobalIlluminationFlags.BakedEmission | MaterialGlobalIlluminationFlags.RealtimeIndirectEmission)) != MaterialGlobalIlluminationFlags.None) - { - material.globalIlluminationFlags |= MaterialGlobalIlluminationFlags.RealtimeDirectEmission; - material.EnableKeyword("_EMISSION"); - } - } - private static void UpdateMaterialSpecularSource(Material material) { SpecularSource specSource = (SpecularSource)material.GetFloat("_SpecSource"); @@ -440,7 +433,7 @@ public ParticleUpgrader(string oldShaderName) /// public static void UpdateStandardSurface(Material material) { - UpdateEmissionMode(material); + MaterialUpgradeUtils.UpdateEmissionMode(material); UpdateSurfaceBlendModes(material); ParticleGUI.SetupMaterialWithColorMode(material); MaterialUpgradeUtils.DisableKeywords(material); @@ -453,7 +446,7 @@ public static void UpdateStandardSurface(Material material) /// public static void UpdateUnlit(Material material) { - UpdateEmissionMode(material); + MaterialUpgradeUtils.UpdateEmissionMode(material); UpdateSurfaceBlendModes(material); ParticleGUI.SetupMaterialWithColorMode(material); MaterialUpgradeUtils.DisableKeywords(material); @@ -494,15 +487,6 @@ static void FixEmissiveFlags(Material material) } } - private static void UpdateEmissionMode(Material material) - { - if ((material.globalIlluminationFlags & (MaterialGlobalIlluminationFlags.BakedEmission | MaterialGlobalIlluminationFlags.RealtimeIndirectEmission)) != MaterialGlobalIlluminationFlags.None) - { - material.globalIlluminationFlags |= MaterialGlobalIlluminationFlags.RealtimeDirectEmission; - material.EnableKeyword("_EMISSION"); - } - } - /// /// Updates the blending mode properties. /// diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/MaterialUpgraderProviders.cs b/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/MaterialUpgraderProviders.cs index e4a8f4e498c..35494c25124 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/MaterialUpgraderProviders.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/MaterialUpgraderProviders.cs @@ -80,19 +80,6 @@ public IEnumerable GetUpgraders() } } - [SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))] - class UIMaterialUpgraderProviders : IMaterialUpgradersProvider - { - public IEnumerable GetUpgraders() - { - yield return new StandardSimpleLightingUpgrader("UI/Lit/Bumped", SupportedUpgradeParams.diffuseAlphaCutout); - yield return new StandardSimpleLightingUpgrader("UI/Lit/Detail", SupportedUpgradeParams.diffuseAlphaCutout); - yield return new StandardSimpleLightingUpgrader("UI/Lit/Refraction", SupportedUpgradeParams.diffuseAlphaCutout); - yield return new StandardSimpleLightingUpgrader("UI/Lit/Refraction Detail", SupportedUpgradeParams.diffuseAlphaCutout); - yield return new StandardSimpleLightingUpgrader("UI/Lit/Transparent", SupportedUpgradeParams.diffuseAlpha); - } - } - [SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))] class MobileMaterialUpgraderProviders : IMaterialUpgradersProvider { diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Tools/Project Auditor/ReadOnlyShadowSettingsMigrationValidation.cs b/Packages/com.unity.render-pipelines.universal/Editor/Tools/Project Auditor/ReadOnlyShadowSettingsMigrationValidation.cs new file mode 100644 index 00000000000..2fac6f93ef9 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Editor/Tools/Project Auditor/ReadOnlyShadowSettingsMigrationValidation.cs @@ -0,0 +1,51 @@ +using System.Collections.Generic; +using System.ComponentModel; +using Unity.ProjectAuditor.Editor; +using UnityEngine; +using UnityEngine.Rendering; +using UnityEngine.Rendering.Universal; + +namespace UnityEditor.Rendering.Universal.ProjectAuditor +{ + [Category("URP Assets")] + class ReadOnlyShadowSettingsMigrationValidation : IRenderingSettingsAnalyzer + { + internal const string URP0007 = nameof(URP0007); + + public Descriptor Descriptor { get; } = new Descriptor( + URP0007, + "URP: Shadow settings in a read-only package are not migrated to a Shadows volume override", + Areas.Quality | Areas.Upgrade, + "One or more URP Assets in read-only packages have shadow distance and cascade settings that could not be moved to a Shadows volume override. URP no longer uses these settings, so shadows use the values from the volume profiles instead.", + "Update the package, or copy the URP Asset into the Assets folder and use the copy." + ) + { + DefaultSeverity = Severity.Major, + MessageFormat = "URP: Shadow settings are not migrated in read-only {0} in {1}", + }; + + public IEnumerable EnumerateIssues() + { + if (GraphicsSettings.defaultRenderPipeline is UniversalRenderPipelineAsset urpAsset + && UniversalRenderPipelineGlobalSettings.HasUnmigratedShadowSettings(urpAsset, inReadOnlyPackage: true)) + { + yield return new RenderingSettingsIssue(URP0007, assetName: AssetDatabase.GetAssetPath(urpAsset)); + } + + using (UnityEngine.Pool.ListPool<(int level, string assetPath)>.Get(out var tmp)) + { + QualitySettings.ForEach((level, name) => + { + if (QualitySettings.renderPipeline is UniversalRenderPipelineAsset qualityUrpAsset + && UniversalRenderPipelineGlobalSettings.HasUnmigratedShadowSettings(qualityUrpAsset, inReadOnlyPackage: true)) + { + tmp.Add((level, AssetDatabase.GetAssetPath(qualityUrpAsset))); + } + }); + + foreach (var (level, assetPath) in tmp) + yield return new RenderingSettingsIssue(URP0007, level, assetPath); + } + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Tools/Project Auditor/ReadOnlyShadowSettingsMigrationValidation.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/Tools/Project Auditor/ReadOnlyShadowSettingsMigrationValidation.cs.meta new file mode 100644 index 00000000000..2cd34be1c76 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Editor/Tools/Project Auditor/ReadOnlyShadowSettingsMigrationValidation.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e63175ebe772483ab38c24409e8110a9 diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Tools/Project Auditor/ShadowSettingsMigrationValidation.cs b/Packages/com.unity.render-pipelines.universal/Editor/Tools/Project Auditor/ShadowSettingsMigrationValidation.cs new file mode 100644 index 00000000000..3a38201f788 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Editor/Tools/Project Auditor/ShadowSettingsMigrationValidation.cs @@ -0,0 +1,75 @@ +using System.Collections.Generic; +using System.ComponentModel; +using Unity.ProjectAuditor.Editor; +using Unity.ProjectAuditor.Editor.Core; +using UnityEngine; +using UnityEngine.Rendering; +using UnityEngine.Rendering.Universal; + +namespace UnityEditor.Rendering.Universal.ProjectAuditor +{ + [Category("URP Assets")] + class ShadowSettingsMigrationValidation : IRenderingSettingsAnalyzer + { + internal const string URP0006 = nameof(URP0006); + + public Descriptor Descriptor { get; } = new Descriptor( + URP0006, + "URP: Shadow settings are not migrated to a Shadows volume override", + Areas.Quality | Areas.Upgrade, + "One or more URP Assets have shadow distance and cascade settings that were not moved to a Shadows volume override, for example because version control could not check out the asset during the upgrade. URP no longer uses these settings, so shadows use the values from the volume profiles instead.", + "Make the URP Asset editable, then fix the issue to move its settings to a Shadows volume override." + ) + { + DefaultSeverity = Severity.Major, + MessageFormat = "URP: Shadow settings are not migrated in {0} in {1}", + Fixer = FixShadowSettings + }; + + public IEnumerable EnumerateIssues() + { + if (GraphicsSettings.defaultRenderPipeline is UniversalRenderPipelineAsset urpAsset + && UniversalRenderPipelineGlobalSettings.HasUnmigratedShadowSettings(urpAsset, inReadOnlyPackage: false)) + { + yield return new RenderingSettingsIssue(URP0006, assetName: AssetDatabase.GetAssetPath(urpAsset)); + } + + using (UnityEngine.Pool.ListPool<(int level, string assetPath)>.Get(out var tmp)) + { + QualitySettings.ForEach((level, name) => + { + if (QualitySettings.renderPipeline is UniversalRenderPipelineAsset qualityUrpAsset + && UniversalRenderPipelineGlobalSettings.HasUnmigratedShadowSettings(qualityUrpAsset, inReadOnlyPackage: false)) + { + tmp.Add((level, AssetDatabase.GetAssetPath(qualityUrpAsset))); + } + }); + + foreach (var (level, assetPath) in tmp) + yield return new RenderingSettingsIssue(URP0006, level, assetPath); + } + } + + public static bool FixShadowSettings(ReportItem issue, AnalysisParams context) + { + string qualityLevel = issue.CustomProperties?.Length > 0 ? issue.CustomProperties[0] : null; + var issueAsset = string.IsNullOrEmpty(qualityLevel) + ? GraphicsSettings.defaultRenderPipeline + : QualitySettings.GetRenderPipelineAssetAt(int.Parse(qualityLevel)); + return FixShadowSettings(issueAsset as UniversalRenderPipelineAsset); + } + + internal static bool FixShadowSettings(UniversalRenderPipelineAsset issueAsset) + { + var urpAssets = new List(); + foreach (var asset in GraphicsSettings.allConfiguredRenderPipelines) + { + if (asset is UniversalRenderPipelineAsset urpAsset && UniversalRenderPipelineGlobalSettings.HasUnmigratedShadowSettings(urpAsset, inReadOnlyPackage: false)) + urpAssets.Add(urpAsset); + } + + UniversalRenderPipelineGlobalSettings.MigratePendingShadowSettingsToVolumeProfiles(urpAssets); + return issueAsset != null && !issueAsset.m_ShadowSettingsMigrationPending; + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Tools/Project Auditor/ShadowSettingsMigrationValidation.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/Tools/Project Auditor/ShadowSettingsMigrationValidation.cs.meta new file mode 100644 index 00000000000..c880fbc3d53 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Editor/Tools/Project Auditor/ShadowSettingsMigrationValidation.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 1ac6142d01f94c42b3454d8b5f6d4f7c \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Unity.RenderPipelines.Universal.Editor.asmdef b/Packages/com.unity.render-pipelines.universal/Editor/Unity.RenderPipelines.Universal.Editor.asmdef index b5a4ce6b16c..c3a9c9d0851 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/Unity.RenderPipelines.Universal.Editor.asmdef +++ b/Packages/com.unity.render-pipelines.universal/Editor/Unity.RenderPipelines.Universal.Editor.asmdef @@ -24,7 +24,8 @@ "GUID:c49c619b6af2be941af9bcbca2641964", "GUID:b5b1bcf1950c2204f8e3959f64726eab", "GUID:716365d8000d25e4c8621aa2d34a92fa", - "GUID:476f7c6c6dfeed041b063446a926e656" + "GUID:476f7c6c6dfeed041b063446a926e656", + "GUID:ab67fb10353d84448ac887a7367cbda8" ], "includePlatforms": [ "Editor" @@ -51,6 +52,11 @@ "expression": "4.0.1", "define": "XR_MANAGEMENT_4_0_1_OR_NEWER" }, + { + "name": "com.unity.xr.foundation", + "expression": "7.0.0", + "define": "XR_FOUNDATION_7_0_0_OR_NEWER" + }, { "name": "com.unity.visualeffectgraph", "expression": "1.0.0", diff --git a/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineAsset/SerializedUniversalRenderPipelineAsset.cs b/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineAsset/SerializedUniversalRenderPipelineAsset.cs index c4b9d8bda89..973471d586e 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineAsset/SerializedUniversalRenderPipelineAsset.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineAsset/SerializedUniversalRenderPipelineAsset.cs @@ -30,6 +30,7 @@ internal class SerializedUniversalRenderPipelineAsset public SerializedProperty mainLightRenderingModeProp { get; } public SerializedProperty mainLightShadowsSupportedProp { get; } public SerializedProperty mainLightShadowmapResolutionProp { get; } + public SerializedProperty mainLightShadowmapDepthBitsProp { get; } public SerializedProperty shEvalModeProp { get; } @@ -46,6 +47,7 @@ internal class SerializedUniversalRenderPipelineAsset public SerializedProperty additionalLightsPerObjectLimitProp { get; } public SerializedProperty additionalLightShadowsSupportedProp { get; } public SerializedProperty additionalLightShadowmapResolutionProp { get; } + public SerializedProperty additionalLightsShadowmapDepthBitsProp { get; } public SerializedProperty additionalLightsShadowResolutionTierLowProp { get; } public SerializedProperty additionalLightsShadowResolutionTierMediumProp { get; } @@ -58,16 +60,13 @@ internal class SerializedUniversalRenderPipelineAsset public SerializedProperty reflectionProbeBoxProjectionProp { get; } public SerializedProperty reflectionProbeAtlasProp { get; } - public SerializedProperty shadowDistanceProp { get; } - public SerializedProperty shadowCascadeCountProp { get; } - public SerializedProperty shadowCascade2SplitProp { get; } - public SerializedProperty shadowCascade3SplitProp { get; } - public SerializedProperty shadowCascade4SplitProp { get; } - public SerializedProperty shadowCascadeBorderProp { get; } public SerializedProperty shadowDepthBiasProp { get; } public SerializedProperty shadowNormalBiasProp { get; } public SerializedProperty softShadowsSupportedProp { get; } public SerializedProperty softShadowQualityProp { get; } + public SerializedProperty mainLightShadowsPCSSProp { get; } + public SerializedProperty additionalLightShadowsPCSSProp { get; } + public SerializedProperty softShadowKernelRadiusPercentProp { get; } public SerializedProperty conservativeEnclosingSphereProp { get; } public SerializedProperty srpBatcher { get; } @@ -99,8 +98,6 @@ internal class SerializedUniversalRenderPipelineAsset public UniversalRenderPipelineAsset asset { get; } public SerializedObject serializedObject { get; } - public EditorPrefBoolFlags state; - public SerializedUniversalRenderPipelineAsset(SerializedObject serializedObject) { asset = serializedObject.targetObject as UniversalRenderPipelineAsset; @@ -142,11 +139,13 @@ public SerializedUniversalRenderPipelineAsset(SerializedObject serializedObject) mainLightRenderingModeProp = serializedObject.FindProperty("m_MainLightRenderingMode"); mainLightShadowsSupportedProp = serializedObject.FindProperty("m_MainLightShadowsSupported"); mainLightShadowmapResolutionProp = serializedObject.FindProperty("m_MainLightShadowmapResolution"); + mainLightShadowmapDepthBitsProp = serializedObject.FindProperty("m_MainLightShadowmapDepthBits"); additionalLightsRenderingModeProp = serializedObject.FindProperty("m_AdditionalLightsRenderingMode"); additionalLightsPerObjectLimitProp = serializedObject.FindProperty("m_AdditionalLightsPerObjectLimit"); additionalLightShadowsSupportedProp = serializedObject.FindProperty("m_AdditionalLightShadowsSupported"); additionalLightShadowmapResolutionProp = serializedObject.FindProperty("m_AdditionalLightsShadowmapResolution"); + additionalLightsShadowmapDepthBitsProp = serializedObject.FindProperty("m_AdditionalLightsShadowmapDepthBits"); additionalLightsShadowResolutionTierLowProp = serializedObject.FindProperty("m_AdditionalLightsShadowResolutionTierLow"); additionalLightsShadowResolutionTierMediumProp = serializedObject.FindProperty("m_AdditionalLightsShadowResolutionTierMedium"); @@ -159,17 +158,13 @@ public SerializedUniversalRenderPipelineAsset(SerializedObject serializedObject) reflectionProbeBoxProjectionProp = serializedObject.FindProperty("m_ReflectionProbeBoxProjection"); reflectionProbeAtlasProp = serializedObject.FindProperty("m_ReflectionProbeAtlas"); - shadowDistanceProp = serializedObject.FindProperty("m_ShadowDistance"); - - shadowCascadeCountProp = serializedObject.FindProperty("m_ShadowCascadeCount"); - shadowCascade2SplitProp = serializedObject.FindProperty("m_Cascade2Split"); - shadowCascade3SplitProp = serializedObject.FindProperty("m_Cascade3Split"); - shadowCascade4SplitProp = serializedObject.FindProperty("m_Cascade4Split"); - shadowCascadeBorderProp = serializedObject.FindProperty("m_CascadeBorder"); shadowDepthBiasProp = serializedObject.FindProperty("m_ShadowDepthBias"); shadowNormalBiasProp = serializedObject.FindProperty("m_ShadowNormalBias"); softShadowsSupportedProp = serializedObject.FindProperty("m_SoftShadowsSupported"); softShadowQualityProp = serializedObject.FindProperty("m_SoftShadowQuality"); + mainLightShadowsPCSSProp = serializedObject.FindProperty("m_MainLightShadowsPCSS"); + additionalLightShadowsPCSSProp = serializedObject.FindProperty("m_AdditionalLightShadowsPCSS"); + softShadowKernelRadiusPercentProp = serializedObject.FindProperty("m_SoftShadowKernelRadiusPercent"); conservativeEnclosingSphereProp = serializedObject.FindProperty("m_ConservativeEnclosingSphere"); srpBatcher = serializedObject.FindProperty("m_UseSRPBatcher"); @@ -201,9 +196,6 @@ public SerializedUniversalRenderPipelineAsset(SerializedObject serializedObject) #endif UpdateUpscalerOptions(); - - string Key = "Universal_Shadow_Setting_Unit:UI_State"; - state = new EditorPrefBoolFlags(Key); } diff --git a/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineAsset/UniversalRenderPipelineAssetUI.Drawers.cs b/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineAsset/UniversalRenderPipelineAssetUI.Drawers.cs index 23078cdedb6..a8b48a41570 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineAsset/UniversalRenderPipelineAssetUI.Drawers.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineAsset/UniversalRenderPipelineAssetUI.Drawers.cs @@ -96,6 +96,29 @@ static bool ValidateRendererGraphicsAPIsForLightLayers(UniversalRenderPipelineAs return unsupportedGraphicsApisMessage == null; } + internal static bool ValidateGraphicsAPIsForPCSS(out string unsupportedGraphicsApisMessage) + { + unsupportedGraphicsApisMessage = null; + + BuildTarget platform = EditorUserBuildSettings.activeBuildTarget; + GraphicsDeviceType[] graphicsAPIs = PlayerSettings.GetGraphicsAPIs(platform); + + for (int apiIndex = 0; apiIndex < graphicsAPIs.Length; apiIndex++) + { + if (!ShadowUtils.SupportsPCSS(graphicsAPIs[apiIndex])) + { + if (unsupportedGraphicsApisMessage != null) + unsupportedGraphicsApisMessage += ", "; + unsupportedGraphicsApisMessage += graphicsAPIs[apiIndex]; + } + } + + if (unsupportedGraphicsApisMessage != null) + unsupportedGraphicsApisMessage += "."; + + return unsupportedGraphicsApisMessage == null; + } + static bool ValidateRendererGraphicsAPIs(UniversalRenderPipelineAsset pipelineAsset, out string unsupportedGraphicsApisMessage) { // Check the list of Renderers against all Graphics APIs the player is built with. @@ -321,7 +344,7 @@ internal static void DrawXRProjectValidationInfoBox(string message, string butto internal static bool IsAndroidXRTargetted() //Include Quest platform { -#if XR_MANAGEMENT_4_0_1_OR_NEWER +#if XR_MANAGEMENT_4_0_1_OR_NEWER || XR_FOUNDATION_7_0_0_OR_NEWER var buildTargetGroup = BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget); if (buildTargetGroup != BuildTargetGroup.Android) return false; @@ -352,6 +375,8 @@ static void DrawQuality(SerializedUniversalRenderPipelineAsset serialized, Edito serialized.msaa, p => p.intValue != (int)MsaaQuality.Disabled && AnyTileOnlyDeferredRenderer(serialized), Styles.msaaText, MessageType.Warning, Styles.msaaTileOnlyDeferredWarning); + if (serialized.msaa.intValue != (int)MsaaQuality.Disabled && AnyTemporalUpscaler(serialized)) + EditorGUILayout.HelpBox(Styles.msaaTemporalUpscalerWarning, MessageType.Warning, true); EditorGUILayout.PropertyField(serialized.enableLODCrossFadeProp, Styles.enableLODCrossFadeText); EditorGUI.BeginDisabledGroup(!serialized.enableLODCrossFadeProp.boolValue); @@ -594,6 +619,7 @@ static void DrawLighting(SerializedUniversalRenderPipelineAsset serialized, Edit disableGroup |= serialized.mainLightShadowsSupportedProp.hasMultipleDifferentValues || !serialized.mainLightShadowsSupportedProp.boolValue; EditorGUI.BeginDisabledGroup(disableGroup); EditorGUILayout.PropertyField(serialized.mainLightShadowmapResolutionProp, Styles.mainLightShadowmapResolutionText); + EditorGUILayout.IntPopup(serialized.mainLightShadowmapDepthBitsProp, Styles.shadowmapDepthBitsNames, Styles.shadowmapDepthBitsValues, Styles.mainLightShadowmapDepthBits); EditorGUI.EndDisabledGroup(); EditorGUI.indentLevel--; @@ -675,6 +701,7 @@ static void DrawLighting(SerializedUniversalRenderPipelineAsset serialized, Edit disableGroup |= serialized.additionalLightShadowsSupportedProp.hasMultipleDifferentValues || !serialized.additionalLightShadowsSupportedProp.boolValue; EditorGUI.BeginDisabledGroup(disableGroup); EditorGUILayout.PropertyField(serialized.additionalLightShadowmapResolutionProp, Styles.additionalLightsShadowmapResolution); + EditorGUILayout.IntPopup(serialized.additionalLightsShadowmapDepthBitsProp, Styles.shadowmapDepthBitsNames, Styles.shadowmapDepthBitsValues, Styles.additionalLightsShadowmapDepthBits); DrawShadowResolutionTierSettings(serialized, ownerEditor); EditorGUI.EndDisabledGroup(); @@ -783,38 +810,7 @@ internal static GUIContent GetNormalBiasSliderLabel(ShadowNormalBiasMode normalB static void DrawShadows(SerializedUniversalRenderPipelineAsset serialized, Editor ownerEditor) { - using (new EditorGUI.MixedValueScope(serialized.shadowDistanceProp.hasMultipleDifferentValues)) - { - EditorGUI.BeginChangeCheck(); - float newShadowDistance = Mathf.Max(0.0f, EditorGUILayout.FloatField(Styles.shadowDistanceText, serialized.shadowDistanceProp.floatValue)); - if (EditorGUI.EndChangeCheck()) - serialized.shadowDistanceProp.floatValue = newShadowDistance; - } - EditorUtils.Unit unit = EditorUtils.Unit.Metric; - if (serialized.shadowCascadeCountProp.intValue != 0) - { - EditorGUI.BeginChangeCheck(); - unit = (EditorUtils.Unit)EditorGUILayout.EnumPopup(Styles.shadowWorkingUnitText, serialized.state.value); - if (EditorGUI.EndChangeCheck()) - { - serialized.state.value = unit; - } - } - - EditorGUILayout.IntSlider(serialized.shadowCascadeCountProp, UniversalRenderPipelineAsset.k_ShadowCascadeMinCount, UniversalRenderPipelineAsset.k_ShadowCascadeMaxCount, Styles.shadowCascadesText); - - int cascadeCount = serialized.shadowCascadeCountProp.intValue; - EditorGUI.indentLevel++; - - bool useMetric = unit == EditorUtils.Unit.Metric; - float baseMetric = serialized.shadowDistanceProp.floatValue; - int cascadeSplitCount = cascadeCount - 1; - - DrawCascadeSliders(serialized, cascadeSplitCount, useMetric, baseMetric); - - EditorGUI.indentLevel--; - DrawCascades(serialized, cascadeCount, useMetric, baseMetric); - EditorGUI.indentLevel++; + EditorGUILayout.HelpBox(Styles.shadowVolumeSettingsInfo, MessageType.Info); if ((GPUResidentDrawerMode)serialized.gpuResidentDrawerMode.intValue != GPUResidentDrawerMode.Disabled) { @@ -862,10 +858,35 @@ static void DrawShadows(SerializedUniversalRenderPipelineAsset serialized, Edito { EditorGUI.indentLevel++; DrawShadowsSoftShadowQuality(serialized, ownerEditor); + DrawShadowsPCSS(serialized); + EditorGUILayout.PropertyField(serialized.softShadowKernelRadiusPercentProp, Styles.softShadowsKernelRadiusPercent); + if (serialized.mainLightShadowsPCSSProp.boolValue && serialized.softShadowKernelRadiusPercentProp.floatValue > 0.0f) + EditorGUILayout.HelpBox(Styles.softShadowsKernelRadiusPCSSInfo.text, MessageType.Info, true); EditorGUI.indentLevel--; } + } - EditorGUI.indentLevel--; + // PCSS replaces the High quality filter, so its toggles are listed only there + static void DrawShadowsPCSS(SerializedUniversalRenderPipelineAsset serialized) + { + bool isHighQuality = serialized.softShadowQualityProp.hasMultipleDifferentValues || serialized.softShadowQualityProp.intValue >= (int)SoftShadowQuality.High; + + if (isHighQuality) + { + EditorGUILayout.PropertyField(serialized.mainLightShadowsPCSSProp, Styles.mainLightShadowsPCSS); + EditorGUILayout.PropertyField(serialized.additionalLightShadowsPCSSProp, Styles.additionalLightShadowsPCSS); + } + + bool enabledInAsset = serialized.mainLightShadowsPCSSProp.boolValue || serialized.additionalLightShadowsPCSSProp.boolValue; + if (!enabledInAsset) + return; + + // A hidden toggle still applies to lights set to High on their own + if (!isHighQuality) + EditorGUILayout.HelpBox(Styles.pcssEnabledBelowHighQuality.text, MessageType.Info, true); + + if (!ValidateGraphicsAPIsForPCSS(out var unsupportedGraphicsApisMessage)) + EditorGUILayout.HelpBox(Styles.pcssUnsupportedMessage.text + unsupportedGraphicsApisMessage, MessageType.Info, true); } static void DrawShadowsSoftShadowQuality(SerializedUniversalRenderPipelineAsset serialized, Editor ownerEditor) @@ -891,150 +912,6 @@ static void DrawShadowsAdditional(SerializedUniversalRenderPipelineAsset seriali EditorGUILayout.PropertyField(serialized.conservativeEnclosingSphereProp, Styles.conservativeEnclosingSphere); } - static void DrawCascadeSliders(SerializedUniversalRenderPipelineAsset serialized, int splitCount, bool useMetric, float baseMetric) - { - Vector4 shadowCascadeSplit = Vector4.one; - if (splitCount == 3) - shadowCascadeSplit = new Vector4(serialized.shadowCascade4SplitProp.vector3Value.x, serialized.shadowCascade4SplitProp.vector3Value.y, serialized.shadowCascade4SplitProp.vector3Value.z, 1); - else if (splitCount == 2) - shadowCascadeSplit = new Vector4(serialized.shadowCascade3SplitProp.vector2Value.x, serialized.shadowCascade3SplitProp.vector2Value.y, 1, 0); - else if (splitCount == 1) - shadowCascadeSplit = new Vector4(serialized.shadowCascade2SplitProp.floatValue, 1, 0, 0); - - float splitBias = 0.001f; - float invBaseMetric = baseMetric == 0 ? 0 : 1f / baseMetric; - - // Ensure correct split order - shadowCascadeSplit[0] = Mathf.Clamp(shadowCascadeSplit[0], 0f, shadowCascadeSplit[1] - splitBias); - shadowCascadeSplit[1] = Mathf.Clamp(shadowCascadeSplit[1], shadowCascadeSplit[0] + splitBias, shadowCascadeSplit[2] - splitBias); - shadowCascadeSplit[2] = Mathf.Clamp(shadowCascadeSplit[2], shadowCascadeSplit[1] + splitBias, shadowCascadeSplit[3] - splitBias); - - - EditorGUI.BeginChangeCheck(); - for (int i = 0; i < splitCount; ++i) - { - float value = shadowCascadeSplit[i]; - - float minimum = i == 0 ? 0 : shadowCascadeSplit[i - 1] + splitBias; - float maximum = i == splitCount - 1 ? 1 : shadowCascadeSplit[i + 1] - splitBias; - - if (useMetric) - { - float valueMetric = value * baseMetric; - valueMetric = EditorGUILayout.Slider(L10n.TextContent($"Split {i + 1}", "The distance where this cascade ends and the next one starts.", null, null), valueMetric, 0f, baseMetric, null); - - shadowCascadeSplit[i] = Mathf.Clamp(valueMetric * invBaseMetric, minimum, maximum); - } - else - { - float valueProcentage = value * 100f; - valueProcentage = EditorGUILayout.Slider(L10n.TextContent($"Split {i + 1}", "The distance where this cascade ends and the next one starts.", null, null), valueProcentage, 0f, 100f, null); - - shadowCascadeSplit[i] = Mathf.Clamp(valueProcentage * 0.01f, minimum, maximum); - } - } - - if (EditorGUI.EndChangeCheck()) - { - switch (splitCount) - { - case 3: - serialized.shadowCascade4SplitProp.vector3Value = shadowCascadeSplit; - break; - case 2: - serialized.shadowCascade3SplitProp.vector2Value = shadowCascadeSplit; - break; - case 1: - serialized.shadowCascade2SplitProp.floatValue = shadowCascadeSplit.x; - break; - } - } - - var borderValue = serialized.shadowCascadeBorderProp.floatValue; - - EditorGUI.BeginChangeCheck(); - if (useMetric) - { - var lastCascadeSplitSize = splitCount == 0 ? baseMetric : (1.0f - shadowCascadeSplit[splitCount - 1]) * baseMetric; - var invLastCascadeSplitSize = lastCascadeSplitSize == 0 ? 0 : 1f / lastCascadeSplitSize; - float valueMetric = borderValue * lastCascadeSplitSize; - valueMetric = EditorGUILayout.Slider(L10n.TextContent("Last Border", "The distance of the last cascade.", null, null), valueMetric, 0f, lastCascadeSplitSize, null); - - borderValue = valueMetric * invLastCascadeSplitSize; - } - else - { - float valueProcentage = borderValue * 100f; - valueProcentage = EditorGUILayout.Slider(L10n.TextContent("Last Border", "The distance of the last cascade.", null, null), valueProcentage, 0f, 100f, null); - - borderValue = valueProcentage * 0.01f; - } - - if (EditorGUI.EndChangeCheck()) - { - serialized.shadowCascadeBorderProp.floatValue = borderValue; - } - } - - static void DrawCascades(SerializedUniversalRenderPipelineAsset serialized, int cascadeCount, bool useMetric, float baseMetric) - { - var cascades = new ShadowCascadeGUI.Cascade[cascadeCount]; - - Vector3 shadowCascadeSplit = Vector3.zero; - if (cascadeCount == 4) - shadowCascadeSplit = serialized.shadowCascade4SplitProp.vector3Value; - else if (cascadeCount == 3) - shadowCascadeSplit = serialized.shadowCascade3SplitProp.vector2Value; - else if (cascadeCount == 2) - shadowCascadeSplit.x = serialized.shadowCascade2SplitProp.floatValue; - else - shadowCascadeSplit.x = serialized.shadowCascade2SplitProp.floatValue; - - float lastCascadePartitionSplit = 0; - for (int i = 0; i < cascadeCount - 1; ++i) - { - cascades[i] = new ShadowCascadeGUI.Cascade() - { - size = i == 0 ? shadowCascadeSplit[i] : shadowCascadeSplit[i] - lastCascadePartitionSplit, // Calculate the size of cascade - borderSize = 0, - cascadeHandleState = ShadowCascadeGUI.HandleState.Enabled, - borderHandleState = ShadowCascadeGUI.HandleState.Hidden, - }; - lastCascadePartitionSplit = shadowCascadeSplit[i]; - } - - // Last cascade is special - var lastCascade = cascadeCount - 1; - cascades[lastCascade] = new ShadowCascadeGUI.Cascade() - { - size = lastCascade == 0 ? 1.0f : 1 - shadowCascadeSplit[lastCascade - 1], // Calculate the size of cascade - borderSize = serialized.shadowCascadeBorderProp.floatValue, - cascadeHandleState = ShadowCascadeGUI.HandleState.Hidden, - borderHandleState = ShadowCascadeGUI.HandleState.Enabled, - }; - - EditorGUI.BeginChangeCheck(); - ShadowCascadeGUI.DrawCascades(ref cascades, useMetric, baseMetric); - if (EditorGUI.EndChangeCheck()) - { - if (cascadeCount == 4) - serialized.shadowCascade4SplitProp.vector3Value = new Vector3( - cascades[0].size, - cascades[0].size + cascades[1].size, - cascades[0].size + cascades[1].size + cascades[2].size - ); - else if (cascadeCount == 3) - serialized.shadowCascade3SplitProp.vector2Value = new Vector2( - cascades[0].size, - cascades[0].size + cascades[1].size - ); - else if (cascadeCount == 2) - serialized.shadowCascade2SplitProp.floatValue = cascades[0].size; - - serialized.shadowCascadeBorderProp.floatValue = cascades[lastCascade].borderSize; - } - } - static void DrawPostProcessing(SerializedUniversalRenderPipelineAsset serialized, Editor ownerEditor) { EditorGUILayout.PropertyField(serialized.colorGradingMode, Styles.colorGradingMode); @@ -1308,5 +1185,22 @@ static void DisplayTileOnlyHelpBox(string labelText, MessageType messageType = M EditorGUILayout.HelpBox(message, messageType); } + + static bool AnyTemporalUpscaler(SerializedUniversalRenderPipelineAsset serialized) + { + if ((ScalingMode)serialized.scalingMode.enumValueIndex != ScalingMode.Upscaling) + return false; + + for (int i = 0; i < serialized.upscalerPriority.arraySize; ++i) + { + string upscalerId = serialized.upscalerPriority.GetArrayElementAtIndex(i).FindPropertyRelative("upscalerId").stringValue; + IUpscaler upscaler = UniversalRenderPipeline.upscaling?.GetIUpscalerById(upscalerId); + + if (upscaler != null && upscaler.isTemporal) + return true; + } + + return false; + } } } diff --git a/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineAsset/UniversalRenderPipelineAssetUI.Skin.cs b/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineAsset/UniversalRenderPipelineAssetUI.Skin.cs index af047aa920c..4695e451a84 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineAsset/UniversalRenderPipelineAssetUI.Skin.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineAsset/UniversalRenderPipelineAssetUI.Skin.cs @@ -1,4 +1,5 @@ using UnityEngine; +using UnityEngine.Rendering; using UnityEngine.Rendering.Universal; namespace UnityEditor.Rendering.Universal @@ -43,6 +44,7 @@ internal static class Styles public static readonly string xrUpscalingInfo = L10n.Tr("When targeting an XR device, the XR runtime or compositor may provide anti-aliasing and upscaling. In that case this URP upscaler can be redundant or ignored - review your XR provider settings to configure anti-aliasing and upscaling.", null); public static readonly string xrUpscalingInfoButton = L10n.Tr("Open Project Validation", null); public static readonly string stpMobilePlatformWarning = L10n.Tr("STP is selected for use on a mobile platform. STP is only supported on modern compute-capable hardware and its performance overhead may make it impractical on lower-end devices.", null); + public static readonly string msaaTemporalUpscalerWarning = L10n.Tr("Upscaler Priority contains temporal upscalers but MSAA is enabled. Temporal upscalers will not be executed.", null); public static GUIContent scalingModeText = L10n.TextContent("Scaling Mode", "Whether the camera renders below, at, or above the display resolution. This sets the available Render Scale range.", null, null); public static readonly string renderScaleQualityModeInfo = L10n.Tr("Render Scale is ignored because this upscaler's Resolution Mode is set to Quality Mode, which controls the render resolution. Set it to Custom Scaling to drive the render resolution from Render Scale.", null); @@ -60,6 +62,13 @@ internal static class Styles public static GUIContent mainLightRenderingModeText = L10n.TextContent("Main Light", "Main light is the brightest directional light.", null, null); public static GUIContent supportsMainLightShadowsText = L10n.TextContent("Cast Shadows", "If enabled, the main light can be a shadow casting light.", null, null); public static GUIContent mainLightShadowmapResolutionText = L10n.TextContent("Shadow Resolution", "Resolution of the main light shadowmap texture. If cascades are enabled, cascades will be packed into an atlas and this setting controls the maximum shadows atlas resolution.", null, null); + public static GUIContent mainLightShadowmapDepthBits = L10n.TextContent("Precision", "Bit depth of the main light shadow map. 32-bit slightly tightens shadow contact but uses twice the memory and bandwidth of 16-bit.", null, null); + public static GUIContent[] shadowmapDepthBitsNames = + { + L10n.TextContent("16 bit", null, null, null), + L10n.TextContent("32 bit", null, null, null) + }; + public static int[] shadowmapDepthBitsValues = { (int)DepthBits.Depth16, (int)DepthBits.Depth32 }; // Probe volumes public static readonly GUIContent lightProbeSystemContent = L10n.TextContent("Light Probe System", "What system to use for Light Probes.", null, null); @@ -76,6 +85,7 @@ internal static class Styles public static GUIContent perObjectLimit = L10n.TextContent("Per Object Limit", "Maximum amount of additional lights. These lights are sorted and culled per-object.", null, null); public static GUIContent supportsAdditionalShadowsText = L10n.TextContent("Cast Shadows", "If enabled, shadows will be supported for spot and point lights.", null, null); public static GUIContent additionalLightsShadowmapResolution = L10n.TextContent("Shadow Atlas Resolution", "All additional lights are packed into a single shadowmap atlas. This setting controls the atlas size.", null, null); + public static GUIContent additionalLightsShadowmapDepthBits = L10n.TextContent("Precision", "Bit depth of the additional lights shadow map. 32-bit keeps shadows attached to objects that are far from the light but uses twice the memory and bandwidth of 16-bit.", null, null); public static GUIContent additionalLightsShadowResolutionTiers = L10n.TextContent("Shadow Resolution Tiers", $"Additional Lights Shadow Resolution Tiers. Rounded to the next power of two, and clamped to be at least {UniversalAdditionalLightData.AdditionalLightsShadowMinimumResolution}.", null, null); public static GUIContent[] additionalLightsShadowResolutionTierNames = { @@ -99,9 +109,7 @@ internal static class Styles public static GUIContent supportsLightCookies = L10n.TextContent("Light Cookies", "Makes the render pipeline include light cookies Shader Variants in the build.", null, null); // Shadow settings - public static GUIContent shadowWorkingUnitText = L10n.TextContent("Working Unit", "The unit in which Unity measures the shadow cascade distances. The exception is Max Distance, which will still be in meters.", null, null); - public static GUIContent shadowDistanceText = L10n.TextContent("Max Distance", "Maximum shadow rendering distance.", null, null); - public static GUIContent shadowCascadesText = L10n.TextContent("Cascade Count", "Number of cascade splits used for directional shadows.", null, null); + public static readonly string shadowVolumeSettingsInfo = L10n.Tr("Max Distance and shadow cascades are configured with the Shadows volume override.", null); public static GUIContent shadowDepthBias = L10n.TextContent("Depth Bias", "Controls the distance at which the shadows will be pushed away from the light. Useful for avoiding false self-shadowing artifacts. The depth bias mode can be changed in Project Settings > Graphics > URP.", null, null); public static GUIContent shadowSlopeScaleDepthBias = L10n.TextContent("Slope-Scale Depth Bias", "Controls the slope-scaled depth bias applied while rendering the shadow map: surfaces at a grazing angle to the light receive a proportionally larger depth offset. Useful for avoiding false self-shadowing artifacts. The depth bias mode can be changed in Project Settings > Graphics > URP.", null, null); public static GUIContent shadowNormalBiasCaster = L10n.TextContent("Normal Bias", "Controls distance at which the shadow casting surfaces will be shrunk along the surface normal. Useful for avoiding false self-shadowing artifacts. The normal bias mode can be changed in Project Settings > Graphics > URP.", null, null); @@ -110,6 +118,9 @@ internal static class Styles public static GUIContent conservativeEnclosingSphere = L10n.TextContent("Conservative Enclosing Sphere", "Enable this option to improve shadow frustum culling and prevent Unity from excessively culling shadows in the corners of the shadow cascades. Disable this option only for compatibility purposes of existing projects created in previous Unity versions.", null, null); public static GUIContent softShadowsQuality = L10n.TextContent("Quality", "Default shadow quality setting for Lights.", null, null); + public static GUIContent mainLightShadowsPCSS = L10n.TextContent("PCSS (Main Light)", "If enabled, the main directional light uses Percentage-Closer Soft Shadows (PCSS), so the penumbra widens with the distance between the caster and the receiver. Only applies to a light whose resolved soft shadow quality is High.", null, null); + public static GUIContent additionalLightShadowsPCSS = L10n.TextContent("PCSS (Additional Lights)", "If enabled, shadow casting Spot and Point lights use Percentage-Closer Soft Shadows (PCSS), so the penumbra widens with the distance between the caster and the receiver. Only applies to a light whose resolved soft shadow quality is High. This costs more than the filtered soft shadows it replaces.", null, null); + public static GUIContent softShadowsKernelRadiusPercent = L10n.TextContent("Kernel Radius (%)", "Radius of the main light's soft shadow filter, as a percentage of a cascade's shadow map width. The penumbra keeps the same width within a cascade regardless of the shadow resolution. Set to 0 to use each soft shadow quality's fixed kernel.", null, null); public static GUIContent[] softShadowsQualityAssetOptions = { L10n.TextContent(nameof(SoftShadowQuality.Low), null, null, null), @@ -162,6 +173,12 @@ internal static class Styles L10n.TextContent("Some Graphics API(s) in the Player Graphics APIs list are incompatible with Light Layers. Switching to these Graphics APIs at runtime can cause issues: ", null, null, null); public static GUIContent rendererUnsupportedAPIMessage = L10n.TextContent("Some Renderer(s) in the Renderer List are incompatible with the Player Graphics APIs list. Switching to these renderers at runtime can cause issues.\n\n", null, null, null); + public static GUIContent pcssUnsupportedMessage = + L10n.TextContent("Some Graphics API(s) in the Player Graphics APIs list don't support PCSS, so lights use the High soft shadow filter there: ", null, null, null); + public static GUIContent pcssEnabledBelowHighQuality = + L10n.TextContent("PCSS is enabled and still applies to lights whose own Soft Shadows Quality is High. Set Quality to High to change its settings.", null, null, null); + public static GUIContent softShadowsKernelRadiusPCSSInfo = + L10n.TextContent("Kernel Radius is not used while the main light uses PCSS.", null, null, null); public static GUIContent webGL2GpuResidentDrawerErrorMessage = L10n.TextContent("GPU Resident Drawer is not supported with the WebGL2 Graphics API.", null, null, null); public static GUIContent brgShaderStrippingErrorMessage = @@ -173,7 +190,7 @@ internal static class Styles L10n.TextContent("Render Graph must be enabled to use occlusion culling.", null, null, null); public static GUIContent stencilLodCrossFadeWarningMessage = L10n.TextContent("LOD Cross Fade with stencil dithering is not compatible with stencil override in Renderer.", null, null, null); - + public static readonly string formatterTileOnlyMode = L10n.Tr("'{0}' will be skipped because it is incompatible with the enabled 'Tile-Only Mode'. Affected renderers: {1}.", null); public static readonly string tileOnlyModeMaybeMessage = L10n.Tr("'{0}' might be skipped when 'Tile-Only Mode' is enabled. Renderer Features can provide this functionality, so behavior can vary. Affected renderers: {1}.", null); public static readonly string msaaTileOnlyInfo = L10n.Tr("'{0}' is supported in 'Tile-Only Mode'. However, in the Editor and on platforms where the back buffer does not support MSAA, URP forces MSAA to None to keep data in Tile Memory. Affected renderers: {1}.", null); diff --git a/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineLightEditor.cs b/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineLightEditor.cs index c0698311344..3f4ec6c8012 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineLightEditor.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineLightEditor.cs @@ -8,6 +8,7 @@ namespace UnityEditor.Rendering.Universal [CustomEditor(typeof(Light))] [SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))] [CanEditMultipleObjects] + [URPHelpURL("urp/light-component")] class UniversalRenderPipelineLightEditor : LightEditor { UniversalRenderPipelineSerializedLight serializedLight { get; set; } diff --git a/Packages/com.unity.render-pipelines.universal/Editor/VFXGraph/Shaders/Templates/URPDecal/PassGBuffer.template b/Packages/com.unity.render-pipelines.universal/Editor/VFXGraph/Shaders/Templates/URPDecal/PassGBuffer.template index 4834a955e4f..973a36fe6e2 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/VFXGraph/Shaders/Templates/URPDecal/PassGBuffer.template +++ b/Packages/com.unity.render-pipelines.universal/Editor/VFXGraph/Shaders/Templates/URPDecal/PassGBuffer.template @@ -30,6 +30,7 @@ Pass // Keywords #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH #pragma multi_compile _DECAL_NORMAL_BLEND_LOW _DECAL_NORMAL_BLEND_MEDIUM _DECAL_NORMAL_BLEND_HIGH #pragma multi_compile _ _DECAL_LAYERS diff --git a/Packages/com.unity.render-pipelines.universal/Editor/VFXGraph/Shaders/Templates/URPDecal/PassScreenSpace.template b/Packages/com.unity.render-pipelines.universal/Editor/VFXGraph/Shaders/Templates/URPDecal/PassScreenSpace.template index ff05900c4fc..225dd36b9fa 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/VFXGraph/Shaders/Templates/URPDecal/PassScreenSpace.template +++ b/Packages/com.unity.render-pipelines.universal/Editor/VFXGraph/Shaders/Templates/URPDecal/PassScreenSpace.template @@ -20,10 +20,12 @@ Pass // Keywords #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS #pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX _ADDITIONAL_LIGHTS #pragma multi_compile _ _LIGHT_FALLOFF_QUADRATIC #pragma multi_compile_fragment _ _ADDITIONAL_LIGHT_SHADOWS #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH + #pragma multi_compile_fragment _ _SHADOWS_PCSS #pragma multi_compile _ _CLUSTER_LIGHT_LOOP #include_with_pragmas "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Fog.hlsl" #include_with_pragmas "Packages/com.unity.render-pipelines.core/ShaderLibrary/FoveatedRenderingKeywords.hlsl" diff --git a/Packages/com.unity.render-pipelines.universal/Editor/VFXGraph/Shaders/VFXDecal.template b/Packages/com.unity.render-pipelines.universal/Editor/VFXGraph/Shaders/VFXDecal.template index 6c91b7d98d2..24139318f9f 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/VFXGraph/Shaders/VFXDecal.template +++ b/Packages/com.unity.render-pipelines.universal/Editor/VFXGraph/Shaders/VFXDecal.template @@ -239,8 +239,7 @@ void PrepareSurfaceAndInputData(VFX_VARYING_PS_INPUTS i, inout SurfaceData surfa decalSurfaceData.normalWS.xyz = normalize(lerp(receiverNormalWS.xyz, decalSurfaceData.normalWS.xyz, decalSurfaceData.normalWS.w)); #endif - float3 unusedGeometricNormalWS; - inputData = VFXGetInputData(i, posInput, decalSurfaceData.normalWS.xyz, true, unusedGeometricNormalWS); + inputData = VFXGetInputData(i, posInput, decalSurfaceData.normalWS.xyz, true); } diff --git a/Packages/com.unity.render-pipelines.universal/Editor/VFXGraph/Shaders/VFXLit.template b/Packages/com.unity.render-pipelines.universal/Editor/VFXGraph/Shaders/VFXLit.template index 809d5b83eb1..77cdb03113c 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/VFXGraph/Shaders/VFXLit.template +++ b/Packages/com.unity.render-pipelines.universal/Editor/VFXGraph/Shaders/VFXLit.template @@ -6,14 +6,14 @@ #define SurfaceData SixWaySurfaceData #endif -void VFXGetURPLitData(out SurfaceData surfaceData, out InputData inputData, VFX_VARYING_PS_INPUTS i, float3 normalWS, const VFXUVData uvData, bool frontFace, uint2 tileIndex, out float3 geometricNormalWS) +void VFXGetURPLitData(out SurfaceData surfaceData, out InputData inputData, VFX_VARYING_PS_INPUTS i, float3 normalWS, const VFXUVData uvData, bool frontFace, uint2 tileIndex) { float3 posRWS = VFXGetPositionRWS(i); float4 posSS = i.VFX_VARYING_POSCS; PositionInputs posInput = GetPositionInput(posSS.xy, _ScreenSize.zw, posSS.z, posSS.w, posRWS, tileIndex); surfaceData = VFXGetSurfaceData(i, normalWS, uvData, frontFace); - inputData = VFXGetInputData(i, posInput, normalWS, frontFace, geometricNormalWS); + inputData = VFXGetInputData(i, posInput, normalWS, frontFace); } #endif diff --git a/Packages/com.unity.render-pipelines.universal/Editor/VFXGraph/Shaders/VFXPasses.template b/Packages/com.unity.render-pipelines.universal/Editor/VFXGraph/Shaders/VFXPasses.template index 2485001e951..003e3a9c566 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/VFXGraph/Shaders/VFXPasses.template +++ b/Packages/com.unity.render-pipelines.universal/Editor/VFXGraph/Shaders/VFXPasses.template @@ -29,12 +29,14 @@ ${VFXEnd} ${VFXBegin:VFXPassForwardLitAdditionalPragma} #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN +#pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS #pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX _ADDITIONAL_LIGHTS #pragma multi_compile _ _LIGHT_FALLOFF_QUADRATIC #pragma multi_compile_fragment _ _ADDITIONAL_LIGHT_SHADOWS #pragma multi_compile_fragment _ _REFLECTION_PROBE_BLENDING #pragma multi_compile_fragment _ _REFLECTION_PROBE_BOX_PROJECTION #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH +#pragma multi_compile_fragment _ _SHADOWS_PCSS #pragma multi_compile_fragment _ _SCREEN_SPACE_OCCLUSION #pragma multi_compile_fragment _ _LIGHT_COOKIES #pragma multi_compile_fragment _ _VOLUMETRIC_FOG @@ -60,6 +62,7 @@ ${VFXBegin:VFXPassGBufferAdditionalPragma} #pragma multi_compile_fragment _ _REFLECTION_PROBE_BOX_PROJECTION #pragma multi_compile_fragment _ _GBUFFER_NORMALS_OCT #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN +#pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS #pragma multi_compile_fragment _ _RENDER_PASS_ENABLED #include_with_pragmas "Packages/com.unity.render-pipelines.universal/ShaderLibrary/ProbeVolumeVariants.hlsl" //See Lit.shader, these multi_compile aren't used in GBuffer diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Passes/Utility/RendererLighting.cs b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Passes/Utility/RendererLighting.cs index fe8a2803148..658fc6902d6 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Passes/Utility/RendererLighting.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Passes/Utility/RendererLighting.cs @@ -409,7 +409,8 @@ private static Material CreateLightMaterial(Renderer2DData rendererData, Light2D // material cache. Sets BOTH the non-volumetric properties (_SrcBlend/_DstBlend, pass 0) and // the volumetric properties (_VolSrcBlend/_VolDstBlend, pass 1). Both depend only on // light.overlapOperation and light.lightType, which are baked into the customLightMaterials - // cache key, so calling this once per cache-fill is sufficient — no per-frame mutation. + // cache key. It is called on every lookup, after the clone is re-synced from its source, + // because that copy overwrites these properties. // Using separate properties per-pass avoids intra-material conflict where pass 0 and pass 1 // would otherwise share `_SrcBlend/_DstBlend` and the later-set value would win. private static void ApplyBlendModesForLight(Material material, Light2D light) @@ -458,10 +459,12 @@ internal static Material GetLightMaterial(this Renderer2DData rendererData, Ligh // live on Renderer2DData and are destroyed alongside `lightMaterials` in Dispose / // ClearLightMaterialCache. // - // Trade-off: property changes on the source material at runtime (e.g. user-tweaked - // color) don't propagate to the clones. Users needing dynamic property updates should - // re-assign `light.material` (invalidates the cache) or drive the property via a shader - // global. This mirrors the existing built-in `lightMaterials` cache contract. + // The clone is synced from its source on every lookup (shader, properties, keywords), + // so edits to the source material show up without a domain reload (UUM-152882). Any + // direct writes to the clone are overwritten; only the blend state is re-applied after + // the copy. Cost: one native property and keyword copy per lookup, and DrawLight2DPass + // looks up once per light draw (each blend style, layer batch and volumetric pass, per + // camera). A cache hit makes no managed GC allocation. var custom = light.material; if (custom != null) { @@ -469,9 +472,17 @@ internal static Material GetLightMaterial(this Renderer2DData rendererData, Ligh if (!rendererData.customLightMaterials.TryGetValue(key, out var instance) || instance == null) { instance = new Material(custom); - ApplyBlendModesForLight(instance, light); rendererData.customLightMaterials[key] = instance; } + else + { + if (instance.shader != custom.shader) + instance.shader = custom.shader; + instance.CopyPropertiesFromMaterial(custom); + } + + // Must run after the copy, which overwrites _SrcBlend/_DstBlend/_VolSrcBlend/_VolDstBlend. + ApplyBlendModesForLight(instance, light); return instance; } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/DrawLight2DPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/DrawLight2DPass.cs index a79755245b6..f3259602f45 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/DrawLight2DPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/DrawLight2DPass.cs @@ -206,7 +206,6 @@ internal class PassData internal int lightTextureIndex; internal bool useRenderingLayers; - internal RenderingLayerUtils.MaskSize maskSize; } void InitializeRenderPass(RenderGraph graph, IRasterRenderGraphBuilder builder, ContextContainer frameData, PassData passData, int batchIndex, bool isVolumetric = false) @@ -241,7 +240,6 @@ void InitializeRenderPass(RenderGraph graph, IRasterRenderGraphBuilder builder, builder.UseTexture(universal2DResourceData.renderingLayersTexture); passData.useRenderingLayers = rendererData.useRenderingLayers; - passData.maskSize = rendererData.renderingLayersMaskSize; passData.layerBatch = layerBatch; passData.rendererData = rendererData; passData.isVolumetric = isVolumetric; @@ -266,7 +264,7 @@ internal void Render(RenderGraph graph, ContextContainer frameData, int batchInd !isLightingActive) return; - // Render single RTs by for apis that don't support MRTs + // Render one light texture per pass where Renderer2D.supportsMRT is false (OpenGLES3 and OpenGLCore) if (!isVolumetric && !Renderer2D.supportsMRT) { var passName = ProfilerMarkers.s_LightSRTPass; @@ -286,8 +284,6 @@ internal void Render(RenderGraph graph, ContextContainer frameData, int batchInd builder.SetRenderFunc(static (PassData data, RasterGraphContext context) => { - RenderingLayerUtils.SetupProperties(context.cmd, data.maskSize); - Execute(context.cmd, data, data.layerBatch, data.lightTextureIndex); }); } @@ -311,8 +307,6 @@ internal void Render(RenderGraph graph, ContextContainer frameData, int batchInd builder.SetRenderFunc(static (PassData data, RasterGraphContext context) => { - RenderingLayerUtils.SetupProperties(context.cmd, data.maskSize); - for (var i = 0; i < data.layerBatch.activeBlendStylesIndices.Length; ++i) Execute(context.cmd, data, data.layerBatch, i); }); diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/DrawNormal2DPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/DrawNormal2DPass.cs index 5cf40956a59..84df47cda02 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/DrawNormal2DPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/DrawNormal2DPass.cs @@ -50,7 +50,7 @@ public void Render(RenderGraph graph, ContextContainer frameData, int batchIndex builder.SetRenderAttachment(universal2DResourceData.normalsTexture[batchIndex], 0); // Depth needed for sprite mask stencil or z test for 3d meshes - if (commonResourceData.activeDepthTexture.IsValid()) + if (Renderer2D.IsDepthUsageAllowed(frameData, rendererData) && commonResourceData.activeDepthTexture.IsValid()) { var depth = universal2DResourceData.normalsDepth.IsValid() ? universal2DResourceData.normalsDepth : commonResourceData.activeDepthTexture; builder.SetRenderAttachmentDepth(depth); diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/DrawRenderer2DPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/DrawRenderer2DPass.cs index a4ee9e4f701..758586d2c45 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/DrawRenderer2DPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/DrawRenderer2DPass.cs @@ -14,7 +14,6 @@ internal class DrawRenderer2DPass : ScriptableRenderPass new List() {k_LegacyPassName, k_CombinedRenderingPassName}; private static readonly int k_HDREmulationScaleID = Shader.PropertyToID("_HDREmulationScale"); - private static readonly int k_RendererColorID = Shader.PropertyToID("_RendererColor"); private static void Execute(RasterGraphContext context, PassData passData) { @@ -22,7 +21,6 @@ private static void Execute(RasterGraphContext context, PassData passData) var blendStylesCount = passData.blendStyleIndices.Length; cmd.SetGlobalFloat(k_HDREmulationScaleID, passData.hdrEmulationScale); - cmd.SetGlobalColor(k_RendererColorID, Color.white); RendererLighting.SetLightShaderGlobals(cmd, passData.lightBlendStyles, passData.blendStyleIndices); #if UNITY_EDITOR 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 d9b4e887cc3..43b578a3530 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 @@ -221,6 +221,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; @@ -537,10 +557,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 { @@ -554,12 +571,14 @@ void CreateResources(RenderGraph renderGraph) m_CreateDepthTexture = baseRenderer.m_CreateDepthTexture; commonResourceData.activeColorID = m_CreateColorTexture ? ActiveID.Camera : ActiveID.BackBuffer; - commonResourceData.activeDepthID = m_CreateDepthTexture ? ActiveID.Camera : ActiveID.BackBuffer; } + // An intermediate color target is never paired with the back buffer depth + commonResourceData.activeDepthID = m_CreateDepthTexture || m_CreateColorTexture ? ActiveID.Camera : ActiveID.BackBuffer; + // Report this camera's real back buffer MSAA need; a 2D camera renders directly to it only when // no intermediate color texture is created (m_CreateColorTexture == false). - ReportRealBackbufferMSAA(cameraData, m_CreateColorTexture); + ReportDisplayTargetMSAA(cameraData, m_CreateColorTexture); ImportResourceSummary importSummary = GetImportResourceSummary(renderGraph, cameraData); @@ -597,7 +616,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) { @@ -890,7 +909,7 @@ internal override void InitRenderGraphFrame(RenderGraph renderGraph) // Renderer is responsible for init/resetting the keywords it manages, for now we can use the default reset InitDefaultGlobalKeywords(cmd, data.cameraData); - data.shaderData.Get().PushDefaultToGlobal(cmd); + data.shaderData.GetGlobal().PushDefault(cmd); }); } } @@ -912,7 +931,7 @@ void SetupRenderGraphCameraProperties(RenderGraph renderGraph, in TextureHandle SetupCameraProperties(context, data.cameraData, isTargetFlipped); - data.uploader.PushDefaultToGlobal(context.cmd, GlobalShaderVariablesGroup.Base); + data.uploader.PushAfterCameraSetup(context.cmd); }); } } @@ -1384,9 +1403,16 @@ internal static bool IsGLESDevice() return SystemInfo.graphicsDeviceType == GraphicsDeviceType.OpenGLES3; } + internal static bool IsGLDevice() + { + return IsGLESDevice() || SystemInfo.graphicsDeviceType == GraphicsDeviceType.OpenGLCore; + } + + // OpenGL uses one light pass per blend style. With MRT on OpenGLCore, NVIDIA drivers write a light's colour + // into the other bound light textures too, so a Multiply light leaks into the Additive texture (UUM-161536). internal static bool supportsMRT { - get => !IsGLESDevice(); + get => !IsGLDevice(); } internal static bool IsSceneViewOrPreviewLightingActive(UniversalCameraData cameraData) diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/Generation/ShadowShapeExpansion.cs b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/Generation/ShadowShapeExpansion.cs index 3a868943205..9d8aa9b864a 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/Generation/ShadowShapeExpansion.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/Generation/ShadowShapeExpansion.cs @@ -7,7 +7,7 @@ namespace UnityEngine.Rendering.Universal /// zero-radius runs stay as line segments, non-zero radii become circles or capsules. /// /// - /// Moved verbatim out of so that any generation path can reuse it + /// Moved out of so that any generation path can reuse it /// rather than reimplement capsule expansion. This is input normalisation, not shadow /// geometry: it produces an outline, and what a path does with that outline is up to the path. /// @@ -78,18 +78,8 @@ internal static void AddCapsuleCap(Vector3 center, float r, Vector3 otherCenter, internal static void AddCapsule(Vector3 pt0, Vector3 pt1, float r0, float r1, NativeArray generatedVertices, NativeArray generatedIndices, bool reverseWindingOrder, ref int vertexWritePos, ref int indexWritePos) { - // Add Straight Segments - Vector3 delta = (pt1 - pt0).normalized; - Vector3 relOffset0 = new Vector3(delta.y, -delta.x, 0); - Vector3 relOffset1 = new Vector3(-delta.y, delta.x, 0); - - if (pt1.x < pt0.x) - { - Vector3 temp = pt0; - pt0 = pt1; - pt1 = temp; - } - + // Each cap is oriented toward the other end, so the outline is the same whichever way + // the edge runs. Do not reorder the endpoints: each radius must stay with its own end. int circle0Start = vertexWritePos; // Add circles diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/Providers/ShadowShape2DProvider_SpriteSkin.cs b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/Providers/ShadowShape2DProvider_SpriteSkin.cs index 3fe86d5a868..1385bb7b75b 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/Providers/ShadowShape2DProvider_SpriteSkin.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/Providers/ShadowShape2DProvider_SpriteSkin.cs @@ -81,12 +81,17 @@ public override void OnInitialized(Component sourceComponent, ShadowShape2D pers public override void OnBeforeRender(Camera camera, 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/Runtime/2D/Shadows/Shadow Provider Utility/ShadowUtility.cs b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/Shadow Provider Utility/ShadowUtility.cs index 06d13a4ab19..7205ecee0fa 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/Shadow Provider Utility/ShadowUtility.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/Shadow Provider Utility/ShadowUtility.cs @@ -76,7 +76,7 @@ public void Initialize() } [BurstCompile] - unsafe static int GetNextShapeStart(int currentShape, int* inShapeStartingEdgePtr, int inShapeStartingEdgeLength, int maxValue) + internal unsafe static int GetNextShapeStart(int currentShape, int* inShapeStartingEdgePtr, int inShapeStartingEdgeLength, int maxValue) { return ((currentShape + 1 < inShapeStartingEdgeLength) && (inShapeStartingEdgePtr[currentShape + 1] >= 0)) ? inShapeStartingEdgePtr[currentShape + 1] : maxValue; } @@ -379,7 +379,7 @@ static internal void CalculateLocalBounds(ref NativeArray inVertices, ou } [BurstCompile] - static void GenerateInteriorMesh(ref NativeArray inVertices, ref NativeArray inIndices, ref NativeArray inEdges, out NativeArray outVertices, out NativeArray outIndices, out int outStartIndex, out int outIndexCount) + internal static void GenerateInteriorMesh(ref NativeArray inVertices, ref NativeArray inIndices, ref NativeArray inEdges, out NativeArray outVertices, out NativeArray outIndices, out int outStartIndex, out int outIndexCount) { int inEdgeCount = inEdges.Length; @@ -500,7 +500,7 @@ static public void GenerateShadowMesh(ref Mesh mesh, NativeArray inVertices, ref NativeArray inEdges, ref NativeArray inShapeStartingEdge, @@ -548,7 +548,7 @@ static void GenerateShadowGeometry_Internal_FromTriangles( // BURST-COMPATIBLE internal function - Line version [BurstCompile] - static void GenerateShadowGeometry_Internal_FromLines( + internal static void GenerateShadowGeometry_Internal_FromLines( ref NativeArray inVertices, ref NativeArray inEdges, ref NativeArray inShapeStartingEdge, @@ -916,7 +916,7 @@ static public void ReverseWindingOrder(ref NativeArray inShapeStartingEdge, } [BurstCompile] - static int GetClosedPathCount(ref NativeArray inShapeStartingEdge, ref NativeArray inShapeIsClosedArray) + internal static int GetClosedPathCount(ref NativeArray inShapeStartingEdge, ref NativeArray inShapeIsClosedArray) { int count = 0; for (int i = 0; i < inShapeStartingEdge.Length; i++) @@ -931,7 +931,7 @@ static int GetClosedPathCount(ref NativeArray inShapeStartingEdge, ref Nati } [BurstCompile] - static void GetPathInfo(ref NativeArray inEdges, ref NativeArray inShapeStartingEdge, ref NativeArray inShapeIsClosedArray, out int closedPathArrayCount, out int closedPathsCount, out int openPathArrayCount, out int openPathsCount) + internal static void GetPathInfo(ref NativeArray inEdges, ref NativeArray inShapeStartingEdge, ref NativeArray inShapeIsClosedArray, out int closedPathArrayCount, out int closedPathsCount, out int openPathArrayCount, out int openPathsCount) { closedPathArrayCount = 0; openPathArrayCount = 0; 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 d1ad1d986cc..f0f81bd7c8c 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 @@ -34,9 +34,10 @@ internal enum ComponentVersions Version_6 = 6, Version_7 = 7, Version_8 = 8, + Version_9 = 9, } - const ComponentVersions k_CurrentComponentVersion = ComponentVersions.Version_8; + const ComponentVersions k_CurrentComponentVersion = ComponentVersions.Version_9; [SerializeField] ComponentVersions m_ComponentVersion = ComponentVersions.Version_Unserialized; internal enum ShadowCastingSources @@ -343,6 +344,20 @@ void SetShadowShape(ShadowMesh2D shadowMesh) } } +#if UNITY_EDITOR + // Points the Casting Source dropdown at the source the shadow is built from. + void SyncSelectedSourceHash() + { + if (m_SelectionSources == null) + return; + + if (m_ShadowCastingSource == ShadowCastingSources.ShapeProvider) + m_SelectionSources.selectedHashCode = LightUtility.ProviderToHash(m_ShadowShape2DProvider, m_ShadowShape2DComponent); + else + m_SelectionSources.selectedHashCode = (int)m_ShadowCastingSource; + } +#endif + private void Awake() { if (m_ShadowCastingSource < 0) @@ -359,6 +374,8 @@ private void Awake() { m_ShadowCastingSource = ShadowCastingSources.ShapeEditor; } + + SyncSelectedSourceHash(); #else m_ShadowCastingSource = ShadowCastingSources.ShapeEditor; #endif @@ -678,15 +695,14 @@ public void OnAfterDeserialize() m_ForceShadowMeshRebuild = true; } - if (m_ComponentVersion < ComponentVersions.Version_6) - { #if UNITY_EDITOR - if (m_ShadowCastingSource == ShadowCastingSources.ShapeProvider) - m_SelectionSources.selectedHashCode = LightUtility.ProviderToHash(shadowShape2DProvider, shadowShape2DComponent); - else - m_SelectionSources.selectedHashCode = (int)m_ShadowCastingSource; + // Before Version_9, Awake left the selected hash at 0 whichever source it picked, so the + // Casting Source dropdown showed its first entry instead. Only a hash of 0 is repaired, + // so a source the user picked in the dropdown is never rewritten. + if (m_ComponentVersion < ComponentVersions.Version_6 || + (m_ComponentVersion < ComponentVersions.Version_9 && m_SelectionSources != null && m_SelectionSources.selectedHashCode == 0)) + SyncSelectedSourceHash(); #endif - } if(m_ShadowMesh != null) m_ShadowMesh.OnAfterDeserialize(); diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Data/UniversalRenderPipelineAsset.asset b/Packages/com.unity.render-pipelines.universal/Runtime/Data/UniversalRenderPipelineAsset.asset index 13cdd9000aa..ab17c3135bb 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Data/UniversalRenderPipelineAsset.asset +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Data/UniversalRenderPipelineAsset.asset @@ -12,8 +12,9 @@ MonoBehaviour: m_Script: {fileID: 11500000, guid: bf2edee5c58d82540a51f03df9d42094, type: 3} m_Name: UniversalRenderPipelineAsset m_EditorClassIdentifier: Unity.RenderPipelines.Universal.Runtime::UnityEngine.Rendering.Universal.UniversalRenderPipelineAsset - k_AssetVersion: 13 - k_AssetPreviousVersion: 13 + k_AssetVersion: 16 + k_AssetPreviousVersion: 16 + m_ShadowSettingsMigrationPending: 0 m_RendererType: 1 m_RendererData: {fileID: 0} m_RendererDataList: @@ -28,11 +29,18 @@ MonoBehaviour: m_MSAA: 1 m_RenderScale: 1 m_UpscalingFilter: 0 + m_ScalingMode: 0 + m_SelectedUpscalerName: + m_UpscalerPriority: + - upscalerId: unity.auto + upscalerName: Auto (Bilinear or Nearest-Neighbor) + m_UpscalerOptions: [] m_FsrOverrideSharpness: 0 m_FsrSharpness: 0.92 m_EnableLODCrossFade: 1 m_LODCrossFadeDitheringType: 1 m_ShEvalMode: 0 + m_ObsoleteLightFalloffMode: 0 m_LightProbeSystem: 0 m_ProbeVolumeMemoryBudget: 1024 m_ProbeVolumeBlendingMemoryBudget: 256 @@ -54,12 +62,12 @@ MonoBehaviour: m_ReflectionProbeBlending: 0 m_ReflectionProbeBoxProjection: 0 m_ReflectionProbeAtlas: 0 - m_ShadowDistance: 50 - m_ShadowCascadeCount: 1 - m_Cascade2Split: 0.25 - m_Cascade3Split: {x: 0.1, y: 0.3} - m_Cascade4Split: {x: 0.067, y: 0.2, z: 0.467} - m_CascadeBorder: 0.2 + m_ObsoleteShadowDistance: 50 + m_ObsoleteShadowCascadeCount: 1 + m_ObsoleteCascade2Split: 0.25 + m_ObsoleteCascade3Split: {x: 0.1, y: 0.3} + m_ObsoleteCascade4Split: {x: 0.067, y: 0.2, z: 0.467} + m_ObsoleteCascadeBorder: 0.2 m_ShadowDepthBias: 1 m_ShadowNormalBias: 1 m_AnyShadowsSupported: 1 @@ -84,6 +92,7 @@ MonoBehaviour: m_SupportScreenSpaceLensFlare: 1 m_GPUResidentDrawerMode: 0 m_SmallMeshScreenPercentage: 0 + m_ShadowSmallMeshScreenPercentages: {x: 0, y: 0, z: 0, w: 0} m_GPUResidentDrawerEnableOcclusionCullingInCameras: 0 m_ShadowType: 1 m_LocalShadowsSupported: 0 @@ -112,15 +121,7 @@ MonoBehaviour: m_PrefilterWriteRenderingLayers: 0 m_PrefilterHDROutput: 0 m_PrefilterAlphaOutput: 0 - m_PrefilterSSAODepthNormals: 0 - m_PrefilterSSAOSourceDepthLow: 0 - m_PrefilterSSAOSourceDepthMedium: 0 - m_PrefilterSSAOSourceDepthHigh: 0 - m_PrefilterSSAOInterleaved: 0 - m_PrefilterSSAOBlueNoise: 0 - m_PrefilterSSAOSampleCountLow: 0 - m_PrefilterSSAOSampleCountMedium: 0 - m_PrefilterSSAOSampleCountHigh: 0 + m_PrefilterSSAOKeywords: 0 m_PrefilterDBufferMRT1: 0 m_PrefilterDBufferMRT2: 0 m_PrefilterDBufferMRT3: 0 @@ -137,6 +138,12 @@ MonoBehaviour: m_PrefilterReflectionProbeBlending: 0 m_PrefilterReflectionProbeBoxProjection: 0 m_PrefilterReflectionProbeAtlas: 0 + m_PrefilterPointSamplingUpsampling: 0 + m_PrefilterExposure: 0 + m_PrefilterVolumetricFog: 0 + m_PrefilterLightFalloffQuadratic: 1 + m_Light2DPrefilteringMode: 0 + m_Light2DKeptVariantCombos: [] m_ShaderVariantLogLevel: 0 m_ShadowCascades: 0 m_Textures: diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Data/UniversalRenderPipelineAsset.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Data/UniversalRenderPipelineAsset.cs index 57c38b7972f..0f777a25b50 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Data/UniversalRenderPipelineAsset.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Data/UniversalRenderPipelineAsset.cs @@ -323,11 +323,24 @@ public enum VolumeFrameworkUpdateMode UsePipelineSettings = 2, } - // Which type of resolution scaling in UI order. - internal enum ScalingMode + /// + /// Defines the type of resolution scaling applied by the render pipeline. + /// + public enum ScalingMode { + /// + /// No scaling. The camera renders at the display resolution. + /// None, + + /// + /// Upscaling. The camera renders below the display resolution and the result is upscaled to the display resolution. + /// Upscaling, + + /// + /// Supersampling. The camera renders above the display resolution and the result is downsampled to the display resolution. + /// Supersampling, } @@ -431,11 +444,13 @@ public partial class UniversalRenderPipelineAsset : RenderPipelineAsset k_LastVersion == k_AssetVersion; - private const int k_LastVersion = 15; + private const int k_LastVersion = 16; // Default values set when a new UniversalRenderPipeline asset is created [SerializeField] internal int k_AssetVersion = k_LastVersion; [SerializeField] int k_AssetPreviousVersion = k_LastVersion; + [SerializeField] internal bool m_ShadowSettingsMigrationPending; + // Deprecated settings for upgrading sakes [SerializeField] RendererType m_RendererType = RendererType.UniversalRenderer; [EditorBrowsable(EditorBrowsableState.Never)] @@ -533,6 +548,7 @@ public UpscalerPriorityEntry(string upscalerId, string upscalerName) [SerializeField] LightRenderingMode m_MainLightRenderingMode = LightRenderingMode.PerPixel; [SerializeField] bool m_MainLightShadowsSupported = true; [SerializeField] ShadowResolution m_MainLightShadowmapResolution = ShadowResolution._2048; + [SerializeField] DepthBits m_MainLightShadowmapDepthBits = DepthBits.Depth16; // Additional lights settings [SerializeField] LightRenderingMode m_AdditionalLightsRenderingMode = LightRenderingMode.PerPixel; @@ -545,6 +561,7 @@ public UpscalerPriorityEntry(string upscalerId, string upscalerName) [SerializeField] int m_AdditionalLightsPerObjectLimit = 4; [SerializeField] bool m_AdditionalLightShadowsSupported = false; [SerializeField] ShadowResolution m_AdditionalLightsShadowmapResolution = ShadowResolution._2048; + [SerializeField] DepthBits m_AdditionalLightsShadowmapDepthBits = DepthBits.Depth16; [SerializeField] int m_AdditionalLightsShadowResolutionTierLow = AdditionalLightsDefaultShadowResolutionTierLow; [SerializeField] int m_AdditionalLightsShadowResolutionTierMedium = AdditionalLightsDefaultShadowResolutionTierMedium; @@ -556,12 +573,24 @@ public UpscalerPriorityEntry(string upscalerId, string upscalerName) [SerializeField] bool m_ReflectionProbeAtlas = true; // Shadows Settings - [SerializeField] float m_ShadowDistance = 50.0f; - [SerializeField] int m_ShadowCascadeCount = 1; - [SerializeField] float m_Cascade2Split = 0.25f; - [SerializeField] Vector2 m_Cascade3Split = new Vector2(0.1f, 0.3f); - [SerializeField] Vector3 m_Cascade4Split = new Vector3(0.067f, 0.2f, 0.467f); - [SerializeField] float m_CascadeBorder = 0.2f; + [SerializeField, FormerlySerializedAs("m_ShadowDistance")] + [Obsolete("Kept for migration. #from(7000.0)", false)] + internal float m_ObsoleteShadowDistance = 50.0f; + [SerializeField, FormerlySerializedAs("m_ShadowCascadeCount")] + [Obsolete("Kept for migration. #from(7000.0)", false)] + internal int m_ObsoleteShadowCascadeCount = 1; + [SerializeField, FormerlySerializedAs("m_Cascade2Split")] + [Obsolete("Kept for migration. #from(7000.0)", false)] + internal float m_ObsoleteCascade2Split = 0.25f; + [SerializeField, FormerlySerializedAs("m_Cascade3Split")] + [Obsolete("Kept for migration. #from(7000.0)", false)] + internal Vector2 m_ObsoleteCascade3Split = new Vector2(0.1f, 0.3f); + [SerializeField, FormerlySerializedAs("m_Cascade4Split")] + [Obsolete("Kept for migration. #from(7000.0)", false)] + internal Vector3 m_ObsoleteCascade4Split = new Vector3(0.067f, 0.2f, 0.467f); + [SerializeField, FormerlySerializedAs("m_CascadeBorder")] + [Obsolete("Kept for migration. #from(7000.0)", false)] + internal float m_ObsoleteCascadeBorder = 0.2f; [SerializeField] float m_ShadowDepthBias = 1.0f; [SerializeField] float m_ShadowNormalBias = 1.0f; #if UNITY_EDITOR // multi_compile_fragment _ _SHADOWS_SOFT @@ -575,6 +604,10 @@ public UpscalerPriorityEntry(string upscalerId, string upscalerName) [SerializeField] bool m_ConservativeEnclosingSphere = false; [SerializeField] int m_NumIterationsEnclosingSphere = 64; [SerializeField] SoftShadowQuality m_SoftShadowQuality = SoftShadowQuality.Medium; + [SerializeField, Range(0.0f, 3.0f)] float m_SoftShadowKernelRadiusPercent; + + [SerializeField] bool m_MainLightShadowsPCSS = false; + [SerializeField] bool m_AdditionalLightShadowsPCSS = false; // Light Cookie Settings [SerializeField] LightCookieResolution m_AdditionalLightsCookieResolution = LightCookieResolution._2048; @@ -861,6 +894,11 @@ void DestroyRenderer(ref ScriptableRenderer renderer) { renderer.Dispose(); renderer = null; + + // The slot can still bind a buffer the renderer released, and after a domain reload + // useGlobalConstantBuffer starts over. + if (UniversalRenderPipeline.useGlobalConstantBuffer) + GlobalShaderVariablesUploader.UnbindGlobal(); } } @@ -1186,12 +1224,19 @@ public string upscalerName } /// - /// Controls whether upscaling is enabled. + /// Controls the type of resolution scaling the render pipeline applies. Set this to to disable upscaling. /// - internal ScalingMode scalingMode + public ScalingMode scalingMode { get => m_ScalingMode; - set => m_ScalingMode = value; + set + { + if (value == m_ScalingMode) + return; + + m_ScalingMode = value; + OnValidate(); + } } /// @@ -1399,6 +1444,15 @@ public int mainLightShadowmapResolution set => m_MainLightShadowmapResolution = (ShadowResolution)value; } + /// + /// The depth buffer precision of the main light shadow map. + /// + public DepthBits mainLightShadowmapDepthBits + { + get => m_MainLightShadowmapDepthBits; + set => m_MainLightShadowmapDepthBits = value; + } + /// /// Specifies the LightRenderingMode for the additional lights used by this UniversalRenderPipelineAsset. /// @@ -1442,6 +1496,15 @@ public int additionalLightsShadowmapResolution set => m_AdditionalLightsShadowmapResolution = (ShadowResolution)value; } + /// + /// The depth buffer precision of the additional lights shadow map atlas. + /// + public DepthBits additionalLightsShadowmapDepthBits + { + get => m_AdditionalLightsShadowmapDepthBits; + set => m_AdditionalLightsShadowmapDepthBits = value; + } + /// /// Returns the additional light shadow resolution defined for tier "Low" in the UniversalRenderPipeline asset. /// @@ -1533,70 +1596,6 @@ internal bool ShouldUseReflectionProbeAtlasBlending(RenderingMode renderingMode) return useProbeBlending && (reflectionProbeAtlas || renderingMode == RenderingMode.DeferredPlus); } - /// - /// Controls the maximum distance at which shadows are visible. - /// - public float shadowDistance - { - get => m_ShadowDistance; - set => m_ShadowDistance = Mathf.Max(0.0f, value); - } - - /// - /// Returns the number of shadow cascades. - /// - public int shadowCascadeCount - { - get => m_ShadowCascadeCount; - set - { - if (value < k_ShadowCascadeMinCount || value > k_ShadowCascadeMaxCount) - { - throw new ArgumentException($"Value ({value}) needs to be between {k_ShadowCascadeMinCount} and {k_ShadowCascadeMaxCount}."); - } - m_ShadowCascadeCount = value; - } - } - - /// - /// Returns the split value. - /// - /// Returns a Float with the split value. - public float cascade2Split - { - get => m_Cascade2Split; - set => m_Cascade2Split = value; - } - - /// - /// Returns the split values. - /// - /// Returns a Vector2 with the split values. - public Vector2 cascade3Split - { - get => m_Cascade3Split; - set => m_Cascade3Split = value; - } - - /// - /// Returns the split values. - /// - /// Returns a Vector3 with the split values. - public Vector3 cascade4Split - { - get => m_Cascade4Split; - set => m_Cascade4Split = value; - } - - /// - /// Last cascade fade distance in percentage. - /// - public float cascadeBorder - { - get => m_CascadeBorder; - set => m_CascadeBorder = value; - } - /// /// The Shadow Depth Bias, controls the offset of the lit pixels. /// @@ -1633,6 +1632,36 @@ internal SoftShadowQuality softShadowQuality set => m_SoftShadowQuality = value; } + /// + /// Enables Percentage-Closer Soft Shadows (PCSS) for the main directional light when its soft shadow quality is High. + /// Note: Builds strip the PCSS shader variants unless a URP Asset in the build enables this. + /// + internal bool mainLightShadowsPCSS + { + get => m_MainLightShadowsPCSS; + set => m_MainLightShadowsPCSS = value; + } + + /// + /// Enables Percentage-Closer Soft Shadows (PCSS) for shadow casting spot and point lights when their soft shadow quality is High. + /// Note: Builds strip the PCSS shader variants unless a URP Asset in the build enables this. + /// + internal bool additionalLightShadowsPCSS + { + get => m_AdditionalLightShadowsPCSS; + set => m_AdditionalLightShadowsPCSS = value; + } + + /// + /// Radius of the main light's soft shadow filter, as a percentage of the width of a cascade's shadow map, so the penumbra keeps the same width within a cascade regardless of the shadow resolution. + /// 0 keeps each soft shadow quality's fixed kernel in shadow-map texels. Ignored when the main light uses PCSS. + /// + internal float softShadowKernelRadiusPercent + { + get => m_SoftShadowKernelRadiusPercent; + set => m_SoftShadowKernelRadiusPercent = Mathf.Max(0.0f, value); + } + /// /// Specifies if this UniversalRenderPipelineAsset should use dynamic batching. /// @@ -1935,11 +1964,11 @@ public void OnAfterDeserialize() int value = (int)m_ShadowCascades; if (value == 2) { - m_ShadowCascadeCount = 4; + m_ObsoleteShadowCascadeCount = 4; } else { - m_ShadowCascadeCount = value + 1; + m_ObsoleteShadowCascadeCount = value + 1; } k_AssetVersion = 6; #pragma warning restore 618 // Obsolete warning @@ -1954,7 +1983,9 @@ public void OnAfterDeserialize() if (k_AssetVersion < 8) { k_AssetPreviousVersion = k_AssetVersion; - m_CascadeBorder = 0.1f; // In previous version we had this hard coded +#pragma warning disable 618 // Obsolete warning + m_ObsoleteCascadeBorder = 0.1f; // In previous version we had this hard coded +#pragma warning restore 618 // Obsolete warning k_AssetVersion = 8; } @@ -2010,6 +2041,14 @@ public void OnAfterDeserialize() k_AssetVersion = 15; } + if (k_AssetVersion < 16) + { + m_ShadowSettingsMigrationPending = true; + + k_AssetPreviousVersion = k_AssetVersion; + k_AssetVersion = 16; + } + #if UNITY_EDITOR if (k_AssetPreviousVersion != k_AssetVersion) { @@ -2109,6 +2148,8 @@ void UpgradeToUpscalerPriority() static void UpgradeAsset(EntityId assetInstanceID) { UniversalRenderPipelineAsset asset = EditorUtility.EntityIdToObject(assetInstanceID) as UniversalRenderPipelineAsset; + if (asset == null) + return; if (asset.k_AssetPreviousVersion < 5) { @@ -2176,6 +2217,11 @@ static void UpgradeAsset(EntityId assetInstanceID) asset.k_AssetPreviousVersion = 15; } + if (asset.k_AssetPreviousVersion < 16) + { + asset.k_AssetPreviousVersion = 16; + } + ResourceReloader.ReloadAllNullIn(asset, packagePath); EditorUtility.SetDirty(asset); } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Data/UniversalRenderPipelineAssetPrefiltering.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Data/UniversalRenderPipelineAssetPrefiltering.cs index a304d2d22f8..e1a893f373f 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Data/UniversalRenderPipelineAssetPrefiltering.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Data/UniversalRenderPipelineAssetPrefiltering.cs @@ -64,7 +64,7 @@ internal enum PrefilteringModeAdditionalLights // NOTE: off variants are atm always removed when shadows are supported // Note: StencilDeferred is intentionally NOT carved out here. // Additional-light shadows keep their carve-out below. - [ShaderKeywordFilter.RemoveIf(PrefilteringModeMainLightShadows.Remove, keywordNames: new [] {ShaderKeywordStrings.MainLightShadows, ShaderKeywordStrings.MainLightShadowCascades})] + [ShaderKeywordFilter.RemoveIf(PrefilteringModeMainLightShadows.Remove, keywordNames: new [] {ShaderKeywordStrings.MainLightShadows, ShaderKeywordStrings.MainLightShadowCascades, ShaderKeywordStrings.MainLightShadowScreen})] [ShaderKeywordFilter.SelectIf(PrefilteringModeMainLightShadows.SelectMainLight, keywordNames: ShaderKeywordStrings.MainLightShadows)] [ShaderKeywordFilter.SelectIf(PrefilteringModeMainLightShadows.SelectMainLightAndOff, keywordNames: new [] {"", ShaderKeywordStrings.MainLightShadows})] [ShaderKeywordFilter.SelectIf(PrefilteringModeMainLightShadows.SelectMainLightAndCascades, keywordNames: new [] {ShaderKeywordStrings.MainLightShadows, ShaderKeywordStrings.MainLightShadowCascades})] @@ -182,6 +182,8 @@ internal enum PrefilteringModeAdditionalLights [SerializeField] private bool m_PrefilterSoftShadowsQualityHigh = false; [ShaderKeywordFilter.RemoveIf(true, keywordNames: ShaderKeywordStrings.SoftShadows)] [SerializeField] private bool m_PrefilterSoftShadows = false; + [ShaderKeywordFilter.RemoveIf(true, keywordNames: ShaderKeywordStrings.ShadowsPCSS)] + [SerializeField] private bool m_PrefilterShadowsPCSS = false; // Screen Coord Override - Controlled by the Global Settings [ShaderKeywordFilter.RemoveIf(true, keywordNames: ShaderKeywordStrings.SCREEN_COORD_OVERRIDE)] @@ -241,6 +243,11 @@ internal enum PrefilteringModeAdditionalLights [ShaderKeywordFilter.SelectIf(false, keywordNames: ShaderKeywordStrings.LightFalloffQuadratic)] [SerializeField] private bool m_PrefilterLightFalloffQuadratic = true; + // Shadow receiver normal bias (_SHADOW_RECEIVER_NORMAL_BIAS) + [ShaderKeywordFilter.RemoveIf(true, keywordNames: ShaderKeywordStrings.ShadowReceiverNormalBias)] + [ShaderKeywordFilter.SelectIf(false, keywordNames: ShaderKeywordStrings.ShadowReceiverNormalBias)] + [SerializeField] private bool m_PrefilterShadowReceiverNormalBias = false; + // Hidden/Light2D variant prefiltering. The 6-keyword combo space (USE_NORMAL_MAP, // USE_SHADOW_MAP, USE_ADDITIVE_BLENDING, USE_VOLUMETRIC, USE_POINT_LIGHT_COOKIES, // LIGHT_QUALITY_FAST) is too dynamic to express with declarative ShaderKeywordFilter @@ -279,6 +286,7 @@ internal struct ShaderPrefilteringData public bool stripSoftShadowsQualityLow; public bool stripSoftShadowsQualityMedium; public bool stripSoftShadowsQualityHigh; + public bool stripShadowsPCSS; public bool stripSSAOKeywords; @@ -296,6 +304,8 @@ internal struct ShaderPrefilteringData public bool stripLightFalloffQuadratic; + public bool stripShadowReceiverNormalBias; + public bool stripScreenSpaceIrradiance; // Keyword used by the DepthNormalOnly pass to write smoothness into alpha channel for screen space reflections. @@ -352,6 +362,7 @@ internal void UpdateShaderKeywordPrefiltering(ref ShaderPrefilteringData prefilt m_PrefilterSoftShadowsQualityMedium = prefilteringData.stripSoftShadowsQualityMedium; m_PrefilterSoftShadowsQualityHigh = prefilteringData.stripSoftShadowsQualityHigh; m_PrefilterSoftShadows = !m_PrefilterSoftShadowsQualityLow || !m_PrefilterSoftShadowsQualityMedium || !m_PrefilterSoftShadowsQualityHigh; + m_PrefilterShadowsPCSS = prefilteringData.stripShadowsPCSS; m_PrefilterSSAOKeywords = prefilteringData.stripSSAOKeywords; @@ -369,6 +380,8 @@ internal void UpdateShaderKeywordPrefiltering(ref ShaderPrefilteringData prefilt m_PrefilterLightFalloffQuadratic = prefilteringData.stripLightFalloffQuadratic; + m_PrefilterShadowReceiverNormalBias = prefilteringData.stripShadowReceiverNormalBias; + m_PrefilterScreenSpaceIrradiance = prefilteringData.stripScreenSpaceIrradiance; m_PrefilterWriteSmoothness = prefilteringData.stripWriteSmoothness; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Debug/DebugDisplaySettingsScreenSpaceReflection.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Debug/DebugDisplaySettingsScreenSpaceReflection.cs new file mode 100644 index 00000000000..241a6ae240c --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Debug/DebugDisplaySettingsScreenSpaceReflection.cs @@ -0,0 +1,139 @@ +using System; +using NameAndTooltip = UnityEngine.Rendering.DebugUI.Widget.NameAndTooltip; + +namespace UnityEngine.Rendering.Universal +{ + internal enum ScreenSpaceReflectionDebugViewMode + { + None, + Reflections, + RawReflections, + Confidence, + RawConfidence, + MipLevel, + Smoothness, + ContactHardeningFactor, + RayDistance, + } + + [Serializable] + internal class DebugDisplaySettingsScreenSpaceReflection : IDebugDisplaySettingsData, ISerializedDebugDisplaySettings + { + public ScreenSpaceReflectionDebugViewMode viewMode { get; set; } + public float rayDistanceRange { get; set; } = 10; + public bool showSceneColor { get; set; } = true; + + internal static class Strings + { + public static readonly NameAndTooltip ViewMode = new() { name = "View Mode", tooltip = "Which Screen Space Reflection debug visualization to display as an overlay." }; + public static readonly NameAndTooltip MapSize = new() { name = "Map Size", tooltip = "The size of the debug overlay texture in the view." }; + public static readonly NameAndTooltip ShowSceneColor = new() { name = "Show Scene Color", tooltip = "Whether to show the scene color where there is no screen space reflection, instead of black." }; + public static readonly NameAndTooltip RayDistanceRange = new() { name = "Ray Distance Range", tooltip = "Ray hit distance, in world units, that maps to the top of the color ramp." }; + public const string ContactHardeningRequired = "This view mode requires Contact Hardening to be enabled in the Screen Space Reflection volume override."; + public const string RendererFeatureMissing = "These view modes require the Screen Space Reflection Renderer Feature to be enabled."; + } + + internal static class WidgetFactory + { + internal static DebugUI.Widget CreateRendererFeatureMissingMessage() => new DebugUI.MessageBox + { + displayName = Strings.RendererFeatureMissing, + style = DebugUI.MessageBox.Style.Warning, + isHiddenCallback = () => + { + if (UniversalRenderPipeline.asset == null) + return true; + + foreach (var rendererData in UniversalRenderPipeline.asset.rendererDataList) + { + if (rendererData == null) + continue; + + foreach (var feature in rendererData.rendererFeatures) + { + if (feature is ScreenSpaceReflectionRendererFeature && feature.isActive) + return true; + } + } + + return false; + } + }; + + internal static DebugUI.Widget CreateViewMode(DebugDisplaySettingsScreenSpaceReflection data) => new DebugUI.EnumField + { + nameAndTooltip = Strings.ViewMode, + autoEnum = typeof(ScreenSpaceReflectionDebugViewMode), + getter = () => (int)data.viewMode, + setter = (value) => data.viewMode = (ScreenSpaceReflectionDebugViewMode)value, + getIndex = () => (int)data.viewMode, + setIndex = (value) => data.viewMode = (ScreenSpaceReflectionDebugViewMode)value + }; + + internal static DebugUI.Widget CreateMapSize(DebugDisplaySettingsScreenSpaceReflection data) => new DebugUI.IntField + { + nameAndTooltip = Strings.MapSize, + getter = () => UniversalRenderPipelineDebugDisplaySettings.Instance.renderingSettings.fullScreenDebugModeOutputSizeScreenPercent, + setter = value => UniversalRenderPipelineDebugDisplaySettings.Instance.renderingSettings.fullScreenDebugModeOutputSizeScreenPercent = value, + incStep = 10, + incStepMult = 50, + min = () => 0, + max = () => 100, + isHiddenCallback = () => data.viewMode == ScreenSpaceReflectionDebugViewMode.None + }; + + internal static DebugUI.Widget CreateShowSceneColor(DebugDisplaySettingsScreenSpaceReflection data) => new DebugUI.BoolField + { + nameAndTooltip = Strings.ShowSceneColor, + getter = () => data.showSceneColor, + setter = (value) => data.showSceneColor = value, + isHiddenCallback = () => data.viewMode != ScreenSpaceReflectionDebugViewMode.Reflections && + data.viewMode != ScreenSpaceReflectionDebugViewMode.RawReflections + }; + + internal static DebugUI.Widget CreateRayDistanceRange(DebugDisplaySettingsScreenSpaceReflection data) => new DebugUI.FloatField + { + nameAndTooltip = Strings.RayDistanceRange, + getter = () => data.rayDistanceRange, + setter = value => data.rayDistanceRange = value, + incStep = 1.0f, + incStepMult = 10.0f, + min = () => 0.01f, + max = () => 99.0f, + isHiddenCallback = () => data.viewMode != ScreenSpaceReflectionDebugViewMode.RayDistance + }; + + internal static DebugUI.Widget CreateContactHardeningRequiredMessage(DebugDisplaySettingsScreenSpaceReflection data) => new DebugUI.MessageBox + { + displayName = Strings.ContactHardeningRequired, + style = DebugUI.MessageBox.Style.Info, + isHiddenCallback = () => data.viewMode != ScreenSpaceReflectionDebugViewMode.ContactHardeningFactor && + data.viewMode != ScreenSpaceReflectionDebugViewMode.RayDistance + }; + } + + [DisplayInfo(name = "Screen Space Reflection", order = 5)] + internal class SettingsPanel : DebugDisplaySettingsPanel + { + public SettingsPanel(DebugDisplaySettingsScreenSpaceReflection data) + : base(data) + { + AddWidget(WidgetFactory.CreateViewMode(data)); + AddWidget(WidgetFactory.CreateMapSize(data)); + AddWidget(WidgetFactory.CreateShowSceneColor(data)); + AddWidget(WidgetFactory.CreateRayDistanceRange(data)); + AddWidget(WidgetFactory.CreateContactHardeningRequiredMessage(data)); + AddWidget(WidgetFactory.CreateRendererFeatureMissingMessage()); + } + } + + /// + public bool AreAnySettingsActive => viewMode != ScreenSpaceReflectionDebugViewMode.None; + + /// + IDebugDisplaySettingsPanelDisposable IDebugDisplaySettingsData.CreatePanel() + { + return new SettingsPanel(this); + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Debug/DebugDisplaySettingsScreenSpaceReflection.cs.meta b/Packages/com.unity.render-pipelines.universal/Runtime/Debug/DebugDisplaySettingsScreenSpaceReflection.cs.meta new file mode 100644 index 00000000000..7ddc1ecd63d --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Debug/DebugDisplaySettingsScreenSpaceReflection.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 81cde35d47c14fd4addcdb607966584f \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Debug/DebugDisplaySettingsShadowCaching.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Debug/DebugDisplaySettingsShadowCaching.cs new file mode 100644 index 00000000000..8e09ec29eea --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Debug/DebugDisplaySettingsShadowCaching.cs @@ -0,0 +1,58 @@ +#if URP_SHADOW_CACHING + +using System; +using NameAndTooltip = UnityEngine.Rendering.DebugUI.Widget.NameAndTooltip; + +namespace UnityEngine.Rendering.Universal +{ + [Serializable] + internal class DebugDisplaySettingsShadowCaching : IDebugDisplaySettingsData, ISerializedDebugDisplaySettings + { + public ShadowCachingDebugState forceState { get; set; } + + internal static class Strings + { + public static readonly NameAndTooltip ForceState = new() { name = "Force State", tooltip = "Use the drop-down to paint all surfaces within the main light's shadow distance with the color of one cache state." }; + } + + internal static class WidgetFactory + { + internal static DebugUI.Widget CreateForceState(DebugDisplaySettingsShadowCaching data) => new DebugUI.EnumField + { + nameAndTooltip = Strings.ForceState, + autoEnum = typeof(ShadowCachingDebugState), + getter = () => (int)data.forceState, + setter = (value) => data.forceState = (ShadowCachingDebugState)value, + getIndex = () => (int)data.forceState, + setIndex = (value) => data.forceState = (ShadowCachingDebugState)value + }; + } + + [DisplayInfo(name = "Shadow Caching", order = 5)] + internal class SettingsPanel : DebugDisplaySettingsPanel + { + public SettingsPanel(DebugDisplaySettingsShadowCaching data) + : base(data) + { + AddWidget(new DebugUI.Foldout + { + displayName = "Advanced", + opened = true, + children = + { + WidgetFactory.CreateForceState(data) + } + }); + } + } + + public bool AreAnySettingsActive => forceState != ShadowCachingDebugState.None; + + IDebugDisplaySettingsPanelDisposable IDebugDisplaySettingsData.CreatePanel() + { + return new SettingsPanel(this); + } + } +} + +#endif diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Debug/DebugDisplaySettingsShadowCaching.cs.meta b/Packages/com.unity.render-pipelines.universal/Runtime/Debug/DebugDisplaySettingsShadowCaching.cs.meta new file mode 100644 index 00000000000..b31a7d982b2 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Debug/DebugDisplaySettingsShadowCaching.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 7e87e59b3c64c4624ad3f1692d5553e9 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Debug/DebugDisplaySettingsSurfaceCache.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Debug/DebugDisplaySettingsSurfaceCache.cs index 64252ed3dcb..08c024b6ec2 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Debug/DebugDisplaySettingsSurfaceCache.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Debug/DebugDisplaySettingsSurfaceCache.cs @@ -1,6 +1,8 @@ #if SURFACE_CACHE_SUPPORTED || UNITY_EDITOR using System; +using Unity.RenderPipelines.Core.Runtime.Shared; +using UnityEngine.PathTracing.Core; using NameAndTooltip = UnityEngine.Rendering.DebugUI.Widget.NameAndTooltip; #if ENABLE_UIELEMENTS_MODULE && UNITY_ENABLE_CHECKS @@ -25,7 +27,8 @@ internal enum SurfaceCacheDebugViewMode UpdateCount, FlatNormal, Albedo, - Emission + Emission, + WorldCulling } /// @@ -44,6 +47,11 @@ internal class DebugDisplaySettingsSurfaceCache : IDebugDisplaySettingsData, ISe /// public bool showSamplePosition { get; set; } + /// + /// Whether the Scene view camera is ignored when deciding which entities Entity Culling keeps. + /// + public bool excludeSceneViewFromEntityCulling { get; set; } + // Several renderers in the pipeline asset can each have an active Surface Cache GI feature static bool TryAggregateActiveFeatures(out int totalActiveCacheCount, out uint combinedWorldRenderingLayerMask) { @@ -73,13 +81,83 @@ static bool TryAggregateActiveFeatures(out int totalActiveCacheCount, out uint c return anyFeatureFound; } + struct MaterialAtlasSummary + { + public int MaterialCount; + public AtlasUsage Albedo; + public AtlasUsage Emission; + public AtlasUsage Transmission; + public long TotalAllocatedBytes; + } + + // Each Surface Cache GI renderer feature owns a separate world with its own atlases, and the slice limit applies + // to each of them, so per atlas type this reports the renderer feature that uses the most slices. + static bool TryAggregateMaterialAtlasUsage(out MaterialAtlasSummary summary) + { + summary = default; + bool anyFeatureFound = false; + + if (UniversalRenderPipeline.asset == null) + return false; + + foreach (var rendererData in UniversalRenderPipeline.asset.rendererDataList) + { + if (rendererData == null) + continue; + + foreach (var feature in rendererData.rendererFeatures) + { + if (feature is SurfaceCacheGIRendererFeature surfaceCacheFeature && surfaceCacheFeature.isActive && surfaceCacheFeature.IsValidForDebugging()) + { + surfaceCacheFeature.GetMaterialAtlasUsage(out int materialCount, out var albedo, out var emission, out var transmission); + summary.MaterialCount += materialCount; + if (!anyFeatureFound || albedo.UsedSliceCount > summary.Albedo.UsedSliceCount) + summary.Albedo = albedo; + if (!anyFeatureFound || emission.UsedSliceCount > summary.Emission.UsedSliceCount) + summary.Emission = emission; + if (!anyFeatureFound || transmission.UsedSliceCount > summary.Transmission.UsedSliceCount) + summary.Transmission = transmission; + summary.TotalAllocatedBytes += albedo.AllocatedBytes + emission.AllocatedBytes + transmission.AllocatedBytes; + anyFeatureFound = true; + } + } + } + + return anyFeatureFound; + } + + static string FormatAtlas(in AtlasUsage usage) + { + var text = $"{usage.UsedSliceCount} / {usage.MaxSliceCount} · {DebugUIUtilities.FormatMemorySize(usage.AllocatedBytes)}"; + return usage.UsedSliceCount >= 0.9 * usage.MaxSliceCount ? "⚠ " + text : text; + } + + static string FormatMaterialAtlas(Func format) + { + return TryAggregateMaterialAtlasUsage(out var summary) ? format(summary) : "-"; + } + internal static class Strings { public static readonly NameAndTooltip ViewMode = new() { name = "View Mode", tooltip = "Use the drop-down to select a Surface Cache debug visualization to display as an overlay." }; - public static readonly NameAndTooltip MapSize = new() { name = "Map Size", tooltip = "Set the size of the debug overlay texture in the view." }; + public static readonly NameAndTooltip MapSize = new() { name = "Map Size", tooltip = "Set the size of the debug overlay in the debug view." }; public static readonly NameAndTooltip ShowSamplePosition = new() { name = "Show Sample Position", tooltip = "Show patch sample positions in the debug view." }; public static readonly NameAndTooltip ActiveCaches = new() { name = "Active Caches", tooltip = "Number of per-camera surface caches currently alive." }; + public static readonly NameAndTooltip EntityCullingSection = new() { name = "Entity Culling", tooltip = "Entity Culling statistics and options for the Surface Cache world." }; + public static readonly NameAndTooltip ExcludeSceneViewFromEntityCulling = new() { name = "Exclude Scene View", tooltip = "Exclude the Scene view camera when culling. Can be used to view culling against other cameras without the Scene view interfering." }; + public static readonly NameAndTooltip TrackedEntities = new() { name = "Entities", tooltip = "Number of entities that can contribute to Surface Cache, including culled entities." }; + public static readonly NameAndTooltip CulledEntities = new() { name = "Culled Entities", tooltip = "Number of entities that Entity Culling leaves out of the Surface Cache world, and their percentage of all entities." }; + public static readonly NameAndTooltip LiveEntities = new() { name = "Live Entities", tooltip = "Number of entities in the Surface Cache world, and their percentage of all entities." }; + public static readonly NameAndTooltip TrackedChunks = new() { name = "Chunks", tooltip = "Number of entity chunks that hold entities that can contribute to Surface Cache." }; + public static readonly NameAndTooltip CulledChunks = new() { name = "Culled Chunks", tooltip = "Number of chunks where Entity Culling leaves out every entity, and their percentage of all chunks." }; + public static readonly NameAndTooltip LiveChunks = new() { name = "Live Chunks", tooltip = "Number of chunks with at least one entity in the Surface Cache world, and their percentage of all chunks." }; public static readonly NameAndTooltip WorldRenderingLayerMask = new() { name = "World Rendering Layer Mask", tooltip = "Combined (OR) rendering layer mask used for the shared world update this frame. This value is read only." }; + public static readonly NameAndTooltip MaterialAtlas = new() { name = "Material Atlas", tooltip = "GPU texture atlases that hold the albedo, emission and transmission of every material used by Surface Cache GI." }; + public static readonly NameAndTooltip Materials = new() { name = "Materials", tooltip = "Number of unique materials in the Surface Cache GI world." }; + public static readonly NameAndTooltip AlbedoAtlas = new() { name = "Albedo", tooltip = "Albedo texture atlas: slices used / device maximum (SystemInfo.maxTextureArraySlices), and VRAM allocated, which includes slices reserved ahead of use. ⚠ marks an atlas at or above 90% of the maximum." }; + public static readonly NameAndTooltip EmissionAtlas = new() { name = "Emission", tooltip = "Emission texture atlas: slices used / device maximum (SystemInfo.maxTextureArraySlices), and VRAM allocated, which includes slices reserved ahead of use. ⚠ marks an atlas at or above 90% of the maximum." }; + public static readonly NameAndTooltip TransmissionAtlas = new() { name = "Transmission", tooltip = "Transmission texture atlas: slices used / device maximum (SystemInfo.maxTextureArraySlices), and VRAM allocated, which includes slices reserved ahead of use. ⚠ marks an atlas at or above 90% of the maximum." }; + public static readonly NameAndTooltip TotalAtlasMemory = new() { name = "Total VRAM", tooltip = "Combined VRAM allocated by the albedo, emission and transmission atlases." }; } class ReadOnlyValueField : DebugUI.Value @@ -136,6 +214,65 @@ internal static class WidgetFactory isHiddenCallback = () => data.viewMode == SurfaceCacheDebugViewMode.None }; + internal static DebugUI.Widget CreateEntityCulling(DebugDisplaySettingsSurfaceCache data) => new DebugUI.Foldout + { + nameAndTooltip = Strings.EntityCullingSection, + opened = true, + children = + { + new ReadOnlyValueField + { + nameAndTooltip = Strings.TrackedEntities, + getter = () => FormatCount(SurfaceCacheEntityChangeBridge.TrackedEntityCount), + }, + new ReadOnlyValueField + { + nameAndTooltip = Strings.CulledEntities, + getter = () => FormatCountWithShare(SurfaceCacheEntityChangeBridge.CulledEntityCount, SurfaceCacheEntityChangeBridge.TrackedEntityCount), + }, + new ReadOnlyValueField + { + nameAndTooltip = Strings.LiveEntities, + getter = () => FormatCountWithShare(SurfaceCacheEntityChangeBridge.TrackedEntityCount - SurfaceCacheEntityChangeBridge.CulledEntityCount, SurfaceCacheEntityChangeBridge.TrackedEntityCount), + }, + new ReadOnlyValueField + { + nameAndTooltip = Strings.TrackedChunks, + getter = () => FormatCount(SurfaceCacheEntityChangeBridge.TrackedChunkCount), + }, + new ReadOnlyValueField + { + nameAndTooltip = Strings.CulledChunks, + getter = () => FormatCountWithShare(SurfaceCacheEntityChangeBridge.CulledChunkCount, SurfaceCacheEntityChangeBridge.TrackedChunkCount), + }, + new ReadOnlyValueField + { + nameAndTooltip = Strings.LiveChunks, + getter = () => FormatCountWithShare(SurfaceCacheEntityChangeBridge.TrackedChunkCount - SurfaceCacheEntityChangeBridge.CulledChunkCount, SurfaceCacheEntityChangeBridge.TrackedChunkCount), + }, + new DebugUI.BoolField + { + nameAndTooltip = Strings.ExcludeSceneViewFromEntityCulling, + getter = () => data.excludeSceneViewFromEntityCulling, + setter = value => data.excludeSceneViewFromEntityCulling = value, + }, + }, + }; + + internal static string FormatCount(int count) + { + return SurfaceCacheEntityChangeBridge.IsConsumerPresent ? count.ToString("N0") : "-"; + } + + internal static string FormatCountWithShare(int count, int total) + { + if (!SurfaceCacheEntityChangeBridge.IsConsumerPresent) + return "-"; + + float percentage = total > 0 ? 100.0f * count / total : 0.0f; + return $"{count:N0} ({percentage:F1}%)"; + } + internal static DebugUI.Widget CreateWorldRenderingLayerMask(DebugDisplaySettingsSurfaceCache data) { // No setter: DebugUI ignores edits when the setter is null, making the field read-only. @@ -151,6 +288,20 @@ internal static DebugUI.Widget CreateWorldRenderingLayerMask(DebugDisplaySetting isHiddenCallback = () => data.viewMode == SurfaceCacheDebugViewMode.None }; } + + internal static DebugUI.Widget CreateMaterialAtlas(DebugDisplaySettingsSurfaceCache data) => new DebugUI.Foldout + { + nameAndTooltip = Strings.MaterialAtlas, + opened = true, + children = + { + new ReadOnlyValueField { nameAndTooltip = Strings.Materials, getter = () => FormatMaterialAtlas(s => s.MaterialCount.ToString()) }, + new ReadOnlyValueField { nameAndTooltip = Strings.AlbedoAtlas, getter = () => FormatMaterialAtlas(s => FormatAtlas(s.Albedo)) }, + new ReadOnlyValueField { nameAndTooltip = Strings.EmissionAtlas, getter = () => FormatMaterialAtlas(s => FormatAtlas(s.Emission)) }, + new ReadOnlyValueField { nameAndTooltip = Strings.TransmissionAtlas, getter = () => FormatMaterialAtlas(s => FormatAtlas(s.Transmission)) }, + new ReadOnlyValueField { nameAndTooltip = Strings.TotalAtlasMemory, getter = () => FormatMaterialAtlas(s => DebugUIUtilities.FormatMemorySize(s.TotalAllocatedBytes)) }, + } + }; } [DisplayInfo(name = "Surface Cache", order = 4)] @@ -164,6 +315,8 @@ public SettingsPanel(DebugDisplaySettingsSurfaceCache data) AddWidget(WidgetFactory.CreateShowSamplePosition(data)); AddWidget(WidgetFactory.CreateActiveCaches(data)); AddWidget(WidgetFactory.CreateWorldRenderingLayerMask(data)); + AddWidget(WidgetFactory.CreateMaterialAtlas(data)); + AddWidget(WidgetFactory.CreateEntityCulling(data)); } } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Debug/DebugHandler.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Debug/DebugHandler.cs index 58e324dcf73..73b3cd54b67 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Debug/DebugHandler.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Debug/DebugHandler.cs @@ -47,6 +47,9 @@ class DebugHandler : IDebugDisplaySettingsQuery // Lighting settings... static readonly int k_DebugLightingModeId = Shader.PropertyToID("_DebugLightingMode"); static readonly int k_DebugLightingFeatureFlagsId = Shader.PropertyToID("_DebugLightingFeatureFlags"); +#if URP_SHADOW_CACHING + static readonly int k_DebugShadowCachingForceStateId = Shader.PropertyToID("_DebugShadowCachingForceState"); +#endif static readonly int k_DebugValidateAlbedoMinLuminanceId = Shader.PropertyToID("_DebugValidateAlbedoMinLuminance"); static readonly int k_DebugValidateAlbedoMaxLuminanceId = Shader.PropertyToID("_DebugValidateAlbedoMaxLuminance"); @@ -113,15 +116,35 @@ class DebugHandler : IDebugDisplaySettingsQuery // These modes would require putting custom data into gbuffer, so instead we just disable deferred mode. internal bool IsActiveModeUnsupportedForDeferred => - AreAnySettingsActive && ( - m_DebugDisplaySettings.lightingSettings.lightingDebugMode != DebugLightingMode.None || - m_DebugDisplaySettings.lightingSettings.lightingFeatureFlags != DebugLightingFeatureFlags.None || - m_DebugDisplaySettings.renderingSettings.sceneOverrideMode != DebugSceneOverrideMode.None || - m_DebugDisplaySettings.materialSettings.materialDebugMode != DebugMaterialMode.None || - m_DebugDisplaySettings.materialSettings.vertexAttributeDebugMode != DebugVertexAttributeMode.None || - m_DebugDisplaySettings.materialSettings.materialValidationMode != DebugMaterialValidationMode.None || - m_DebugDisplaySettings.renderingSettings.mipInfoMode != DebugMipInfoMode.None || - m_DebugDisplaySettings.renderingSettings.batchingTypeViewEnabled); + AreAnySettingsActive && IsModeUnsupportedForDeferred( + m_DebugDisplaySettings.lightingSettings, + m_DebugDisplaySettings.materialSettings, + m_DebugDisplaySettings.renderingSettings +#if URP_SHADOW_CACHING + , m_DebugDisplaySettings.shadowCachingSettings +#endif + ); + + internal static bool IsModeUnsupportedForDeferred( + DebugDisplaySettingsLighting lightingSettings, + DebugDisplaySettingsMaterial materialSettings, + DebugDisplaySettingsRendering renderingSettings +#if URP_SHADOW_CACHING + , DebugDisplaySettingsShadowCaching shadowCachingSettings +#endif + ) => + lightingSettings.lightingDebugMode != DebugLightingMode.None || + lightingSettings.lightingFeatureFlags != DebugLightingFeatureFlags.None || + renderingSettings.sceneOverrideMode != DebugSceneOverrideMode.None || + materialSettings.materialDebugMode != DebugMaterialMode.None || + materialSettings.vertexAttributeDebugMode != DebugVertexAttributeMode.None || + materialSettings.materialValidationMode != DebugMaterialValidationMode.None || + renderingSettings.mipInfoMode != DebugMipInfoMode.None || + renderingSettings.batchingTypeViewEnabled +#if URP_SHADOW_CACHING + || shadowCachingSettings.AreAnySettingsActive +#endif + ; /// public bool TryGetScreenClearColor(ref Color color) @@ -359,6 +382,13 @@ internal void ResetCustomDebugTexture() internal bool IsCustomDebugTextureActive => RenderingSettings.fullScreenDebugMode == DebugFullScreenMode.None && m_HasCustomDebugTexture; + // Full screen debug modes are composited by the final blit or final post-processing pass, which only run when + // the camera renders to an intermediate texture + internal bool RequiresIntermediateTexture(bool isPreviewCamera) + { + return IsActiveForCamera(isPreviewCamera) && TryGetFullscreenDebugMode(out _); + } + class DebugFinalValidationPassData { public bool isFinalPass; @@ -498,7 +528,7 @@ internal void UpdateShaderGlobalPropertiesForFinalValidationPass(RenderGraph ren } } - class DebugSetupPassData + internal class DebugSetupPassData { public bool isActiveForCamera; @@ -508,6 +538,9 @@ class DebugSetupPassData public DebugDisplaySettingsMaterial materialSettings; public DebugDisplaySettingsRendering renderingSettings; public DebugDisplaySettingsLighting lightingSettings; +#if URP_SHADOW_CACHING + public DebugDisplaySettingsShadowCaching shadowCachingSettings; +#endif } DebugSetupPassData InitDebugSetupPassData(DebugSetupPassData passData, bool isPreviewCamera) @@ -516,11 +549,14 @@ DebugSetupPassData InitDebugSetupPassData(DebugSetupPassData passData, bool isPr passData.materialSettings = MaterialSettings; passData.renderingSettings = RenderingSettings; passData.lightingSettings = LightingSettings; +#if URP_SHADOW_CACHING + passData.shadowCachingSettings = m_DebugDisplaySettings.shadowCachingSettings; +#endif return passData; } [Conditional("UNITY_ENABLE_CHECKS")] - static void Setup(RasterCommandBuffer cmd, DebugSetupPassData passData) + internal static void Setup(RasterCommandBuffer cmd, DebugSetupPassData passData) { if (passData.isActiveForCamera) { @@ -549,6 +585,9 @@ static void Setup(RasterCommandBuffer cmd, DebugSetupPassData passData) // Lighting settings... cmd.SetGlobalFloat(k_DebugLightingModeId, (int)passData.lightingSettings.lightingDebugMode); cmd.SetGlobalInteger(k_DebugLightingFeatureFlagsId, (int)passData.lightingSettings.lightingFeatureFlags); +#if URP_SHADOW_CACHING + cmd.SetGlobalInteger(k_DebugShadowCachingForceStateId, (int)passData.shadowCachingSettings.forceState); +#endif // Set-up any other persistent properties... cmd.SetGlobalColor(k_DebugColorInvalidModePropertyId, Color.red); diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Debug/ShadowCachingDebugState.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Debug/ShadowCachingDebugState.cs new file mode 100644 index 00000000000..a28813cf714 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Debug/ShadowCachingDebugState.cs @@ -0,0 +1,21 @@ +#if URP_SHADOW_CACHING + +namespace UnityEngine.Rendering.Universal +{ + [GenerateHLSL] + internal enum ShadowCachingDebugState + { + /// No shadow caching debug color. + None, + /// Shadows come from the cache. + Cached, + /// Shadows were rendered into the cache recently. + RecentlyRefreshed, + /// Shadows are rendered this frame. + Live, + /// Shadows do not cover the camera, and nothing has refreshed them. + Stale, + } +} + +#endif diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Debug/ShadowCachingDebugState.cs.hlsl b/Packages/com.unity.render-pipelines.universal/Runtime/Debug/ShadowCachingDebugState.cs.hlsl new file mode 100644 index 00000000000..c88a222b0cb --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Debug/ShadowCachingDebugState.cs.hlsl @@ -0,0 +1,17 @@ +// +// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead +// + +#ifndef SHADOWCACHINGDEBUGSTATE_CS_HLSL +#define SHADOWCACHINGDEBUGSTATE_CS_HLSL +// +// UnityEngine.Rendering.Universal.ShadowCachingDebugState: static fields +// +#define SHADOWCACHINGDEBUGSTATE_NONE (0) +#define SHADOWCACHINGDEBUGSTATE_CACHED (1) +#define SHADOWCACHINGDEBUGSTATE_RECENTLY_REFRESHED (2) +#define SHADOWCACHINGDEBUGSTATE_LIVE (3) +#define SHADOWCACHINGDEBUGSTATE_STALE (4) + + +#endif diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Debug/ShadowCachingDebugState.cs.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Runtime/Debug/ShadowCachingDebugState.cs.hlsl.meta new file mode 100644 index 00000000000..1c54a000b1d --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Debug/ShadowCachingDebugState.cs.hlsl.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 78d240ec74a754ddeb2d8d9dab7989ff +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Debug/ShadowCachingDebugState.cs.meta b/Packages/com.unity.render-pipelines.universal/Runtime/Debug/ShadowCachingDebugState.cs.meta new file mode 100644 index 00000000000..0019d77b7d6 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Debug/ShadowCachingDebugState.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 2d094e6beb4b2477cb63e474bd2c6c37 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Debug/UniversalRenderPipelineDebugDisplaySettings.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Debug/UniversalRenderPipelineDebugDisplaySettings.cs index f3d750ecf8b..1f14d0165ea 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Debug/UniversalRenderPipelineDebugDisplaySettings.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Debug/UniversalRenderPipelineDebugDisplaySettings.cs @@ -46,8 +46,15 @@ public class UniversalRenderPipelineDebugDisplaySettings : DebugDisplaySettings< internal DebugDisplaySettingsSurfaceCache surfaceCacheSettings { get; private set; } #endif + internal DebugDisplaySettingsScreenSpaceReflection screenSpaceReflectionSettings { get; private set; } +#if URP_SHADOW_CACHING + internal DebugDisplaySettingsShadowCaching shadowCachingSettings { get; private set; } +#endif + internal bool isSceneOverrideActive => AreAnySettingsActive && renderingSettings.sceneOverrideMode != DebugSceneOverrideMode.None; + internal bool isHidingDebugOverlays => areDebugOverlaysHidden; + #region IDebugDisplaySettingsQuery /// @@ -114,6 +121,10 @@ public override void Reset() #if SURFACE_CACHE_SUPPORTED || UNITY_EDITOR surfaceCacheSettings = Add(DebugDisplaySerializer.GetOrCreate()); #endif + screenSpaceReflectionSettings = Add(DebugDisplaySerializer.GetOrCreate()); +#if URP_SHADOW_CACHING + shadowCachingSettings = Add(DebugDisplaySerializer.GetOrCreate()); +#endif // This is not a debug property owned by any `IDebugDisplaySettingsData`, it is a static property on `Texture`. // When the user hits reset, we want to make sure texture mip caching is enabled again (regardless of whether the diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/DeferredLights.cs b/Packages/com.unity.render-pipelines.universal/Runtime/DeferredLights.cs index b4bb4c4ceb7..82581d2320b 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/DeferredLights.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/DeferredLights.cs @@ -365,8 +365,6 @@ private void SetupLights(CommandBuffer cmd, UniversalCameraData cameraData, Vect // This should be moved to a more global scope when framebuffer fetch is introduced to more passes cmd.SetKeyword(ShaderGlobalKeywords.RenderPassEnabled, true); cmd.SetKeyword(ShaderGlobalKeywords.LightLayers, UseLightLayers && !CoreUtils.IsSceneLightingDisabled(camera)); - - RenderingLayerUtils.SetupProperties(cmd, RenderingLayerMaskSize); } } @@ -684,7 +682,7 @@ void PrecomputeLights( int visibleLightCount = visibleLights.Length; for (ushort visLightIndex = 0; visLightIndex < visibleLightCount; ++visLightIndex) { - ref VisibleLight vl = ref visibleLights.UnsafeElementAtMutable(visLightIndex); + ref VisibleLight vl = ref visibleLights.UnsafeElementAt(visLightIndex); ++stencilVisLightOffsets[(int)vl.lightType]; } @@ -705,7 +703,7 @@ void PrecomputeLights( for (ushort visLightIndex = 0; visLightIndex < visibleLightCount; ++visLightIndex) { - ref VisibleLight vl = ref visibleLights.UnsafeElementAtMutable(visLightIndex); + ref VisibleLight vl = ref visibleLights.UnsafeElementAt(visLightIndex); if (vl.lightType != LightType.Spot && vl.lightType != LightType.Directional && vl.lightType != LightType.Point) @@ -807,7 +805,7 @@ void RenderStencilDirectionalLights(RasterCommandBuffer cmd, UniversalLightData for (int soffset = m_stencilVisLightOffsets[(int)LightType.Directional]; soffset < m_stencilVisLights.Length; ++soffset) { ushort visLightIndex = m_stencilVisLights[soffset]; - ref VisibleLight vl = ref visibleLights.UnsafeElementAtMutable(visLightIndex); + ref VisibleLight vl = ref visibleLights.UnsafeElementAt(visLightIndex); if (vl.lightType != LightType.Directional) break; @@ -878,7 +876,7 @@ void RenderStencilPointLights(RasterCommandBuffer cmd, UniversalLightData lightD for (int soffset = m_stencilVisLightOffsets[(int)LightType.Point]; soffset < m_stencilVisLights.Length; ++soffset) { ushort visLightIndex = m_stencilVisLights[soffset]; - ref VisibleLight vl = ref visibleLights.UnsafeElementAtMutable(visLightIndex); + ref VisibleLight vl = ref visibleLights.UnsafeElementAt(visLightIndex); if (vl.lightType != LightType.Point) break; @@ -949,7 +947,7 @@ void RenderStencilSpotLights(RasterCommandBuffer cmd, UniversalLightData lightDa { ushort visLightIndex = m_stencilVisLights[soffset]; - ref VisibleLight vl = ref visibleLights.UnsafeElementAtMutable(visLightIndex); + ref VisibleLight vl = ref visibleLights.UnsafeElementAt(visLightIndex); if (vl.lightType != LightType.Spot) break; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Deprecated.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Deprecated.cs index dd08c01ddae..aab074c63ca 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Deprecated.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Deprecated.cs @@ -211,6 +211,111 @@ public LightFalloffMode lightFalloffMode { get => GraphicsSettings.GetRenderPipelineSettings().lightFalloffMode; } + + static bool s_WarnedObsoleteShadowSetter; + + static ShadowsVolumeOverride GetShadowsVolumeFromStack() + { + return VolumeManager.instance.isInitialized ? VolumeManager.instance.stack.GetComponent() : null; + } + + static void WarnObsoleteShadowSetterOnce() + { + if (s_WarnedObsoleteShadowSetter) + return; + + s_WarnedObsoleteShadowSetter = true; + Debug.LogWarning("UniversalRenderPipelineAsset shadow distance and cascade properties are obsolete and have no effect. Edit the ShadowsVolumeOverride in a Volume Profile instead."); + } + +#pragma warning disable 618 // Obsolete warning + /// + /// The maximum shadow distance from the ShadowsVolumeOverride in the current volume stack. Setting it has no effect. + /// + [Obsolete("Moved to the ShadowsVolumeOverride volume component. Setting this value has no effect; edit a VolumeProfile instead. #from(7000.0)", false)] + public float shadowDistance + { + get + { + var shadowsVolume = GetShadowsVolumeFromStack(); + return shadowsVolume != null ? shadowsVolume.maxShadowDistance.value : m_ObsoleteShadowDistance; + } + set => WarnObsoleteShadowSetterOnce(); + } + + /// + /// The shadow cascade count from the ShadowsVolumeOverride in the current volume stack. Setting it has no effect. + /// + [Obsolete("Moved to the ShadowsVolumeOverride volume component. Setting this value has no effect; edit a VolumeProfile instead. #from(7000.0)", false)] + public int shadowCascadeCount + { + get + { + var shadowsVolume = GetShadowsVolumeFromStack(); + return shadowsVolume != null ? shadowsVolume.cascadeCount.value : m_ObsoleteShadowCascadeCount; + } + set => WarnObsoleteShadowSetterOnce(); + } + + /// + /// The first cascade split from the ShadowsVolumeOverride in the current volume stack. Setting it has no effect. + /// + /// Returns a Float with the first cascade split. + [Obsolete("Moved to the ShadowsVolumeOverride volume component. Setting this value has no effect; edit a VolumeProfile instead. #from(7000.0)", false)] + public float cascade2Split + { + get + { + var shadowsVolume = GetShadowsVolumeFromStack(); + return shadowsVolume != null ? shadowsVolume.cascadeSplit0.value : m_ObsoleteCascade2Split; + } + set => WarnObsoleteShadowSetterOnce(); + } + + /// + /// The first two cascade splits from the ShadowsVolumeOverride in the current volume stack. Setting it has no effect. + /// + /// Returns a Vector2 with the first two cascade splits. + [Obsolete("Moved to the ShadowsVolumeOverride volume component. Setting this value has no effect; edit a VolumeProfile instead. #from(7000.0)", false)] + public Vector2 cascade3Split + { + get + { + var shadowsVolume = GetShadowsVolumeFromStack(); + return shadowsVolume != null ? new Vector2(shadowsVolume.cascadeSplit0.value, shadowsVolume.cascadeSplit1.value) : m_ObsoleteCascade3Split; + } + set => WarnObsoleteShadowSetterOnce(); + } + + /// + /// The three cascade splits from the ShadowsVolumeOverride in the current volume stack. Setting it has no effect. + /// + /// Returns a Vector3 with the three cascade splits. + [Obsolete("Moved to the ShadowsVolumeOverride volume component. Setting this value has no effect; edit a VolumeProfile instead. #from(7000.0)", false)] + public Vector3 cascade4Split + { + get + { + var shadowsVolume = GetShadowsVolumeFromStack(); + return shadowsVolume != null ? new Vector3(shadowsVolume.cascadeSplit0.value, shadowsVolume.cascadeSplit1.value, shadowsVolume.cascadeSplit2.value) : m_ObsoleteCascade4Split; + } + set => WarnObsoleteShadowSetterOnce(); + } + + /// + /// The last cascade border from the ShadowsVolumeOverride in the current volume stack. Setting it has no effect. + /// + [Obsolete("Moved to the ShadowsVolumeOverride volume component. Setting this value has no effect; edit a VolumeProfile instead. #from(7000.0)", false)] + public float cascadeBorder + { + get + { + var shadowsVolume = GetShadowsVolumeFromStack(); + return shadowsVolume != null ? shadowsVolume.lastCascadeBorder.value : m_ObsoleteCascadeBorder; + } + set => WarnObsoleteShadowSetterOnce(); + } +#pragma warning restore 618 // Obsolete warning } public abstract partial class ScriptableRenderer diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Fog.meta b/Packages/com.unity.render-pipelines.universal/Runtime/Fog.meta new file mode 100644 index 00000000000..baa45dfb541 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Fog.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 372c4e6f4aef43ad8b6483dcaba296ac +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Fog/FogVolume.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Fog/FogVolume.cs new file mode 100644 index 00000000000..6b69258269b --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Fog/FogVolume.cs @@ -0,0 +1,232 @@ +#if VOLUMETRIC_FOG + +using System; + +namespace UnityEngine.Rendering.Universal +{ + /// + /// Options for how a distributes fog density. + /// + public enum FogVolumeDensityMode + { + /// + /// Applies the same density everywhere inside the fog volume. + /// + Constant, + + /// + /// Modulates the density with a 3D texture. + /// + Texture, + } + + /// + /// Options for how a combines with the global fog and with overlapping fog volumes. + /// + public enum FogVolumeBlendMode + { + /// + /// Replaces the existing fog with this volume's fog. + /// + Overwrite, + + /// + /// Adds this volume's fog to the existing fog. + /// + Add, + + /// + /// Multiplies the existing fog by this volume's fog. + /// + Multiply, + + /// + /// Keeps the lower of the existing fog and this volume's fog. + /// + Min, + + /// + /// Keeps the higher of the existing fog and this volume's fog. + /// + Max, + } + + /// + /// Represents a box-shaped volume that changes the volumetric fog inside it. + /// + /// + /// The GameObject's Transform sets the position, rotation, and size of the box. + /// + [ExecuteAlways] + [AddComponentMenu("Rendering/Fog Volume")] + [Icon("Packages/com.unity.render-pipelines.core/Editor/Icons/Processed/LocalVolumetricFog Icon.asset")] + public sealed class FogVolume : MonoBehaviour + { + [SerializeField] + FogVolumeDensityMode m_DensityMode; + + [SerializeField, Min(0.0f)] + float m_Density = 0.1f; + + [SerializeField, ColorUsage(false)] + Color m_Albedo = Color.white; + + [SerializeField] + Texture m_DensityTexture; + + [SerializeField] + Vector3 m_DensityTextureTiling = Vector3.one; + + [SerializeField] + Vector3 m_DensityTextureScrollSpeed; + + [SerializeField] + FogVolumeBlendMode m_BlendMode = FogVolumeBlendMode.Add; + + [SerializeField] + int m_BlendPriority; + + internal static event Action fogVolumeEnabled; + internal static event Action fogVolumeDisabled; + internal static event Action fogVolumeChanged; + + /// + /// The method the fog volume uses to distribute fog density. + /// + public FogVolumeDensityMode densityMode + { + get => m_DensityMode; + set + { + m_DensityMode = value; + OnValidate(); + } + } + + /// + /// The fog density inside the fog volume. + /// + /// + /// Higher values make the fog thicker. The minimum value is 0. + /// + public float density + { + get => m_Density; + set + { + m_Density = Mathf.Max(0.0f, value); + OnValidate(); + } + } + + /// + /// The color of the light that the fog scatters. + /// + /// + /// The albedo is an SDR color. Each channel is clamped to the range 0 to 1, and alpha is ignored. + /// + public Color albedo + { + get => m_Albedo; + set + { + m_Albedo = new Color(Mathf.Clamp01(value.r), Mathf.Clamp01(value.g), Mathf.Clamp01(value.b), 1.0f); + OnValidate(); + } + } + + /// + /// The 3D texture that modulates the fog when is . + /// + /// + /// The RGB channels tint the albedo, and the alpha channel scales the density. Alpha-only textures only scale the density. + /// The texture must be a or a 3D , otherwise the fog volume has no fog. + /// + public Texture densityTexture + { + get => m_DensityTexture; + set + { + m_DensityTexture = value; + OnValidate(); + } + } + + /// + /// The number of times the density texture repeats across the fog volume along each axis. + /// + public Vector3 densityTextureTiling + { + get => m_DensityTextureTiling; + set + { + m_DensityTextureTiling = value; + OnValidate(); + } + } + + /// + /// The speed at which the density texture moves through the fog volume along each axis, in texture repeats per second. + /// + public Vector3 densityTextureScrollSpeed + { + get => m_DensityTextureScrollSpeed; + set + { + m_DensityTextureScrollSpeed = value; + OnValidate(); + } + } + + /// + /// The method the fog volume uses to combine with the global fog and with overlapping fog volumes. + /// + public FogVolumeBlendMode blendMode + { + get => m_BlendMode; + set + { + m_BlendMode = value; + OnValidate(); + } + } + + /// + /// The order in which overlapping fog volumes blend, from lowest to highest. + /// + public int blendPriority + { + get => m_BlendPriority; + set + { + m_BlendPriority = value; + OnValidate(); + } + } + + void OnEnable() + { + fogVolumeEnabled?.Invoke(this); + } + + void OnDisable() + { + fogVolumeDisabled?.Invoke(this); + } + + void OnValidate() + { + if (!isActiveAndEnabled) + return; + + fogVolumeChanged?.Invoke(this); + } + + void OnDidApplyAnimationProperties() + { + OnValidate(); + } + } +} + +#endif diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Fog/FogVolume.cs.meta b/Packages/com.unity.render-pipelines.universal/Runtime/Fog/FogVolume.cs.meta new file mode 100644 index 00000000000..a8d5e0e6f61 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Fog/FogVolume.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: ae5751f7f381480496abda207a160e86 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Fog/FogVolumeCullingJob.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Fog/FogVolumeCullingJob.cs new file mode 100644 index 00000000000..f384a0cee11 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Fog/FogVolumeCullingJob.cs @@ -0,0 +1,248 @@ +#if VOLUMETRIC_FOG + +using System; +using Unity.Burst; +using Unity.Collections; +using Unity.Jobs; +using Unity.Mathematics; + +namespace UnityEngine.Rendering.Universal +{ + struct FogVolumeProperties + { + public float4 scattering; + public float3 densityTextureTiling; + public float3 densityTextureScrollSpeed; + public int blendPriority; + public EntityId entityId; + public FogVolumeDensityMode densityMode; + public FogVolumeBlendMode blendMode; +#if UNITY_EDITOR + public ulong sceneCullingMask; +#endif + } + + // Must match FogVolumeData in FogVolume.shader. + struct FogVolumeData + { + public float4 axisX; + public float4 axisY; + public float4 axisZ; + public float4 center; + public float4 scattering; + public float4 clipBounds; + public float3 densityTextureTiling; + public uint startSlice; // 16-byte boundary + public float3 densityTextureScrollSpeed; + public uint sliceCount; // 16-byte boundary + public uint densityMode; + public uint3 padding; // 16-byte boundary + } + + struct FogVolumeSortKey : IComparable + { + public int blendPriority; + public EntityId entityId; + public int fogVolumeIndex; + + public int CompareTo(FogVolumeSortKey other) + { + // Blend priority, ascending + int result = blendPriority.CompareTo(other.blendPriority); + + // EntityId, ascending (tie-break) + if (result == 0) + result = entityId.CompareTo(other.entityId); + + return result; + } + } + + struct FogVolumeBox + { + public float3 center; + public float3x3 halfAxes; + public float3x3 worldToLocal; + + public FogVolumeBox(in float4x4 localToWorld) + { + center = localToWorld.c3.xyz; + halfAxes = 0.5f * math.float3x3(localToWorld.c0.xyz, localToWorld.c1.xyz, localToWorld.c2.xyz); + worldToLocal = math.inverse(halfAxes); + } + + public float3 GetCorner(int index) + { + float3 signs = math.select(math.float3(-1.0f), math.float3(1.0f), (index & math.int3(1, 2, 4)) != 0); + return center + math.mul(halfAxes, signs); + } + + public bool IsBehindPlane(float4 plane) + { + float radius = math.csum(math.abs(math.mul(plane.xyz, halfAxes))); + return math.dot(plane.xyz, center) + plane.w < -radius; + } + + public float GetDistance(float3 point) + { + float3 offset = point - center; + float3 pointLS = math.mul(worldToLocal, offset); + float3 excess = pointLS - math.clamp(pointLS, -1.0f, 1.0f); + if (math.all(excess == 0.0f)) + return 0.0f; + + // Exact for orthogonal axes and never overestimates for sheared ones. + float3 direction = math.normalize(math.mul(halfAxes, excess)); + return math.max(0.0f, math.dot(direction, offset) - math.csum(math.abs(math.mul(direction, halfAxes)))); + } + } + + [BurstCompile] + struct FogVolumeCullingJob : IJob + { + const float k_MinHalfExtent = 0.0005f; + + [ReadOnly] public NativeArray boxes; + [ReadOnly] public NativeArray properties; + [ReadOnly] public NativeArray layers; + public int fogVolumeCount; + + public int cullingMask; +#if UNITY_EDITOR + public ulong sceneCullingMask; +#endif + public float4x4 worldToClip; + public float4x4 worldToGPUClip; + public float3 cameraPosition; + public float maxDistance; + public float4 encodingParams; + public int sliceCount; + public float2 voxelSizeNDC; + + public NativeArray sortKeys; + public NativeArray fogVolumeData; + public NativeArray blendModes; + public NativeReference visibleCount; + + public void Execute() + { + var rows = math.transpose(worldToClip); + var left = rows.c3 + rows.c0; + var right = rows.c3 - rows.c0; + var bottom = rows.c3 + rows.c1; + var top = rows.c3 - rows.c1; + + int count = 0; + for (int i = 0; i < fogVolumeCount; ++i) + { + if ((cullingMask & (1 << layers[i])) == 0) + continue; + +#if UNITY_EDITOR + if ((sceneCullingMask & properties[i].sceneCullingMask) == 0) + continue; +#endif + + var box = boxes[i]; + + if (math.abs(math.determinant(box.halfAxes)) < k_MinHalfExtent * k_MinHalfExtent * k_MinHalfExtent) + continue; + + if (box.IsBehindPlane(left) || + box.IsBehindPlane(right) || + box.IsBehindPlane(bottom) || + box.IsBehindPlane(top)) + continue; + + if (box.GetDistance(cameraPosition) >= maxDistance) + continue; + + sortKeys[count++] = new FogVolumeSortKey + { + blendPriority = properties[i].blendPriority, + entityId = properties[i].entityId, + fogVolumeIndex = i, + }; + } + + sortKeys.GetSubArray(0, count).Sort(); + + for (int i = 0; i < count; ++i) + { + int fogVolumeIndex = sortKeys[i].fogVolumeIndex; + var fogVolumeProperties = properties[fogVolumeIndex]; + fogVolumeData[i] = ConvertToGPUData(boxes[fogVolumeIndex], fogVolumeProperties); + blendModes[i] = fogVolumeProperties.blendMode; + } + + visibleCount.Value = count; + } + + FogVolumeData ConvertToGPUData(in FogVolumeBox box, in FogVolumeProperties fogVolumeProperties) + { + float nearestDistance = box.GetDistance(cameraPosition); + float farthestDistance = 0.0f; + float2 clipMin = float.MaxValue; + float2 clipMax = float.MinValue; + bool coversScreen = nearestDistance == 0.0f; + + for (int corner = 0; corner < 8; ++corner) + { + float3 cornerWS = box.GetCorner(corner); + farthestDistance = math.max(farthestDistance, math.distance(cornerWS, cameraPosition)); + + float4 cornerCS = math.mul(worldToGPUClip, math.float4(cornerWS, 1.0f)); + if (cornerCS.w <= 0.0f) + { + coversScreen = true; + continue; + } + + float2 cornerNDC = cornerCS.xy / cornerCS.w; + clipMin = math.min(clipMin, cornerNDC); + clipMax = math.max(clipMax, cornerNDC); + } + + if (coversScreen) + { + clipMin = -1.0f; + clipMax = 1.0f; + } + else + { + clipMin = math.max(clipMin - voxelSizeNDC, -1.0f); + clipMax = math.min(clipMax + voxelSizeNDC, 1.0f); + } + + int startSlice = math.clamp(GetSlice(nearestDistance) - 1, 0, sliceCount - 1); + int endSlice = math.clamp(GetSlice(farthestDistance) + 1, 0, sliceCount - 1); + + var worldToLocalRows = math.transpose(box.worldToLocal); + + return new FogVolumeData + { + axisX = math.float4(worldToLocalRows.c0, 0.0f), + axisY = math.float4(worldToLocalRows.c1, 0.0f), + axisZ = math.float4(worldToLocalRows.c2, 0.0f), + center = math.float4(box.center, 0.0f), + scattering = fogVolumeProperties.scattering, + clipBounds = math.float4(clipMin, clipMax - clipMin), + densityTextureTiling = fogVolumeProperties.densityTextureTiling, + startSlice = (uint)startSlice, + densityTextureScrollSpeed = fogVolumeProperties.densityTextureScrollSpeed, + sliceCount = (uint)(endSlice - startSlice + 1), + densityMode = (uint)fogVolumeProperties.densityMode, + }; + } + + // Mirrors EncodeLogarithmicDepthGeneralized() in Common.hlsl. + int GetSlice(float distance) + { + float encoded = encodingParams.x + + encodingParams.y * math.log2(math.max(0.0f, distance - encodingParams.z)); + return (int)math.floor(math.saturate(encoded) * sliceCount); + } + } +} + +#endif diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Fog/FogVolumeCullingJob.cs.meta b/Packages/com.unity.render-pipelines.universal/Runtime/Fog/FogVolumeCullingJob.cs.meta new file mode 100644 index 00000000000..2404fb69e15 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Fog/FogVolumeCullingJob.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 14483dfe394fa324bb2254f729781227 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Fog/FogVolumeManager.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Fog/FogVolumeManager.cs new file mode 100644 index 00000000000..d7229babda7 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Fog/FogVolumeManager.cs @@ -0,0 +1,281 @@ +#if VOLUMETRIC_FOG + +using System; +using System.Collections.Generic; +using Unity.Collections; +using Unity.Jobs; +using Unity.Mathematics; +using UnityEngine.Jobs; +#if UNITY_EDITOR +using UnityEditor; +using UnityEditor.SceneManagement; +#endif + +namespace UnityEngine.Rendering.Universal +{ + sealed class FogVolumeManager : IDisposable + { + const int k_CapacityGranularity = 16; + const int k_TransformBatchSize = 32; + + static readonly ProfilingSampler s_BeginContextRenderingSampler = new ProfilingSampler($"{nameof(FogVolumeManager)}.{nameof(OnBeginContextRendering)}"); + static readonly ProfilingSampler s_ScheduleCullingSampler = new ProfilingSampler($"{nameof(FogVolumeManager)}.{nameof(ScheduleCulling)}"); + static readonly ProfilingSampler s_CompleteCullingSampler = new ProfilingSampler($"{nameof(FogVolumeManager)}.{nameof(CompleteCulling)}"); + + readonly List m_FogVolumes = new List(); + readonly Dictionary m_FogVolumeIndices = new Dictionary(); + + TransformAccessArray m_Transforms; + NativeArray m_Boxes; + NativeArray m_Properties; + NativeArray m_Layers; + + NativeArray m_SortKeys; + NativeArray m_VisibleFogVolumeData; + NativeArray m_VisibleBlendModes; + NativeReference m_VisibleCount; + + JobHandle m_JobHandle; + + internal int fogVolumeCount => m_FogVolumes.Count; + internal NativeArray visibleFogVolumeData => m_VisibleFogVolumeData; + internal NativeArray visibleBlendModes => m_VisibleBlendModes; + + internal FogVolumeManager() + { + FogVolume.fogVolumeEnabled += OnFogVolumeEnabled; + FogVolume.fogVolumeDisabled += OnFogVolumeDisabled; + FogVolume.fogVolumeChanged += OnFogVolumeChanged; + RenderPipelineManager.beginContextRendering += OnBeginContextRendering; +#if UNITY_EDITOR + SceneVisibilityManager.visibilityChanged += OnSceneVisibilityChanged; +#endif + + // Runs once on instantiation to pick up fog volumes enabled before the manager existed. + foreach (var fogVolume in Object.FindObjectsByType()) + { + if (fogVolume.isActiveAndEnabled) + OnFogVolumeEnabled(fogVolume); + } + } + + public void Dispose() + { + FogVolume.fogVolumeEnabled -= OnFogVolumeEnabled; + FogVolume.fogVolumeDisabled -= OnFogVolumeDisabled; + FogVolume.fogVolumeChanged -= OnFogVolumeChanged; + RenderPipelineManager.beginContextRendering -= OnBeginContextRendering; +#if UNITY_EDITOR + SceneVisibilityManager.visibilityChanged -= OnSceneVisibilityChanged; +#endif + + if (m_FogVolumes.Count > 0) + Deallocate(); + + m_FogVolumes.Clear(); + m_FogVolumeIndices.Clear(); + } + + void OnFogVolumeEnabled(FogVolume fogVolume) + { + int index = m_FogVolumes.Count; + if (!m_FogVolumeIndices.TryAdd(fogVolume, index)) + return; + + if (m_FogVolumes.Count == 0) + { + int initialCapacity = GetCapacity(1); + m_Transforms = new TransformAccessArray(initialCapacity); + m_Boxes = new NativeArray(initialCapacity, Allocator.Persistent); + m_Properties = new NativeArray(initialCapacity, Allocator.Persistent); + m_Layers = new NativeArray(initialCapacity, Allocator.Persistent); + m_SortKeys = new NativeArray(initialCapacity, Allocator.Persistent); + m_VisibleFogVolumeData = new NativeArray(initialCapacity, Allocator.Persistent); + m_VisibleBlendModes = new NativeArray(initialCapacity, Allocator.Persistent); + m_VisibleCount = new NativeReference(Allocator.Persistent); + } + + m_JobHandle.Complete(); + + m_FogVolumes.Add(fogVolume); + if (m_Boxes.Length < m_FogVolumes.Count) + { + int capacity = GetCapacity(m_FogVolumes.Count); + m_Boxes.ResizeArray(capacity); + m_Properties.ResizeArray(capacity); + m_Layers.ResizeArray(capacity); + m_SortKeys.ResizeArray(capacity); + m_VisibleFogVolumeData.ResizeArray(capacity); + m_VisibleBlendModes.ResizeArray(capacity); + } + + m_Transforms.Add(fogVolume.transform); + m_Boxes[index] = new FogVolumeBox(fogVolume.transform.localToWorldMatrix); + m_Layers[index] = fogVolume.gameObject.layer; + WriteProperties(fogVolume, index); + } + + void OnFogVolumeDisabled(FogVolume fogVolume) + { + if (!m_FogVolumeIndices.Remove(fogVolume, out int index)) + return; + + m_JobHandle.Complete(); + + int lastIndex = m_FogVolumes.Count - 1; + var lastFogVolume = m_FogVolumes[lastIndex]; + m_FogVolumes[index] = lastFogVolume; + m_FogVolumes.RemoveAt(lastIndex); + if (index != lastIndex) + m_FogVolumeIndices[lastFogVolume] = index; + + if (m_FogVolumes.Count == 0) + { + Deallocate(); + return; + } + + m_Transforms.RemoveAtSwapBack(index); + m_Boxes[index] = m_Boxes[lastIndex]; + m_Properties[index] = m_Properties[lastIndex]; + m_Layers[index] = m_Layers[lastIndex]; + } + + void OnBeginContextRendering(ScriptableRenderContext context, List cameras) + { + if (m_FogVolumes.Count == 0) + return; + + using var _ = new ProfilingScope(s_BeginContextRenderingSampler); + m_JobHandle.Complete(); + + for (int i = 0; i < m_FogVolumes.Count; ++i) + m_Layers[i] = m_FogVolumes[i].gameObject.layer; + + var transformJob = new FogVolumeTransformJob { boxes = m_Boxes }; + m_JobHandle = transformJob.ScheduleReadOnly(m_Transforms, k_TransformBatchSize); + JobHandle.ScheduleBatchedJobs(); + } + + void OnFogVolumeChanged(FogVolume fogVolume) + { + if (!m_FogVolumeIndices.TryGetValue(fogVolume, out int index)) + return; + + m_JobHandle.Complete(); + WriteProperties(fogVolume, index); + } + +#if UNITY_EDITOR + void OnSceneVisibilityChanged() + { + m_JobHandle.Complete(); + for (int i = 0; i < m_FogVolumes.Count; ++i) + WriteProperties(m_FogVolumes[i], i); + } +#endif + + internal void ScheduleCulling( + UniversalCameraData cameraData, + in VBufferParams vBufferParams, + float cutoffDistance) + { + if (m_FogVolumes.Count == 0) + return; + + using var _ = new ProfilingScope(s_ScheduleCullingSampler); + + var camera = cameraData.camera; + var worldToCamera = cameraData.GetViewMatrix(); + var projection = cameraData.GetProjectionMatrixNoJitter(); + var cullingJob = new FogVolumeCullingJob + { + boxes = m_Boxes, + properties = m_Properties, + layers = m_Layers, + fogVolumeCount = m_FogVolumes.Count, + cullingMask = camera.cullingMask, + worldToClip = projection * worldToCamera, + worldToGPUClip = GL.GetGPUProjectionMatrix(projection, true) * worldToCamera, + cameraPosition = camera.transform.position, + maxDistance = camera.nearClipPlane + cutoffDistance, + encodingParams = vBufferParams.encodingParams, + sliceCount = vBufferParams.sliceCount, + voxelSizeNDC = math.float2(2.0f * vBufferParams.viewportSize.z, 2.0f * vBufferParams.viewportSize.w), + sortKeys = m_SortKeys, + fogVolumeData = m_VisibleFogVolumeData, + blendModes = m_VisibleBlendModes, + visibleCount = m_VisibleCount, + }; +#if UNITY_EDITOR + // A hidden prefab context is applied by native culling, not by the camera's scene culling mask. + var prefabStage = PrefabStageUtility.GetCurrentPrefabStage(); + if (camera.cameraType == CameraType.SceneView && + prefabStage != null && + CoreUtils.IsSceneViewPrefabStageContextHidden()) + cullingJob.sceneCullingMask = EditorSceneManager.GetSceneCullingMask(prefabStage.scene); + else + cullingJob.sceneCullingMask = RenderingUtils.GetSceneCullingMaskFromCamera(camera); +#endif + + m_JobHandle = cullingJob.Schedule(m_JobHandle); + JobHandle.ScheduleBatchedJobs(); + } + + internal int CompleteCulling() + { + using var _ = new ProfilingScope(s_CompleteCullingSampler); + m_JobHandle.Complete(); + return m_VisibleCount.Value; + } + + void WriteProperties(FogVolume fogVolume, int index) + { + Color albedo = fogVolume.albedo; + float density = fogVolume.density; + + var properties = new FogVolumeProperties + { + scattering = math.float4(albedo.r * density, albedo.g * density, albedo.b * density, density), + densityTextureTiling = fogVolume.densityTextureTiling, + densityTextureScrollSpeed = fogVolume.densityTextureScrollSpeed, + blendPriority = fogVolume.blendPriority, + entityId = fogVolume.GetEntityId(), + densityMode = fogVolume.densityMode, + blendMode = fogVolume.blendMode, + }; +#if UNITY_EDITOR + var gameObject = fogVolume.gameObject; + properties.sceneCullingMask = SceneVisibilityManager.instance.IsHidden(gameObject) + ? SceneCullingMasks.GameViewObjects + : gameObject.sceneCullingMask; +#endif + m_Properties[index] = properties; + } + + internal FogVolume GetVisibleFogVolume(int visibleIndex) + { + return m_FogVolumes[m_SortKeys[visibleIndex].fogVolumeIndex]; + } + + void Deallocate() + { + m_JobHandle.Complete(); + m_Transforms.Dispose(); + m_Boxes.Dispose(); + m_Properties.Dispose(); + m_Layers.Dispose(); + m_SortKeys.Dispose(); + m_VisibleFogVolumeData.Dispose(); + m_VisibleBlendModes.Dispose(); + m_VisibleCount.Dispose(); + } + + static int GetCapacity(int count) + { + return CoreUtils.DivRoundUp(count, k_CapacityGranularity) * k_CapacityGranularity; + } + } +} + +#endif diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Fog/FogVolumeManager.cs.meta b/Packages/com.unity.render-pipelines.universal/Runtime/Fog/FogVolumeManager.cs.meta new file mode 100644 index 00000000000..3a245c41dae --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Fog/FogVolumeManager.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: db07b2050a202f14294a27a61b0869cf \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Fog/FogVolumeTransformJob.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Fog/FogVolumeTransformJob.cs new file mode 100644 index 00000000000..db2f890183d --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Fog/FogVolumeTransformJob.cs @@ -0,0 +1,21 @@ +#if VOLUMETRIC_FOG + +using Unity.Burst; +using Unity.Collections; +using UnityEngine.Jobs; + +namespace UnityEngine.Rendering.Universal +{ + [BurstCompile] + struct FogVolumeTransformJob : IJobParallelForTransform + { + [WriteOnly] public NativeArray boxes; + + public void Execute(int index, TransformAccess transform) + { + boxes[index] = new FogVolumeBox(transform.localToWorldMatrix); + } + } +} + +#endif diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Fog/FogVolumeTransformJob.cs.meta b/Packages/com.unity.render-pipelines.universal/Runtime/Fog/FogVolumeTransformJob.cs.meta new file mode 100644 index 00000000000..f114c63dd80 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Fog/FogVolumeTransformJob.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: b0c949c9f131d0a4198f0883a52b3492 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/ForwardLights.cs b/Packages/com.unity.render-pipelines.universal/Runtime/ForwardLights.cs index 544e0c5b0d9..198d160d1bb 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/ForwardLights.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/ForwardLights.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; +using Unity.Burst; using Unity.Collections; using Unity.Jobs; using Unity.Mathematics; @@ -85,7 +86,7 @@ static class LightShaderPropertyId bool m_UseAdditionalLightsConstantBuffer; - bool m_UseForwardPlus; + bool m_UseClustering; int m_DirectionalLightCount; int m_ActualTileWidth; int2 m_TileResolution; @@ -95,6 +96,9 @@ static class LightShaderPropertyId // Forward+ cluster data uses StructuredBuffers (SSBOs) when possible and optimal bool m_UseForwardPlusStructuredBuffer; + // True while clustering jobs have been kicked off, but data has not yet uploaded to the GPU. + internal bool hasPendingClusteringData => m_ZBins.IsCreated; + const string k_ZBinBufferName = "URP Z-Bin Buffer"; NativeArray m_ZBins; GraphicsBuffer m_ZBinsBuffer; @@ -102,6 +106,7 @@ static class LightShaderPropertyId const string k_TileBufferName = "URP Tile Buffer"; NativeArray m_TileMasks; GraphicsBuffer m_TileMasksBuffer; + int m_TileMasksBufferWords; LightCookieManager m_LightCookieManager; ReflectionProbeManager m_ReflectionProbeManager; @@ -110,11 +115,13 @@ static class LightShaderPropertyId float m_ZBinOffset; int m_LightCount; int m_BinCount; + int m_UsedZBinWords; + int m_UsedTileWords; internal struct InitParams { public LightCookieManager lightCookieManager; - public bool forwardPlus; + public bool clustering; static internal InitParams Create() { @@ -129,7 +136,7 @@ static internal InitParams Create() } p.lightCookieManager = new LightCookieManager(ref settings); - p.forwardPlus = false; + p.clustering = false; } return p; } @@ -144,19 +151,19 @@ internal ForwardLights(InitParams initParams) { m_UseAdditionalLightsConstantBuffer = RenderingUtils.usePersistentConstantBuffer; m_UseForwardPlusStructuredBuffer = RenderingUtils.useStructuredBuffer; - m_UseForwardPlus = initParams.forwardPlus; + m_UseClustering = initParams.clustering; m_MaxVisibleAdditionalLights = UniversalRenderPipeline.maxVisibleAdditionalLights; if (m_UseAdditionalLightsConstantBuffer) { - CreateAdditionalLightsConstantBuffer(); + CreateAdditionalLightsConstantBufferSideArrays(); } else { CreateAdditionalLightsLooseUniformArrays(); } - if (m_UseForwardPlus) + if (m_UseClustering) { CreateForwardPlusBuffers(); m_ReflectionProbeManager = ReflectionProbeManager.Create(); @@ -165,8 +172,25 @@ internal ForwardLights(InitParams initParams) m_LightCookieManager = initParams.lightCookieManager; } - void CreateAdditionalLightsConstantBuffer() + // CPU side arrays of the constant buffer path. They are not GPU resources and consumers read them + // unconditionally (volumetric fog), so unlike the buffer itself they stay allocated with the renderer. + void CreateAdditionalLightsConstantBufferSideArrays() + { + m_AdditionalLightsLayerMasks = new float[m_MaxVisibleAdditionalLights]; +#if VOLUMETRIC_FOG + m_AdditionalLightsVolumetricParams = new Vector4[m_MaxVisibleAdditionalLights]; +#endif + } + + // The GPU side is allocated on first use, so content without any additional light never pays for it. + // PreSetup calls it when the frame is recorded, because volumetric fog reads the buffer when its pass is + // recorded. SetupAdditionalLightConstants calls it again before filling the buffer, for the cameras recorded + // without PreSetup (offscreen depth targets). + void EnsureAdditionalLightsConstantBuffer() { + if (m_AdditionalLightsData.IsCreated) + return; + int length = m_MaxVisibleAdditionalLights * k_AdditionalLightsChannelCount; m_AdditionalLightsData = new NativeArray(length, Allocator.Persistent); @@ -178,10 +202,6 @@ void CreateAdditionalLightsConstantBuffer() name = k_AdditionalLightsCBName }; } - m_AdditionalLightsLayerMasks = new float[m_MaxVisibleAdditionalLights]; -#if VOLUMETRIC_FOG - m_AdditionalLightsVolumetricParams = new Vector4[m_MaxVisibleAdditionalLights]; -#endif } void DisposeAdditionalLightsConstantBuffer() @@ -209,8 +229,7 @@ void CreateAdditionalLightsLooseUniformArrays() void CreateForwardPlusBuffers() { - m_ZBins = new NativeArray(UniversalRenderPipeline.maxZBinWords, Allocator.Persistent); - m_TileMasks = new NativeArray(UniversalRenderPipeline.maxTileWords, Allocator.Persistent); + m_TileMasksBufferWords = UniversalRenderPipeline.maxTileWords; if (m_UseForwardPlusStructuredBuffer) { @@ -225,6 +244,16 @@ void CreateForwardPlusBuffers() } m_ZBinsBuffer.name = k_ZBinBufferName; m_TileMasksBuffer.name = k_TileBufferName; + + // Uploads only cover the used words, which can be zero; GLES allocates buffer storage on the first upload. + ClearBuffer(m_ZBinsBuffer); + ClearBuffer(m_TileMasksBuffer); + } + + static void ClearBuffer(GraphicsBuffer buffer) + { + using var zeros = new NativeArray(buffer.count * buffer.stride / sizeof(uint), Allocator.Temp); + buffer.SetData(zeros); } void ResizeAdditionalLightsBuffer(int maxLights) @@ -232,8 +261,9 @@ void ResizeAdditionalLightsBuffer(int maxLights) m_MaxVisibleAdditionalLights = maxLights; if (m_UseAdditionalLightsConstantBuffer) { + // The buffer is allocated again, with the new max count, by the next EnsureAdditionalLightsConstantBuffer. DisposeAdditionalLightsConstantBuffer(); - CreateAdditionalLightsConstantBuffer(); + CreateAdditionalLightsConstantBufferSideArrays(); } else { @@ -329,6 +359,9 @@ internal static JobHandle ScheduleClusteringJobs( out int wordsPerTile ) { + // Also bounds an infinite far plane, which a camera accepts though its projection is then not renderable. + farClipPlane = math.min(farClipPlane, TilingJob.k_MaxDistance); + localLightCount = supportsAdditionalLights ? lights.Length: 0; // The lights array first has directional lights, and then local lights. We traverse the list to find the // index of the first local light. @@ -382,49 +415,59 @@ out int wordsPerTile binCount = (int)(farClipPlane * zBinScale + zBinOffset); } - // Necessary to avoid negative bin count when the farClipPlane is set to Infinity in the editor. - binCount = Math.Max(binCount, 0); + // At least one bin keeps the shader's last-bin clamp valid. + binCount = Math.Max(binCount, 1); + + // Nothing to cluster: one empty bin per view, which the shader's last-bin clamp always reads, and no tile words. + if (itemsPerTile == 0) + { + binCount = 1; + for (var i = 0; i < ZBinningJob.headerLength * viewCount; i++) + zBins[i] = ZBinningJob.emptyHeader; + return default; + } - var minMaxZs = new NativeArray(itemsPerTile * viewCount, Allocator.TempJob); + var minMaxZBins = new NativeArray(itemsPerTile * viewCount, Allocator.TempJob); + var zBinMapping = new ZBinMapping { scale = zBinScale, offset = zBinOffset, binCount = binCount, isOrthographic = isOrthographic }; - var lightMinMaxZJob = new LightMinMaxZJob + var lightMinMaxZBinsJob = new LightMinMaxZBinsJob { worldToViews = worldToViews, lights = localLights, - minMaxZs = minMaxZs.GetSubArray(0, localLightCount * viewCount), - near = nearClipPlane + minMaxZBins = minMaxZBins.GetSubArray(0, localLightCount * viewCount), + near = nearClipPlane, + zBinMapping = zBinMapping }; // 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()); + var lightMinMaxZBinsHandle = localLightCount > 0 ? lightMinMaxZBinsJob.ScheduleParallel(localLightCount * viewCount, 32, default) : default; var reflectionProbeRotation = GraphicsSettings.TryGetRenderPipelineSettings(out var reflectionProbeSettings) ? reflectionProbeSettings.UseReflectionProbeRotation : true; - var reflectionProbeMinMaxZJob = new ReflectionProbeMinMaxZJob + var reflectionProbeMinMaxZBinsJob = new ReflectionProbeMinMaxZBinsJob { worldToViews = worldToViews, reflectionProbes = probes, reflectionProbeRotation = reflectionProbeRotation, - minMaxZs = minMaxZs.GetSubArray(localLightCount * viewCount, reflectionProbeCount * viewCount) + minMaxZBins = minMaxZBins.GetSubArray(localLightCount * viewCount, reflectionProbeCount * viewCount), + near = nearClipPlane, + zBinMapping = zBinMapping }; - var reflectionProbeMinMaxZHandle = reflectionProbeMinMaxZJob.ScheduleParallel(reflectionProbeCount * viewCount, 32, lightMinMaxZHandle); + var reflectionProbeMinMaxZBinsHandle = reflectionProbeCount > 0 ? reflectionProbeMinMaxZBinsJob.ScheduleParallel(reflectionProbeCount * viewCount, 32, lightMinMaxZBinsHandle) : lightMinMaxZBinsHandle; var zBinningBatchCount = (binCount + ZBinningJob.batchSize - 1) / ZBinningJob.batchSize; var zBinningJob = new ZBinningJob { bins = zBins, - minMaxZs = minMaxZs, - zBinScale = zBinScale, - zBinOffset = zBinOffset, + minMaxZBins = minMaxZBins, binCount = binCount, wordsPerTile = wordsPerTile, lightCount = localLightCount, reflectionProbeCount = reflectionProbeCount, batchCount = zBinningBatchCount, viewCount = viewCount, - isOrthographic = isOrthographic }; - var zBinningHandle = zBinningJob.ScheduleParallel(zBinningBatchCount * viewCount, 1, reflectionProbeMinMaxZHandle); + var zBinningHandle = zBinningJob.ScheduleParallel(zBinningBatchCount * viewCount, 1, reflectionProbeMinMaxZBinsHandle); GetViewParams(isOrthographic, viewToClips[0], out float viewPlaneBottom0, out float viewPlaneTop0, out float4 viewToViewportScaleBias0); GetViewParams(isOrthographic, viewToClips[1], out float viewPlaneBottom1, out float viewPlaneTop1, out float4 viewToViewportScaleBias1); @@ -448,10 +491,11 @@ out int wordsPerTile viewToViewportScaleBiases = new Fixed2(viewToViewportScaleBias0, viewToViewportScaleBias1), tileCount = tileResolution, near = nearClipPlane, + far = farClipPlane, isOrthographic = isOrthographic }; - var tileRangeHandle = tilingJob.ScheduleParallel(itemsPerTile * viewCount, 1, reflectionProbeMinMaxZHandle); + var tileRangeHandle = tilingJob.ScheduleParallel(itemsPerTile * viewCount, 1, default); var expansionJob = new TileRangeExpansionJob { @@ -464,10 +508,24 @@ out int wordsPerTile }; var tilingHandle = expansionJob.ScheduleParallel(tileResolution.y * viewCount, 1, tileRangeHandle); - JobHandle cullingHandle = JobHandle.CombineDependencies( - minMaxZs.Dispose(zBinningHandle), - tileRanges.Dispose(tilingHandle)); - return cullingHandle; + var disposeJob = new DisposeClusteringScratchJob { minMaxZBins = minMaxZBins, tileRanges = tileRanges }; + return disposeJob.Schedule(JobHandle.CombineDependencies(zBinningHandle, tilingHandle)); + } + + // Frees the per-schedule scratch arrays in one job instead of one dispose job each. + [BurstCompile] + struct DisposeClusteringScratchJob : IJob + { + [ReadOnly, DeallocateOnJobCompletion] + public NativeArray minMaxZBins; + + [ReadOnly, DeallocateOnJobCompletion] + public NativeArray tileRanges; + + public void Execute() + { + // Nothing to do: the job only exists to free its arrays after both clustering chains. + } } internal void PreSetup(UniversalRenderingData renderingData, UniversalCameraData cameraData, UniversalLightData lightData) @@ -478,33 +536,28 @@ internal void PreSetup(UniversalRenderingData renderingData, UniversalCameraData ResizeAdditionalLightsBuffer(maxLights); } - if (m_UseForwardPlus) + if (m_UseAdditionalLightsConstantBuffer && lightData.additionalLightsCount > 0) + EnsureAdditionalLightsConstantBuffer(); + + if (m_UseClustering) { using var _ = new ProfilingScope(m_ProfilingSamplerFPSetup); m_ReflectionProbeManager.PreSetup(); - if (!m_CullingHandle.IsCompleted) - { - throw new InvalidOperationException("Forward+ jobs have not completed yet."); - } - - if (m_TileMasks.Length != UniversalRenderPipeline.maxTileWords) + if (m_TileMasksBufferWords != UniversalRenderPipeline.maxTileWords) { - m_ZBins.Dispose(); m_ZBinsBuffer.Dispose(); - m_TileMasks.Dispose(); m_TileMasksBuffer.Dispose(); CreateForwardPlusBuffers(); } - else - { - unsafe - { - UnsafeUtility.MemClear(m_ZBins.GetUnsafePtr(), m_ZBins.Length * sizeof(uint)); - UnsafeUtility.MemClear(m_TileMasks.GetUnsafePtr(), m_TileMasks.Length * sizeof(uint)); - } - } + + Debug.Assert(!hasPendingClusteringData, "Clustering data from a previous render was never uploaded."); + if (hasPendingClusteringData) + DisposeClusteringData(); + + m_ZBins = new NativeArray(UniversalRenderPipeline.maxZBinWords, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); + m_TileMasks = new NativeArray(UniversalRenderPipeline.maxTileWords, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); #if ENABLE_VR && ENABLE_XR_MODULE var viewCount = cameraData.xr.enabled && cameraData.xr.singlePassEnabled ? 2 : 1; @@ -539,6 +592,9 @@ internal void PreSetup(UniversalRenderingData renderingData, UniversalCameraData out m_WordsPerTile ); + m_UsedZBinWords = m_BinCount * (ZBinningJob.headerLength + m_WordsPerTile) * viewCount; + m_UsedTileWords = m_TileResolution.x * m_TileResolution.y * m_WordsPerTile * viewCount; + JobHandle.ScheduleBatchedJobs(); } } @@ -580,31 +636,23 @@ internal void SetupLights(UnsafeCommandBuffer cmd, UniversalRenderingData render bool additionalLightsPerVertex = lightData.shadeAdditionalLightsPerVertex; using (new ProfilingScope(m_ProfilingSampler)) { - if (m_UseForwardPlus) + if (m_UseClustering) { if (lightData.reflectionProbeAtlas) { m_ReflectionProbeManager.UpdateGpuData(cameraData, CommandBufferHelpers.GetNativeCommandBuffer(cmd), ref renderingData.cullResults); } - using (new ProfilingScope(m_ProfilingSamplerFPComplete)) - { - m_CullingHandle.Complete(); - } - - using (new ProfilingScope(m_ProfilingSamplerFPUpload)) + // No clustering data when PreSetup was skipped, e.g. for offscreen depth cameras, which shade no lights. + if (m_ZBins.IsCreated) { if (m_UseForwardPlusStructuredBuffer) { - m_ZBinsBuffer.SetData(m_ZBins); - m_TileMasksBuffer.SetData(m_TileMasks); cmd.SetGlobalBuffer(LightShaderPropertyId._ZBins, m_ZBinsBuffer); cmd.SetGlobalBuffer(LightShaderPropertyId._Tiles, m_TileMasksBuffer); } else { - m_ZBinsBuffer.SetData(m_ZBins.Reinterpret(UnsafeUtility.SizeOf())); - m_TileMasksBuffer.SetData(m_TileMasks.Reinterpret(UnsafeUtility.SizeOf())); cmd.SetGlobalConstantBuffer(m_ZBinsBuffer, LightShaderPropertyId._ZBinBuffer, 0, UniversalRenderPipeline.maxZBinWords * 4); cmd.SetGlobalConstantBuffer(m_TileMasksBuffer, LightShaderPropertyId._TileBuffer, 0, UniversalRenderPipeline.maxTileWords * 4); } @@ -617,10 +665,10 @@ internal void SetupLights(UnsafeCommandBuffer cmd, UniversalRenderingData render cmd.SetKeyword(ShaderGlobalKeywords.Exposure, useExposure); bool lightCountCheck = (cameraData.renderer.stripAdditionalLightOffVariants && lightData.supportsAdditionalLights) || additionalLightsCount > 0; - cmd.SetKeyword(ShaderGlobalKeywords.AdditionalLightsVertex, lightCountCheck && additionalLightsPerVertex && !m_UseForwardPlus); - cmd.SetKeyword(ShaderGlobalKeywords.AdditionalLightsPixel, lightCountCheck && !additionalLightsPerVertex && !m_UseForwardPlus); - cmd.SetKeyword(ShaderGlobalKeywords.ClusterLightLoop, m_UseForwardPlus); - cmd.SetKeyword(ShaderGlobalKeywords.ForwardPlus, m_UseForwardPlus); // Backward compatibility. Deprecated in 6.1. + cmd.SetKeyword(ShaderGlobalKeywords.AdditionalLightsVertex, lightCountCheck && additionalLightsPerVertex && !m_UseClustering); + cmd.SetKeyword(ShaderGlobalKeywords.AdditionalLightsPixel, lightCountCheck && !additionalLightsPerVertex && !m_UseClustering); + cmd.SetKeyword(ShaderGlobalKeywords.ClusterLightLoop, m_UseClustering); + cmd.SetKeyword(ShaderGlobalKeywords.ForwardPlus, m_UseClustering); // Backward compatibility. Deprecated in 6.1. bool isShadowMask = lightData.supportsMixedLighting && m_MixedLightingSetup == MixedLightingSetup.ShadowMask; bool isShadowMaskAlways = isShadowMask && QualitySettings.shadowmaskMode == ShadowmaskMode.Shadowmask; @@ -630,7 +678,7 @@ internal void SetupLights(UnsafeCommandBuffer cmd, UniversalRenderingData render cmd.SetKeyword(ShaderGlobalKeywords.MixedLightingSubtractive, isSubtractive); // Backward compatibility cmd.SetKeyword(ShaderGlobalKeywords.ReflectionProbeBlending, lightData.reflectionProbeBlending); cmd.SetKeyword(ShaderGlobalKeywords.ReflectionProbeBoxProjection, lightData.reflectionProbeBoxProjection); - cmd.SetKeyword(ShaderGlobalKeywords.ReflectionProbeAtlas, lightData.reflectionProbeAtlas && m_UseForwardPlus && lightData.reflectionProbeBlending); // Needs to match shader stripping + cmd.SetKeyword(ShaderGlobalKeywords.ReflectionProbeAtlas, lightData.reflectionProbeAtlas && m_UseClustering && lightData.reflectionProbeBlending); // Needs to match shader stripping var asset = UniversalRenderPipeline.asset; #if UNITY_META_QUEST @@ -653,6 +701,7 @@ internal void SetupLights(UnsafeCommandBuffer cmd, UniversalRenderingData render cmd.SetKeyword(ShaderGlobalKeywords.EVALUATE_SH_VERTEX, shMode == ShEvalMode.PerVertex); cmd.SetKeyword(ShaderGlobalKeywords.LightFalloffQuadratic, UniversalRenderPipeline.IsQuadraticFalloffEnabled()); + cmd.SetKeyword(ShaderGlobalKeywords.ShadowReceiverNormalBias, ShadowUtils.IsShadowReceiverNormalBiasEnabled()); var stack = VolumeManager.instance.stack; ProbeReferenceVolume.instance.UpdateShaderVariablesProbeVolumes( @@ -684,13 +733,73 @@ internal void SetupLights(UnsafeCommandBuffer cmd, UniversalRenderingData render } } - internal void Cleanup() + static readonly ProfilingSampler s_UploadClusteringData = new ProfilingSampler("Upload Clustering Data"); + + class UploadClusteringDataPassData + { + internal ForwardLights forwardLights; + } + + /// + /// Uploads the clustering data at the end of the render graph, giving the jobs the whole graph execution to finish. + /// + internal void UploadRenderGraphClusteringData(RenderGraph renderGraph) + { + if (!m_UseClustering) + return; + + using (var builder = renderGraph.AddUnsafePass(s_UploadClusteringData.name, out var passData, s_UploadClusteringData)) + { + passData.forwardLights = this; + builder.AllowPassCulling(false); + builder.SetRenderFunc(static (UploadClusteringDataPassData data, UnsafeGraphContext _) => data.forwardLights.UploadClusteringData()); + } + } + + void UploadClusteringData() { - if (m_UseForwardPlus) + if (!m_ZBins.IsCreated) + return; + + using (new ProfilingScope(m_ProfilingSamplerFPComplete)) { m_CullingHandle.Complete(); - m_ZBins.Dispose(); - m_TileMasks.Dispose(); + } + + // Immediate rather than recorded; valid because the camera's commands are only submitted after the graph executes. + // GPU work issued immediately (not recorded) by an earlier pass would still see the previous upload. + using (new ProfilingScope(m_ProfilingSamplerFPUpload)) + { + if (m_UseForwardPlusStructuredBuffer) + { + m_ZBinsBuffer.SetData(m_ZBins, 0, 0, m_UsedZBinWords); + m_TileMasksBuffer.SetData(m_TileMasks, 0, 0, m_UsedTileWords); + } + else + { + m_ZBinsBuffer.SetData(m_ZBins.Reinterpret(UnsafeUtility.SizeOf()), 0, 0, (m_UsedZBinWords + 3) / 4); + m_TileMasksBuffer.SetData(m_TileMasks.Reinterpret(UnsafeUtility.SizeOf()), 0, 0, (m_UsedTileWords + 3) / 4); + } + } + + DisposeClusteringData(); + } + + internal void DisposeClusteringData() + { + m_CullingHandle.Complete(); + m_CullingHandle = default; + m_ZBins.Dispose(); + m_ZBins = default; + m_TileMasks.Dispose(); + m_TileMasks = default; + } + + internal void Cleanup() + { + if (m_UseClustering) + { + DisposeClusteringData(); m_ZBinsBuffer.Dispose(); m_ZBinsBuffer = null; m_TileMasksBuffer.Dispose(); @@ -797,7 +906,7 @@ internal void UpdateGlobalShaderVariables(GlobalShaderVariablesUploader vars, Un : Vector4.zero; // Forward+ Parameters, cached by PreSetup. - if (m_UseForwardPlus) + if (m_UseClustering) { vars._FPParams0 = math.float4(m_ZBinScale, m_ZBinOffset, m_LightCount, m_DirectionalLightCount); vars._FPParams1 = math.float4(cameraData.pixelRect.size / m_ActualTileWidth, m_TileResolution.x, m_WordsPerTile); @@ -835,12 +944,14 @@ void SetupAdditionalLightConstants(UnsafeCommandBuffer cmd, ref CullingResults c var lights = lightData.visibleLights; int maxAdditionalLightsCount = m_MaxVisibleAdditionalLights; - int additionalLightsCount = SetupPerObjectLightIndices(cullResults, lightData, reuseCullingResult); - if (additionalLightsCount > 0) + SetupPerObjectLightIndices(cullResults, lightData, reuseCullingResult); + if (lightData.additionalLightsCount > 0) { int mainLight = lightData.mainLightIndex; if (m_UseAdditionalLightsConstantBuffer) { + EnsureAdditionalLightsConstantBuffer(); + int positionOffset = maxAdditionalLightsCount * k_AdditionalLightsPositionChannel; int colorOffset = maxAdditionalLightsCount * k_AdditionalLightsColorChannel; int attenuationOffset = maxAdditionalLightsCount * k_AdditionalLightsAttenuationChannel; @@ -885,13 +996,8 @@ void SetupAdditionalLightConstants(UnsafeCommandBuffer cmd, ref CullingResults c } if (m_AdditionalLightsBuffer != null) - { m_AdditionalLightsBuffer.SetData(m_AdditionalLightsData); - cmd.SetGlobalConstantBuffer(m_AdditionalLightsBuffer, LightShaderPropertyId._AdditionalLightsBuffer, 0, - m_AdditionalLightsData.Length * UnsafeUtility.SizeOf()); - } - if (supportsLightLayers) cmd.SetGlobalFloatArray(LightShaderPropertyId._AdditionalLightsLayerMasks, m_AdditionalLightsLayerMasks); } @@ -932,17 +1038,25 @@ void SetupAdditionalLightConstants(UnsafeCommandBuffer cmd, ref CullingResults c cmd.SetGlobalFloatArray(LightShaderPropertyId._AdditionalLightsLayerMasks, m_AdditionalLightsLayerMasks); } } + + // Once created, the buffer is bound for every camera, also when the count is 0, like the reflection probe + // buffer. The shaders read only the first _AdditionalLightsCount entries, so the stale ones are never read. + if (m_AdditionalLightsBuffer != null) + { + cmd.SetGlobalConstantBuffer(m_AdditionalLightsBuffer, LightShaderPropertyId._AdditionalLightsBuffer, 0, + m_AdditionalLightsData.Length * UnsafeUtility.SizeOf()); + } } - int SetupPerObjectLightIndices(CullingResults cullResults, UniversalLightData lightData, bool reuseCullingResult) + void SetupPerObjectLightIndices(CullingResults cullResults, UniversalLightData lightData, bool reuseCullingResult) { - if (lightData.additionalLightsCount == 0 || m_UseForwardPlus) - return lightData.additionalLightsCount; + if (lightData.additionalLightsCount == 0 || m_UseClustering) + return; // SetLightIndexMap was already applied on the previous pass; calling it again would // mutate the shared per-object cull a second time. if (reuseCullingResult) - return lightData.additionalLightsCount; + return; var perObjectLightIndexMap = cullResults.GetLightIndexMap(Allocator.Temp); int globalDirectionalLightsCount = 0; @@ -980,6 +1094,11 @@ int SetupPerObjectLightIndices(CullingResults cullResults, UniversalLightData li } } + // The loop maps the lights CreateLightData counted: the visible lights other than the main light, up to the + // max visible additional lights. The light arrays and _AdditionalLightsCount use lightData's count. + Debug.Assert(additionalLightsCount == lightData.additionalLightsCount, + "The per-object light index map covers a different number of additional lights than lightData.additionalLightsCount."); + // Disable all remaining lights we cannot fit into the global light buffer. for (int i = globalDirectionalLightsCount + additionalLightsCount; i < perObjectLightIndexMap.Length; ++i) perObjectLightIndexMap[i] = -1; @@ -987,7 +1106,6 @@ int SetupPerObjectLightIndices(CullingResults cullResults, UniversalLightData li cullResults.SetLightIndexMap(perObjectLightIndexMap); perObjectLightIndexMap.Dispose(); - return additionalLightsCount; } } } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/DefaultGlobalShaderData.cs b/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/DefaultGlobalShaderData.cs index d21038d96e2..195b81babd1 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/DefaultGlobalShaderData.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/DefaultGlobalShaderData.cs @@ -10,7 +10,7 @@ internal class DefaultGlobalShaderData : ContextItem internal void Set(GlobalShaderVariablesUploader uploader) => m_Uploader = uploader; - internal GlobalShaderVariablesUploader Get() => m_Uploader; + internal GlobalShaderVariablesUploader GetGlobal() => m_Uploader; public override void Reset() { diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/Universal2DGlobalShaderData.cs b/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/Universal2DGlobalShaderData.cs index b8ff7d89124..beadabc1978 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/Universal2DGlobalShaderData.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/Universal2DGlobalShaderData.cs @@ -1,10 +1,50 @@ using System; +using UnityEngine.Rendering; +using UnityEngine.Rendering.Universal; -namespace UnityEngine.Rendering.Universal +namespace UnityEngine.Experimental.Rendering { - // Lives in the core Runtime assembly rather than the 2D one (like Universal2DResourceData) because passes shared - // by both renderers need to reach it, and the 2D assembly is the one referencing this assembly, not the reverse. - internal class Universal2DGlobalShaderData : ContextItem + /// + /// Gives the passes of the URP 2D renderer access to the URP global shader variables. + /// + /// + /// + /// Get it from the frame data while recording, keep it in the pass data, and call or + /// from the render function: the variables are only available while the render graph + /// executes. Get() changes them for the calling pass only, GetGlobal() for every later pass of the camera. A pass that + /// pushes them must call + /// with true. + /// + /// + /// Outside URP camera rendering, for example in an editor tool that draws URP shaders with a command buffer, the + /// buffer URP bound for its last camera stays bound while **Use Persistent Global Constant Buffer** is enabled, so + /// SetGlobal* doesn't reach these variables. Unbind it first, then set the variables your shaders read, as in the + /// example that draws a mesh into a render texture. URP binds its buffer again for its next camera. URP doesn't + /// update the loose uniform values in this mode, so the shaders read what you set, or stale values. + /// + /// + /// This API is experimental and might change in future versions. + /// + /// + /// + /// This sample code draws the sprites of a layer with the 2D Renderer, with their shader animations stopped + /// at a given time, for example while the application is paused. The shaders of later passes read the time of the + /// camera. + /// + /// + /// This sample code draws a mesh with a URP material into a render texture outside URP camera rendering, for + /// example to make a preview in a Unity Editor tool. It unbinds the URP global constant buffer, then sets the + /// variables that the shaders read. + /// + /// + /// + /// + /// + /// + // Lives in the URP Runtime assembly (Unity.RenderPipelines.Universal.Runtime) rather than the URP 2D one + // (Unity.RenderPipelines.Universal.2D.Runtime), like Universal2DResourceData: passes shared by both renderers need to + // reach it, and the 2D assembly references this one, not the reverse. + public class Universal2DGlobalShaderData : ContextItem { // Owned and created by the renderer (so its persistent constant buffer survives across frames); this per-frame // ContextItem only references it, set once per frame via Set(). @@ -12,7 +52,48 @@ internal class Universal2DGlobalShaderData : ContextItem internal void Set(GlobalShaderVariablesUploader uploader) => m_Uploader = uploader; - internal IUniversal2DGlobalShaderVariablesUploader Get() + /// + /// Creates a temporary copy of the URP global shader variables that applies to the calling pass only. + /// + /// + /// Disposing the copy restores the values that were bound before you called this method. Dispose it before the + /// render function returns, typically with a using statement. To make changes that persist for the later passes + /// of the camera, use instead. + /// + /// + /// This sample code draws the sprites of a layer with the 2D Renderer, with their shader animations + /// stopped at a given time, for example while the application is paused. The shaders of later passes read the + /// time of the camera. + /// + /// + /// + /// The temporary copy of the global shader variables. + /// Thrown when called outside the render graph execution of the camera, + /// for example while the render graph records, or while a temporary copy that was changed or pushed is open. + public IUniversal2DGlobalShaderVariablesTemporaryUploader Get() => GetUploader().Get(); + + /// + /// Gets the global shader variables at the point of the execute timeline where the calling pass runs. What + /// the pass pushes through them stays set for the later passes of the camera. + /// + /// + /// Changes that you push through the returned object stay set for every later pass of the camera. To go back to the + /// values URP filled for the camera, call on the + /// returned object. For changes to the calling pass only, use instead. + /// + /// + /// This sample code tells the later passes of the camera that the camera target changed size, for example + /// after a custom upscaling pass that outputs the full camera resolution. The pass works with both the + /// Universal Renderer and the 2D Renderer. + /// + /// + /// + /// The staged global shader variables. + /// Thrown when called outside the render graph execution of the camera, + /// for example while the render graph records. + public IUniversal2DGlobalShaderVariablesUploader GetGlobal() => GetUploader(); + + private GlobalShaderVariablesUploader GetUploader() { if (m_Uploader == null) throw new InvalidOperationException( @@ -22,6 +103,12 @@ internal IUniversal2DGlobalShaderVariablesUploader Get() return m_Uploader; } + /// + /// Clears the reference to the global shader variables so the frame data can reuse this item. + /// + /// + /// The render pipeline calls this method when it resets the frame data. You don't need to call it yourself. + /// public override void Reset() { m_Uploader = null; 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 7d2fcfae8a5..fb0b84d63fe 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/UniversalCameraData.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/UniversalCameraData.cs @@ -476,9 +476,6 @@ internal bool IsTemporalPixelSynthesisActive() /// True if TAA is enabled internal bool IsTemporalAAEnabled() { - UniversalAdditionalCameraData additionalCameraData; - camera.TryGetComponent(out additionalCameraData); - return IsTemporalAARequested() // Requested && postProcessEnabled // Postprocessing Enabled && (taaHistory != null) // Initialized @@ -644,6 +641,11 @@ internal bool resetHistory /// public Camera baseCamera; + // The UniversalAdditionalCameraData of the camera field above, or null if that camera has none. + // UniversalRenderPipeline.InitializeAdditionalCameraData sets it, so the code that runs for this camera + // reads it here instead of calling camera.TryGetComponent each time. + internal UniversalAdditionalCameraData additionalCameraData; + /// /// Returns true if the baseCamera field is the last base camera being rendered to the frame. /// While the last camera in a camera stack implies a last overlay camera, this indicates the last of all input base cameras. @@ -712,6 +714,7 @@ public override void Reset() taaSettings = default; subpixelJitter = default; baseCamera = null; + additionalCameraData = null; isLastBaseCamera = false; stackAnyPostProcessingEnabled = false; stackLastCameraOutputToHDR = false; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/UniversalGlobalShaderData.cs b/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/UniversalGlobalShaderData.cs index 0d1b85c7c61..8e436eb3121 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/UniversalGlobalShaderData.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/UniversalGlobalShaderData.cs @@ -1,15 +1,97 @@ using System; +using UnityEngine.Rendering; +using UnityEngine.Rendering.Universal; -namespace UnityEngine.Rendering.Universal +namespace UnityEngine.Experimental.Rendering { - internal class UniversalGlobalShaderData : ContextItem + /// + /// Gives the passes of the URP 3D renderer access to the URP global shader variables. + /// + /// + /// + /// Get it from the frame data while recording, keep it in the pass data, and call or + /// from the render function: the variables are only available while the render graph + /// executes. Get() changes them for the calling pass only, GetGlobal() for every later pass of the camera. A pass that + /// pushes them must call + /// with true. + /// + /// + /// Outside URP camera rendering, for example in an editor tool that draws URP shaders with a command buffer, the + /// buffer URP bound for its last camera stays bound while **Use Persistent Global Constant Buffer** is enabled, so + /// SetGlobal* doesn't reach these variables. Unbind it first, then set the variables your shaders read, as in the + /// example that draws a mesh into a render texture. URP binds its buffer again for its next camera. URP doesn't + /// update the loose uniform values in this mode, so the shaders read what you set, or stale values. + /// + /// + /// This API is experimental and might change in future versions. + /// + /// + /// + /// This sample code draws the opaque objects again into a half-resolution texture, for example as the source + /// of a glow effect. The shaders of the pass read the screen size of the half-resolution texture, and the shaders + /// of later passes read the screen size of the camera. The renderer feature adds the pass to the renderer. + /// + /// + /// This sample code draws a mesh with a URP material into a render texture outside URP camera rendering, for + /// example to make a preview in a Unity Editor tool. It unbinds the URP global constant buffer, then sets the + /// variables that the shaders read. + /// + /// + /// + /// + /// + /// + public class UniversalGlobalShaderData : ContextItem { // Owned and created by the renderer private GlobalShaderVariablesUploader m_Uploader; internal void Set(GlobalShaderVariablesUploader uploader) => m_Uploader = uploader; - internal IUniversalGlobalShaderVariablesUploader Get() + /// + /// Creates a temporary copy of the URP global shader variables that applies to the calling pass only. + /// + /// + /// Disposing the copy restores the values that were bound before you called this method. Dispose it before the + /// render function returns, typically with a using statement. To make changes that persist for the later passes + /// of the camera, use instead. + /// + /// + /// This sample code draws the opaque objects again into a half-resolution texture, for example as the + /// source of a glow effect. The shaders of the pass read the screen size of the half-resolution texture, and + /// the shaders of later passes read the screen size of the camera. The renderer feature adds the pass to the + /// renderer. + /// + /// + /// + /// The temporary copy of the global shader variables. + /// Thrown when called outside the render graph execution of the camera, + /// for example while the render graph records, or while a temporary copy that was changed or pushed is open. + public IUniversalGlobalShaderVariablesTemporaryUploader Get() => GetUploader().Get(); + + /// + /// Gets the global shader variables at the point of the execute timeline where the calling pass runs. What + /// the pass pushes through them stays set for the later passes of the camera. + /// + /// + /// Changes that you push through the returned object stay set for every later pass of the camera. To go back to the + /// values URP filled for the camera, call on the + /// returned object. For changes to the calling pass only, use instead. + /// + /// + /// This sample code makes texture sampling sharper for every later pass of the camera, for example when + /// the camera renders at a low render scale and an upscaler restores the resolution. A negative mip bias + /// selects more detailed mipmaps. + /// + /// + /// + /// The staged global shader variables. + /// Thrown when called outside the render graph execution of the camera, + /// for example while the render graph records. + public IUniversalGlobalShaderVariablesUploader GetGlobal() => GetUploader(); + + // URP's own passes write the variables that are read-only on the public interfaces through it. + internal GlobalShaderVariablesUploader GetUploader() { if (m_Uploader == null) throw new InvalidOperationException( @@ -19,6 +101,12 @@ internal IUniversalGlobalShaderVariablesUploader Get() return m_Uploader; } + /// + /// Clears the reference to the global shader variables so the frame data can reuse this item. + /// + /// + /// The render pipeline calls this method when it resets the frame data. You don't need to call it yourself. + /// public override void Reset() { m_Uploader = null; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/UniversalShadowData.cs b/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/UniversalShadowData.cs index 75c806fbd89..0da84ba8a86 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/UniversalShadowData.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/UniversalShadowData.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using Unity.Collections; +using UnityEngine.Experimental.Rendering; using UnityEngine.Rendering.Universal.Internal; namespace UnityEngine.Rendering.Universal @@ -75,8 +76,19 @@ public class UniversalShadowData : ContextItem /// /// The number of bits used. /// + [Obsolete("Use mainLightShadowmapDepthBits or additionalLightsShadowmapDepthBits. #from(7000.0)", false)] public int shadowmapDepthBufferBits; + /// + /// The depth buffer precision of the main light shadow map. + /// + public DepthBits mainLightShadowmapDepthBits; + + /// + /// The depth buffer precision of the additional lights shadow map atlas. + /// + public DepthBits additionalLightsShadowmapDepthBits; + /// /// A list of shadow bias. /// @@ -89,9 +101,15 @@ public class UniversalShadowData : ContextItem internal ShadowDepthBiasMode depthBiasMode; internal ShadowNormalBiasMode normalBiasMode; + internal GraphicsFormat mainLightShadowmapFormat; + internal GraphicsFormat additionalLightsShadowmapFormat; + internal float softShadowKernelRadiusPercent; + internal bool mainLightReceiverNormalBiasSkipped; internal bool isKeywordAdditionalLightShadowsEnabled; internal bool isKeywordSoftShadowsEnabled; + internal bool isMainLightPCSSEnabled; + internal bool isAdditionalLightsPCSSEnabled; internal int mainLightShadowResolution; internal int mainLightRenderTargetWidth; internal int mainLightRenderTargetHeight; @@ -102,6 +120,7 @@ public class UniversalShadowData : ContextItem // Owned by AdditionalLightsShadowCasterPass internal GraphicsBuffer emptyAdditionalLightShadowsBuffer; internal GraphicsBuffer extraForwardAdditionalLightShadowsBuffer; + internal GraphicsBuffer extraForwardAdditionalLightPCSSBuffer; internal Vector4[] extraForwardAdditionalLightShadowParams; internal Vector4[] extraForwardAdditionalLightReceiverNormalBiases; internal short[] visibleLightIndexToAdditionalLightIndex; @@ -127,14 +146,24 @@ public override void Reset() additionalLightsShadowmapWidth = 0; additionalLightsShadowmapHeight = 0; supportsSoftShadows = false; +#pragma warning disable 618 // Obsolete warning shadowmapDepthBufferBits = 0; +#pragma warning restore 618 // Obsolete warning + mainLightShadowmapDepthBits = DepthBits.None; + additionalLightsShadowmapDepthBits = DepthBits.None; + mainLightShadowmapFormat = GraphicsFormat.None; + additionalLightsShadowmapFormat = GraphicsFormat.None; bias?.Clear(); resolution?.Clear(); depthBiasMode = ShadowDepthBiasMode.Legacy; normalBiasMode = ShadowNormalBiasMode.Caster; + softShadowKernelRadiusPercent = 0.0f; + mainLightReceiverNormalBiasSkipped = false; isKeywordAdditionalLightShadowsEnabled = false; isKeywordSoftShadowsEnabled = false; + isMainLightPCSSEnabled = false; + isAdditionalLightsPCSSEnabled = false; mainLightShadowResolution = 0; mainLightRenderTargetWidth = 0; mainLightRenderTargetHeight = 0; @@ -147,6 +176,7 @@ public override void Reset() emptyAdditionalLightShadowsBuffer = null; extraForwardAdditionalLightShadowsBuffer = null; + extraForwardAdditionalLightPCSSBuffer = null; extraForwardAdditionalLightShadowParams = null; extraForwardAdditionalLightReceiverNormalBiases = null; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/GlobalShaderVariables/ConstantBufferPropertyWarnings.cs b/Packages/com.unity.render-pipelines.universal/Runtime/GlobalShaderVariables/ConstantBufferPropertyWarnings.cs new file mode 100644 index 00000000000..3ec64edea1b --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/GlobalShaderVariables/ConstantBufferPropertyWarnings.cs @@ -0,0 +1,249 @@ +using System.Diagnostics; +using Unity.Scripting.LifecycleManagement; +using CoreBridge = Unity.RenderPipelines.Core.Runtime.Shared.ConstantBufferBackedPropertiesBridge; + +namespace UnityEngine.Rendering.Universal +{ + /// + /// Warns in the Editor when a loose-uniform API writes a shader property that URP stores in a constant buffer it binds + /// itself, or will bind itself in a future version. The engine skips a bound constant buffer when it gathers loose + /// uniforms, so once URP binds the constant buffer, a Shader.SetGlobal*, CommandBuffer.SetGlobal*, Material.Set* or + /// MaterialPropertyBlock.Set* write to one of these properties never reaches URP shaders. + /// + /// + /// The engine does the checks, see ConstantBufferBackedPropertyWarnings.h. URP marks the properties and enables the + /// checks of the writes other than Material.Set* only while it renders: loose uniforms set before or after URP + /// rendering can be meant for other shaders. + /// + internal static class ConstantBufferPropertyWarnings + { + // URP binds these itself whenever RenderingUtils.usePersistentConstantBuffer is true. + internal readonly struct LightingConstantBuffer + { + public readonly string name; + public readonly string[] members; + + public LightingConstantBuffer(string name, params string[] members) + { + this.name = name; + this.members = members; + } + } + + [NoAutoStaticsCleanup] + internal static readonly LightingConstantBuffer[] k_LightingConstantBuffers = + { + new LightingConstantBuffer("AdditionalLights", + "_AdditionalLightsPosition", "_AdditionalLightsColor", "_AdditionalLightsAttenuation", + "_AdditionalLightsSpotDir", "_AdditionalLightsOcclusionProbes"), + new LightingConstantBuffer("AdditionalLightShadows", + "_AdditionalLightsWorldToShadow", "_AdditionalShadowParams", "_AdditionalShadowReceiverNormalBias"), + new LightingConstantBuffer("urp_ReflectionProbeBuffer", + "urp_ReflProbes_BoxMax", "urp_ReflProbes_BoxMin", "urp_ReflProbes_ProbePosition", + "urp_ReflProbes_MipScaleOffset", "urp_ReflProbes_Rotation", "urp_ReflProbes_ExposureMultipliers"), + new LightingConstantBuffer("LightCookies", + "_AdditionalLightsWorldToLights", "_AdditionalLightsCookieAtlasUVRects", "_AdditionalLightsLightTypes", + "_AdditionalLightsCookieEnableBits"), + }; + + internal const string k_GlobalWarningBoundLater = + "Shader property '{0}' is a variable of URP's global constant buffer (GlobalShaderVariables), which URP will bind " + + "itself in a future version. From then on, setting it with Shader.SetGlobal*, CommandBuffer.SetGlobal*, " + + "Material.Set* or MaterialPropertyBlock.Set* won't change the value that URP shaders read. Rename the property if " + + "it belongs to your own shader. To change URP's value, use UniversalGlobalShaderData (Universal2DGlobalShaderData " + + "with the 2D renderer) from a render graph pass, which works in both modes. This warning is logged once per property."; + + internal const string k_GlobalWarningBound = + "Shader property '{0}' is a variable of URP's global constant buffer (GlobalShaderVariables), which URP binds " + + "itself while Use Persistent Global Constant Buffer is on (Project Settings > Graphics > URP > Rendering Capabilities). " + + "Setting it with Shader.SetGlobal*, CommandBuffer.SetGlobal*, Material.Set* or MaterialPropertyBlock.Set* doesn't " + + "change the value that URP shaders read. Rename the property if it belongs to your own shader. To change URP's " + + "value, use UniversalGlobalShaderData (Universal2DGlobalShaderData with the 2D renderer) from a render graph pass: " + + "Get() for that pass only, GetGlobal() for the rest of the camera. This warning is logged once per property."; + + internal static string LightingConstantBufferWarning(string constantBuffer) + { + return "Shader property '{0}' is a variable of URP's " + constantBuffer + " constant buffer, which URP binds " + + "itself. Setting it with Shader.SetGlobal*, CommandBuffer.SetGlobal*, Material.Set* or " + + "MaterialPropertyBlock.Set* doesn't change the value that URP shaders read. Rename the property if it " + + "belongs to your own shader. This warning is logged once per property."; + } + + // The members of GlobalShaderVariables but the padding, which ConstantBufferPropertyWarningsTests checks against the HLSL. + [NoAutoStaticsCleanup] + internal static readonly string[] k_GlobalShaderVariables = + { + "_Time", "_SinTime", "_CosTime", "unity_DeltaTime", "_TimeParameters", "_LastTimeParameters", "_ScreenParams", + "_ZBufferParams", "_RTHandleScale", "_ScreenSize", "_ScreenSizeOverride", "_ScreenCoordScaleBias", + "unity_AmbientSky", "unity_AmbientEquator", "unity_AmbientGround", "_GlossyEnvironmentColor", "unity_OrthoParams", + "_ScaledScreenParams", "_GlobalMipBias", "_DitheringTextureInvSize", "_SubtractiveShadowColor", + "_GlossyEnvironmentCubeMap_HDR", + + "_MainLightPosition", "_MainLightColor", "_MainLightOcclusionProbes", "_MainLightLayerMask", + "_RenderingLayerMaxInt", "_EnableProbeVolumes", "_MainLightCookieTextureFormat", "_FPParams0", "_FPParams1", + "_FPParams2", "_AdditionalLightsCount", "_CascadeShadowSplitSpheres0", "_CascadeShadowSplitSpheres1", + "_CascadeShadowSplitSpheres2", "_CascadeShadowSplitSpheres3", "_CascadeShadowSplitSphereRadii", + "_MainLightShadowOffset0", "_MainLightShadowOffset1", "_MainLightShadowmapSize", "_MainLightPCSSParams0", + "_MainLightPCSSParams1", "_MainLightPCSSAtlas", "_MainLightPCSSScalars", "_AdditionalShadowOffset0", + "_AdditionalShadowOffset1", "_AdditionalShadowmapSize", "_MainLightWorldToShadow", "_MainLightWorldToLight", + "_NonJitteredViewProjMatrix", "_PrevViewProjMatrix", "_AdditionalLightsCookieAtlasTextureFormat", + }; + + // The mode the properties are marked for: -1 when none is, else 1 when URP binds its global constant buffer, 0 otherwise. + [NoAutoStaticsCleanup] static int s_RegisteredMode = -1; + // Render() and render requests, which can happen while URP renders. + [NoAutoStaticsCleanup] static int s_RenderDepth; + [NoAutoStaticsCleanup] static int s_PipelineWriteDepth; + + /// + /// Call when URP starts rendering, in UniversalRenderPipeline.Render() or for a render request, paired with + /// . + /// + /// + /// Resolves the mode like RenderCameras() does later in the frame: useGlobalConstantBuffer still holds the previous one. + /// + [Conditional("UNITY_EDITOR")] + internal static void BeginRender() + { + BeginRender(UniversalRenderPipeline.IsGlobalConstantBufferRequested()); + } + + /// + /// for a given mode. + /// + /// Whether URP binds its global constant buffer itself this frame. + [Conditional("UNITY_EDITOR")] + internal static void BeginRender(bool useGlobalConstantBuffer) + { + if (!AreValidityChecksEnabled()) + { + Release(); + return; + } + + // A render request made while URP renders keeps the warnings of that rendering. + if (s_RenderDepth > 0) + { + ++s_RenderDepth; + return; + } + + if (s_RegisteredMode != (useGlobalConstantBuffer ? 1 : 0)) + Register(useGlobalConstantBuffer); + + // A pipeline write section that an exception left open doesn't silence the next frames. + s_PipelineWriteDepth = 0; + CoreBridge.EnableWarnings(true); + s_RenderDepth = 1; + } + + /// + /// Call when URP stops rendering, even when rendering threw. + /// + [Conditional("UNITY_EDITOR")] + internal static void EndRender() + { + if (s_RenderDepth > 0 && --s_RenderDepth == 0) + CoreBridge.EnableWarnings(false); + } + + /// + /// Call before URP sets the variables of its global constant buffer as loose uniforms, which the engine copies to + /// that constant buffer while URP doesn't bind it, paired with . These writes aren't + /// the ones to warn about. + /// + [Conditional("UNITY_EDITOR")] + internal static void BeginPipelineWrites() + { + if (s_PipelineWriteDepth++ == 0 && s_RenderDepth > 0) + CoreBridge.EnableWarnings(false); + } + + [Conditional("UNITY_EDITOR")] + internal static void EndPipelineWrites() + { + if (s_PipelineWriteDepth > 0 && --s_PipelineWriteDepth == 0 && s_RenderDepth > 0) + CoreBridge.EnableWarnings(true); + } + + /// + /// Call when the pipeline is disposed. Nothing changes while URP stays the active pipeline, so that the Material writes + /// of Awake, OnEnable and Start still warn before URP renders again. + /// + [Conditional("UNITY_EDITOR")] + internal static void OnPipelineDisposed() + { + OnPipelineDisposed(GraphicsSettings.currentRenderPipeline is UniversalRenderPipelineAsset); + } + + /// + /// for a given active pipeline. + /// + /// Whether URP is still the active render pipeline. + [Conditional("UNITY_EDITOR")] + internal static void OnPipelineDisposed(bool urpStaysActive) + { + if (!urpStaysActive) + Release(); + } + + /// + /// Unmarks every property, so none stays marked for another render pipeline. + /// + [Conditional("UNITY_EDITOR")] + internal static void Release() + { + CoreBridge.ClearWarnings(); + CoreBridge.EnableWarnings(false); + s_RegisteredMode = -1; + s_RenderDepth = 0; + s_PipelineWriteDepth = 0; + } + +#if UNITY_EDITOR + // Registers before Awake, OnEnable and Start run, rather than on the first render, which would re-arm the properties + // they already warned about. + [UnityEditor.InitializeOnLoadMethod] + static void RegisterAfterDomainReload() + { + CoreBridge.EnableWarnings(false); + if (GraphicsSettings.currentRenderPipeline is UniversalRenderPipelineAsset && AreValidityChecksEnabled()) + Register(UniversalRenderPipeline.IsGlobalConstantBufferRequested()); + } +#endif + + static void Register(bool globalsBoundByPipeline) + { + // Clear first, so no mark of the previous mode stays. + CoreBridge.ClearWarnings(); + + string globalWarning = globalsBoundByPipeline ? k_GlobalWarningBound : k_GlobalWarningBoundLater; + foreach (string name in k_GlobalShaderVariables) + MarkProperty(name, globalWarning); + + if (RenderingUtils.usePersistentConstantBuffer) + { + foreach (LightingConstantBuffer constantBuffer in k_LightingConstantBuffers) + { + string warning = LightingConstantBufferWarning(constantBuffer.name); + foreach (string member in constantBuffer.members) + MarkProperty(member, warning); + } + } + + s_RegisteredMode = globalsBoundByPipeline ? 1 : 0; + } + + internal static void MarkProperty(string propertyName, string warning) + { + CoreBridge.SetBackedByConstantBuffer(Shader.PropertyToID(propertyName), warning.Replace("{0}", propertyName)); + } + + // Without Render Graph settings, as in some unit tests, the checks stay on like Render Graph's. + static bool AreValidityChecksEnabled() + { + return !GraphicsSettings.TryGetRenderPipelineSettings(out var renderGraphSettings) + || renderGraphSettings.enableValidityChecks; + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/GlobalShaderVariables/ConstantBufferPropertyWarnings.cs.meta b/Packages/com.unity.render-pipelines.universal/Runtime/GlobalShaderVariables/ConstantBufferPropertyWarnings.cs.meta new file mode 100644 index 00000000000..8edbdd86dc8 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/GlobalShaderVariables/ConstantBufferPropertyWarnings.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 99ec6e4db6be42e8a32128449c26365e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/GlobalShaderVariables/GlobalShaderVariables.cs b/Packages/com.unity.render-pipelines.universal/Runtime/GlobalShaderVariables/GlobalShaderVariables.cs index 1a33dbcdd4b..9c3c5f5e8cd 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/GlobalShaderVariables/GlobalShaderVariables.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/GlobalShaderVariables/GlobalShaderVariables.cs @@ -27,6 +27,17 @@ namespace UnityEngine.Rendering.Universal /// /// 5. Try to keep data grouped by access and rendering system as much as possible. /// - Don't move a float parameter away from where it belongs for filling a hole. Add padding in this case. + /// - The members lit fragment shaders read sit together, from _GlossyEnvironmentColor in GlobalShaderVariablesBase to + /// _AdditionalShadowmapSize in GlobalShaderVariablesOnly3D, followed by the main light shadow matrices. A lit draw then + /// reads its constants from fewer 64 byte cache lines. + /// - Add a member lit shaders read inside that range, any other one outside of it. GlobalShaderVariablesBase ends + /// inside the range, so a Base member lit shaders don't read goes before _GlossyEnvironmentColor, not at the end. + /// - The scalars lit shaders read share the row right after the main light. The last row of GlobalShaderVariablesOnly3D + /// holds _AdditionalLightsCookieAtlasTextureFormat, read only with additional light cookies, and the free slots + /// for new 3D scalars. + /// - Keep the number of 16 byte rows before _MainLightWorldToShadow, GlobalShaderVariablesBase included, a multiple + /// of 4, so that each cascade matrix fills exactly one cache line. The same goes for every matrix: + /// GlobalShaderVariablesLayoutTests checks that each one starts on a 64 byte boundary. /// /// 6. Total size of each sub-struct must be a multiple of 16 bytes (Vector4), add trailing padding when needed. /// diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/GlobalShaderVariables/GlobalShaderVariablesBase.cs b/Packages/com.unity.render-pipelines.universal/Runtime/GlobalShaderVariables/GlobalShaderVariablesBase.cs index 4b8c0295ca9..7cc7a20afaf 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/GlobalShaderVariables/GlobalShaderVariablesBase.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/GlobalShaderVariables/GlobalShaderVariablesBase.cs @@ -4,13 +4,13 @@ namespace UnityEngine.Rendering.Universal { - // One bit per pushable field of GlobalShaderVariablesBase, so PushGlobal() only re-uploads what changed. + // One bit per pushable field of GlobalShaderVariablesBase, so Push() only re-uploads what changed. // // GlobalShaderVariablesUploader is the only thing that raises or clears these bits: // - a property setter raises the bit of the field it writes, at record time inside a BeginFill/EndFill window // - EndFill snapshots the raised bits as the defaults of the camera, then clears the staging ones - // - PushGlobal clears the bits it just pushed, so nothing goes out twice - // - ResetToDefault raises them again from that snapshot, which is how PushDefaultToGlobal re-sends the whole set + // - Push clears the bits it just pushed, so nothing goes out twice + // - ResetToDefault raises them again from that snapshot, which is how PushDefault re-sends the whole set // recorded for the camera once something else has overwritten the global state // // Warning! Add a bit here, an accessor in GlobalShaderVariablesUploader and a line in SetGlobals() for every new field. @@ -63,23 +63,25 @@ internal struct GlobalShaderVariablesBase public Vector4 _LastTimeParameters; // UnityInput.hlsl public Vector4 _ScreenParams; // UnityInput.hlsl public Vector4 _ZBufferParams; // UnityInput.hlsl - public Vector4 unity_OrthoParams; // UnityInput.hlsl public Vector4 _RTHandleScale; // UnityInput.hlsl - public Vector4 _ScaledScreenParams; // Unity.hlsl public Vector4 _ScreenSize; // UnityInput.hlsl public Vector4 _ScreenSizeOverride; // Unity.hlsl public Vector4 _ScreenCoordScaleBias; // Unity.hlsl - // Ambient gradient, filled from RenderSettings. + // Ambient gradient and environment color, filled from RenderSettings. public Vector4 unity_AmbientSky; // UnityInput.hlsl public Vector4 unity_AmbientEquator; // UnityInput.hlsl public Vector4 unity_AmbientGround; // UnityInput.hlsl + public Vector4 _GlossyEnvironmentColor; // Unity.hlsl + + // From _GlossyEnvironmentColor on, the members lit fragment shaders read, see guideline 5 in GlobalShaderVariables. + public Vector4 unity_OrthoParams; // UnityInput.hlsl + public Vector4 _ScaledScreenParams; // Unity.hlsl public Vector2 _GlobalMipBias; // UnityInput.hlsl public float _DitheringTextureInvSize; // LODCrossFade.hlsl public float _URPPadding1; // Environment, come from RenderSettings. - public Vector4 _GlossyEnvironmentColor; // Unity.hlsl public Vector4 _SubtractiveShadowColor; // Unity.hlsl public Vector4 _GlossyEnvironmentCubeMap_HDR; // Unity.hlsl } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/GlobalShaderVariables/GlobalShaderVariablesOnly3D.cs b/Packages/com.unity.render-pipelines.universal/Runtime/GlobalShaderVariables/GlobalShaderVariablesOnly3D.cs index 71a32c1d235..031b1a746ec 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/GlobalShaderVariables/GlobalShaderVariablesOnly3D.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/GlobalShaderVariables/GlobalShaderVariablesOnly3D.cs @@ -1,5 +1,7 @@ using System; using System.Runtime.InteropServices; +using UnityEngine.Experimental.Rendering; +using UnityEngine.Rendering; using Dirty = UnityEngine.Rendering.Universal.GlobalShaderVariablesOnly3DDirty; namespace UnityEngine.Rendering.Universal @@ -53,38 +55,58 @@ internal enum GlobalShaderVariablesOnly3DDirty : uint _NonJitteredViewProjMatrix = 1u << 25, _PrevViewProjMatrix = 1u << 26, + // Main Light Shadows, PCSS. Each cascade array goes out as a single push. + _MainLightPCSSParams0 = 1u << 27, + _MainLightPCSSParams1 = 1u << 28, + _MainLightPCSSAtlas = 1u << 29, + _MainLightPCSSScalars = 1u << 30, + // Keep this referencing the last bit declared above when adding a variable. - All = (_PrevViewProjMatrix << 1) - 1u, + All = (_MainLightPCSSScalars << 1) - 1u, } +} +namespace UnityEngine.Experimental.Rendering +{ /// - /// The main light world to shadow matrices, one per cascade plus a trailing no-op slice. + /// The main light world to shadow matrices, one per cascade plus a trailing no-op matrix for indices past the last cascade. /// /// - /// Grouped in a nested struct rather than declared as five fields so the dirty flag contract stays one bit per push: - /// they go out as a single SetGlobalMatrixArray. + /// Shaders read the five matrices as the `_MainLightWorldToShadow` array. To change them from a render graph pass, use the + /// property of the object that + /// or returns. This is a + /// struct, so read the property, change the copy, and assign it back. /// + /// + /// This sample code draws the objects of a layer with the main light shadows of the first shadow cascade + /// only. The other cascades get the values that the shaders read beyond the last cascade: a matrix that has no + /// effect, and an empty percentage-closer soft shadows (PCSS) atlas tile. + /// + /// + /// + /// + /// [StructLayout(LayoutKind.Sequential)] - internal struct MainLightShadowMatrices + public struct MainLightShadowMatrices { - /// The number of matrices, MAX_SHADOW_CASCADES + 1 in Shadows.hlsl. + /// The number of matrices, MAX_SHADOW_CASCADES + 1 as declared in GlobalShaderVariables.hlsl. public const int count = 5; - /// The matrix of the first cascade. + /// The matrix of the first shadow cascade. public Matrix4x4 cascade0; - /// The matrix of the second cascade. + /// The matrix of the second shadow cascade. public Matrix4x4 cascade1; - /// The matrix of the third cascade. + /// The matrix of the third shadow cascade. public Matrix4x4 cascade2; - /// The matrix of the fourth cascade. + /// The matrix of the fourth shadow cascade. public Matrix4x4 cascade3; /// - /// The trailing no-op matrix. It always transforms the shadow coord to half3(0, 0, NEAR_PLANE), which avoids - /// branching since ComputeCascadeIndex can return MAX_SHADOW_CASCADES. + /// The trailing no-op matrix for indices past the last cascade (ComputeCascadeIndex returns MAX_SHADOW_CASCADES + /// there), so shaders need no branch. /// public Matrix4x4 cascade4; @@ -93,15 +115,14 @@ internal struct MainLightShadowMatrices /// /// The command buffer used to set the global. /// The shader property id of the array. - public readonly unsafe void SetGlobal(IBaseCommandBuffer cmd, int nameID) + internal readonly unsafe void SetGlobal(IBaseCommandBuffer cmd, int nameID) { fixed (Matrix4x4* matrices = &cascade0) cmd.SetGlobalMatrixArray(nameID, new ReadOnlySpan(matrices, count)); } - /// Gets or sets the matrix of a given cascade. + /// The matrix of the cascade at the given index. /// The cascade index, between 0 and - 1. - /// The matrix stored for the requested cascade. /// Thrown if is out of range. public Matrix4x4 this[int index] { @@ -129,31 +150,121 @@ public Matrix4x4 this[int index] } } + /// + /// One vector per main light shadow cascade, plus a trailing slot for the index past the last cascade. + /// + /// + /// URP uses this struct for the main light PCSS shadow parameters: + /// , + /// , and + /// . Only _MainLightPCSSAtlas is writable: this is + /// a struct, so read the property, change the copy, and assign it back. URP fills the other two. + /// + /// + /// This sample code draws the objects of a layer with the main light shadows of the first shadow cascade + /// only. The other cascades get the values that the shaders read beyond the last cascade: a matrix that has no + /// effect, and an empty percentage-closer soft shadows (PCSS) atlas tile. + /// + /// + /// + /// + [StructLayout(LayoutKind.Sequential)] + public struct MainLightShadowCascadeVectors + { + /// The number of vectors, MAX_SHADOW_CASCADES + 1 as declared in GlobalShaderVariables.hlsl. + public const int count = 5; + + /// The vector of the first shadow cascade. + public Vector4 cascade0; + + /// The vector of the second shadow cascade. + public Vector4 cascade1; + + /// The vector of the third shadow cascade. + public Vector4 cascade2; + + /// The vector of the fourth shadow cascade. + public Vector4 cascade3; + + /// The trailing slot, which shaders use past the last cascade. + public Vector4 cascade4; + + /// + /// Pushes the vectors as a single global vector array. + /// + /// The command buffer used to set the global. + /// The shader property id of the array. + /// A scratch array of elements the values are copied through. + internal readonly void SetGlobal(IBaseCommandBuffer cmd, int nameID, Vector4[] scratch) + { + scratch[0] = cascade0; + scratch[1] = cascade1; + scratch[2] = cascade2; + scratch[3] = cascade3; + scratch[4] = cascade4; + cmd.SetGlobalVectorArray(nameID, scratch); + } + + /// The vector of the cascade at the given index. + /// The cascade index, between 0 and - 1. + /// Thrown if is out of range. + public Vector4 this[int index] + { + readonly get => index switch + { + 0 => cascade0, + 1 => cascade1, + 2 => cascade2, + 3 => cascade3, + 4 => cascade4, + _ => throw new IndexOutOfRangeException($"index {index} is out of range, it must be between 0 and {count - 1}."), + }; + set + { + switch (index) + { + case 0: cascade0 = value; break; + case 1: cascade1 = value; break; + case 2: cascade2 = value; break; + case 3: cascade3 = value; break; + case 4: cascade4 = value; break; + default: throw new IndexOutOfRangeException($"index {index} is out of range, it must be between 0 and {count - 1}."); + } + } + } + } +} + +namespace UnityEngine.Rendering.Universal +{ // Global shader variables only URP 3D declares and fills, see GlobalShaderVariables for the declaration guidelines. [StructLayout(LayoutKind.Sequential)] internal struct GlobalShaderVariablesOnly3D { + // Up to the main light shadow matrices, the members lit fragment shaders read, see guideline 5 in + // GlobalShaderVariables. They continue the ones closing GlobalShaderVariablesBase. + // Main Light - public Matrix4x4 _MainLightWorldToLight; // LightCookieInput.hlsl public Vector4 _MainLightPosition; // Forward + Deferred Light public Vector4 _MainLightColor; // Forward + Deferred Light (half precision in shader) public Vector4 _MainLightOcclusionProbes; // Forward Light (half precision in shader) + // The scalars lit shaders read, in a single 16 byte row next to the main light, see guideline 5 in + // GlobalShaderVariables. + public uint _MainLightLayerMask; // Forward + Deferred Light + public uint _RenderingLayerMaxInt; // Unity.hlsl + public uint _EnableProbeVolumes; // Forward Light + public float _MainLightCookieTextureFormat; // LightCookieInput.hlsl + // Forward+ Parameters public Vector4 _FPParams0; // Input.hlsl + USE_CLUSTER_LIGHT_LOOP public Vector4 _FPParams1; // Input.hlsl + USE_CLUSTER_LIGHT_LOOP public Vector4 _FPParams2; // Input.hlsl + USE_CLUSTER_LIGHT_LOOP - // Motion Vectors. In XR single pass the shader macros redirect every read to the Stereo arrays, which stay - // loose uniforms, so these two are only consumed outside XR. See UnityInput.hlsl. - public Matrix4x4 _NonJitteredViewProjMatrix; // UnityInput.hlsl - public Matrix4x4 _PrevViewProjMatrix; // UnityInput.hlsl - // Additional Lights. The arrays themselves are in the AdditionalLights CBuffer. public Vector4 _AdditionalLightsCount; // Input.hlsl (half precision in shader), x holds the count // Main Light Shadows - public MainLightShadowMatrices _MainLightWorldToShadow; // GlobalShaderVariables.hlsl public Vector4 _CascadeShadowSplitSpheres0; // Shadows.hlsl public Vector4 _CascadeShadowSplitSpheres1; // Shadows.hlsl public Vector4 _CascadeShadowSplitSpheres2; // Shadows.hlsl @@ -163,20 +274,32 @@ internal struct GlobalShaderVariablesOnly3D public Vector4 _MainLightShadowOffset1; // Shadows.hlsl public Vector4 _MainLightShadowmapSize; // Shadows.hlsl + // Main Light Shadows, PCSS + public MainLightShadowCascadeVectors _MainLightPCSSParams0; // Shadows.hlsl + public MainLightShadowCascadeVectors _MainLightPCSSParams1; // Shadows.hlsl + public MainLightShadowCascadeVectors _MainLightPCSSAtlas; // Shadows.hlsl + public Vector4 _MainLightPCSSScalars; // Shadows.hlsl + // Additional Lights Shadows public Vector4 _AdditionalShadowOffset0; // Shadows.hlsl public Vector4 _AdditionalShadowOffset1; // Shadows.hlsl public Vector4 _AdditionalShadowmapSize; // Shadows.hlsl - // Misc - public float _MainLightCookieTextureFormat; // LightCookieInput.hlsl - public float _AdditionalLightsCookieAtlasTextureFormat; // LightCookieInput.hlsl - public uint _RenderingLayerMaxInt; // Unity.hlsl - public uint _EnableProbeVolumes; // Forward Light + // Main Light Shadows matrices. The rows before them add up to a multiple of 64 bytes, so each cascade matrix fills + // one cache line, see guideline 5 in GlobalShaderVariables. + public MainLightShadowMatrices _MainLightWorldToShadow; // GlobalShaderVariables.hlsl - // Kept last on purpose: these scalars share a single 16 byte row, so the next 3D fields we add can consume the + // Main Light cookie + public Matrix4x4 _MainLightWorldToLight; // LightCookieInput.hlsl + + // Motion Vectors. In XR single pass the shader macros redirect every read to the Stereo arrays, which stay + // loose uniforms, so these two are only consumed outside XR. See UnityInput.hlsl. + public Matrix4x4 _NonJitteredViewProjMatrix; // UnityInput.hlsl + public Matrix4x4 _PrevViewProjMatrix; // UnityInput.hlsl + + // Kept last on purpose: these scalars share a single 16 byte row, so the next 3D scalars we add can consume the // remaining padding slots instead of needing padding of their own. - public uint _MainLightLayerMask; // Forward + Deferred Light + public float _AdditionalLightsCookieAtlasTextureFormat; // LightCookieInput.hlsl public uint _URPPadding2; public uint _URPPadding3; public uint _URPPadding4; @@ -187,6 +310,9 @@ internal struct GlobalShaderVariablesOnly3D internal static class GlobalShaderVariablesOnly3DExtensions { + // SetGlobalVectorArray takes no span + static readonly Vector4[] s_CascadeVectorScratch = new Vector4[MainLightShadowCascadeVectors.count]; + /// /// Sets the URP 3D shader variables flagged in as global uniforms using the provided /// CommandBuffer. This is a fallback when persistent constant buffer mode is disabled. @@ -227,6 +353,12 @@ internal static void SetGlobals(this in GlobalShaderVariablesOnly3D vars, IBaseC if ((dirty & Dirty._MainLightShadowOffset1) != 0) cmd.SetGlobalVector(PropertyId.mainLightShadowOffset1, vars._MainLightShadowOffset1); if ((dirty & Dirty._MainLightShadowmapSize) != 0) cmd.SetGlobalVector(PropertyId.mainLightShadowmapSize, vars._MainLightShadowmapSize); + // Main Light Shadows, PCSS + if ((dirty & Dirty._MainLightPCSSParams0) != 0) vars._MainLightPCSSParams0.SetGlobal(cmd, PropertyId.mainLightPCSSParams0, s_CascadeVectorScratch); + if ((dirty & Dirty._MainLightPCSSParams1) != 0) vars._MainLightPCSSParams1.SetGlobal(cmd, PropertyId.mainLightPCSSParams1, s_CascadeVectorScratch); + if ((dirty & Dirty._MainLightPCSSAtlas) != 0) vars._MainLightPCSSAtlas.SetGlobal(cmd, PropertyId.mainLightPCSSAtlas, s_CascadeVectorScratch); + if ((dirty & Dirty._MainLightPCSSScalars) != 0) cmd.SetGlobalVector(PropertyId.mainLightPCSSScalars, vars._MainLightPCSSScalars); + // Additional Lights Shadows if ((dirty & Dirty._AdditionalShadowOffset0) != 0) cmd.SetGlobalVector(PropertyId.additionalShadowOffset0, vars._AdditionalShadowOffset0); if ((dirty & Dirty._AdditionalShadowOffset1) != 0) cmd.SetGlobalVector(PropertyId.additionalShadowOffset1, vars._AdditionalShadowOffset1); @@ -266,6 +398,10 @@ private static class PropertyId public static readonly int mainLightShadowOffset0 = Shader.PropertyToID("_MainLightShadowOffset0"); public static readonly int mainLightShadowOffset1 = Shader.PropertyToID("_MainLightShadowOffset1"); public static readonly int mainLightShadowmapSize = Shader.PropertyToID("_MainLightShadowmapSize"); + public static readonly int mainLightPCSSParams0 = Shader.PropertyToID("_MainLightPCSSParams0"); + public static readonly int mainLightPCSSParams1 = Shader.PropertyToID("_MainLightPCSSParams1"); + public static readonly int mainLightPCSSAtlas = Shader.PropertyToID("_MainLightPCSSAtlas"); + public static readonly int mainLightPCSSScalars = Shader.PropertyToID("_MainLightPCSSScalars"); // Additional Lights public static readonly int additionalLightsCount = Shader.PropertyToID("_AdditionalLightsCount"); diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/GlobalShaderVariables/GlobalShaderVariablesUploader.cs b/Packages/com.unity.render-pipelines.universal/Runtime/GlobalShaderVariables/GlobalShaderVariablesUploader.cs index 00af5ca7d71..ffe9e229c80 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/GlobalShaderVariables/GlobalShaderVariablesUploader.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/GlobalShaderVariables/GlobalShaderVariablesUploader.cs @@ -1,10 +1,16 @@ using System; +using System.Collections.Generic; using System.Runtime.CompilerServices; +using UnityEngine.Experimental.Rendering; using UnityEngine.Rendering.Universal.Internal; namespace UnityEngine.Rendering.Universal { - internal sealed class GlobalShaderVariablesUploader : IUniversalGlobalShaderVariablesUploader, IUniversal2DGlobalShaderVariablesUploader + // The renderers own one uploader each. Get() hands out a second instance of this class, a temporary copy of + // the renderer's one: same accessors, but its pushes are undone when it is disposed, see the "Temporary copies" section. + internal sealed class GlobalShaderVariablesUploader : + IUniversalGlobalShaderVariablesUploader, IUniversal2DGlobalShaderVariablesUploader, + IUniversalGlobalShaderVariablesTemporaryUploader, IUniversal2DGlobalShaderVariablesTemporaryUploader { // None of these vars depend on the target UV origin (y-flip), so a single default covers both backbuffer and offscreen rendering. // URP passes fill the default pre-Record, then we freeze the default and pass it as staging during the execute timeline between passes, @@ -54,14 +60,41 @@ internal sealed class GlobalShaderVariablesUploader : IUniversalGlobalShaderVari //////////////////////////////////////////// + /// Temporary copies only, see Get() /// + + // The uploader this temporary copy was made from, null on the renderers' uploaders. + private readonly GlobalShaderVariablesUploader m_Parent; + + // The temporary copy Get() hands out, reused from one pass to the next. + private GlobalShaderVariablesUploader m_Temporary; + + // Between Get() and Dispose(). Dispose() records the restore on the command buffer of the last push, + // none until the first push, when there is nothing to put back. + private bool m_IsOpen; + private IBaseCommandBuffer m_TemporaryCmd; + + // Loose uniforms: the variables the temporary copy pushed, which Dispose() pushes again from the parent. + private GlobalShaderVariablesDirty m_PushedByTemporary; + + // Constant buffer: whether the temporary copy took the global slot, and which parent buffer held it at + // Get(), noted then because the temporary copy's pushes change the parent's state. + private bool m_TemporaryBoundGlobalSlot; + private bool m_ParentDefaultsWereBound; + + // Constant buffer: what PushToCompute() binds, apart from the global slot so the other shaders never read it. + private ConstantBuffer m_ComputeConstantBuffer; + + // The compute shaders PushToCompute() bound, unbound by Dispose(): their binding wins over the global slot. + private List m_BoundComputeShaders; + + private const string k_TemporaryNotDisposed = "A temporary copy of the URP global shader variables wasn't disposed. Dispose the object that Get() returns before the render function returns, for example with a using statement."; + + //////////////////////////////////////////// + /// /// Determines whether to push a persistent constant buffer or to fill dynamic constant buffers with loose uniforms APIs (cmd.SetGlobalFloat, ...) + /// Set before each fill; the pipeline unbinds the slot when it leaves the persistent mode. /// - /// - /// Refreshed by the renderer every frame: the setting behind it can be toggled at any time in the Editor. - /// Switching mode is safe mid-flight because every frame starts with a PushDefaultToGlobal, which re-establishes - /// all the variables in the mode currently selected. - /// internal bool useConstantBuffer { get; set; } internal GlobalShaderVariablesUploader(GlobalShaderVariablesGroup ownedGroups) @@ -71,6 +104,13 @@ internal GlobalShaderVariablesUploader(GlobalShaderVariablesGroup ownedGroups) m_DefaultDirty.Clear(); } + // Temporary copies are only made by Get(). + private GlobalShaderVariablesUploader(GlobalShaderVariablesUploader parent) + : this(parent.m_OwnedGroups) + { + m_Parent = parent; + } + /// /// Opens the fill window: the caller is about to write the values of this camera through the accessors. /// Paired with , one pair per camera render since the uploader outlives them. @@ -92,9 +132,24 @@ internal void Release() m_OverrideConstantBuffer?.Release(); m_OverrideConstantBuffer = null; + m_ComputeConstantBuffer?.Release(); + m_ComputeConstantBuffer = null; + m_IsFillingDefaults = false; m_IsDefaultBufferUploaded = false; m_IsDefaultBufferBound = false; + + // The temporary copy owns buffers too. + m_Temporary?.Release(); + m_Temporary = null; + } + + /// + /// Unbinds the global constant buffer slot. + /// + internal static void UnbindGlobal() + { + Shader.SetGlobalConstantBuffer(k_GlobalShaderVariablesID, (GraphicsBuffer)null, 0, 0); } /// @@ -104,7 +159,7 @@ internal void Release() /// /// /// Thrown when no fill window is open, so either called twice or without a matching . - /// Closing twice would promote execute-time overrides to defaults, making a later PushDefaultToGlobal restore + /// Closing twice would promote execute-time overrides to defaults, making a later PushDefault restore /// values the fill never produced; closing without opening means the camera state was never filled. /// internal void EndFill() @@ -129,18 +184,61 @@ internal void EndFill() m_DivergedGroups = GlobalShaderVariablesGroup.None; } - public void PushDefaultToGlobal(IBaseCommandBuffer cmd) => PushDefaultToGlobal(cmd, GlobalShaderVariablesGroup.All); + public void PushDefault(IBaseCommandBuffer cmd) => PushDefault(cmd, GlobalShaderVariablesGroup.All); - internal void PushDefaultToGlobal(IBaseCommandBuffer cmd, GlobalShaderVariablesGroup groups) + internal void PushDefault(IBaseCommandBuffer cmd, GlobalShaderVariablesGroup groups) { ResetToDefault(groups); - PushGlobal(cmd, groups); + Push(cmd, groups); + } + + // The base variables cmd.SetupCameraProperties() writes as loose uniforms. + private const GlobalShaderVariablesBaseDirty k_WrittenByCameraSetup = + GlobalShaderVariablesBaseDirty._Time | GlobalShaderVariablesBaseDirty._SinTime | GlobalShaderVariablesBaseDirty._CosTime | + GlobalShaderVariablesBaseDirty.unity_DeltaTime | GlobalShaderVariablesBaseDirty._ScreenParams | + GlobalShaderVariablesBaseDirty._ZBufferParams | GlobalShaderVariablesBaseDirty.unity_OrthoParams; + + // Pushes the staged values of these variables again, after the camera setup overwrote them. + internal void PushAfterCameraSetup(IBaseCommandBuffer cmd) + { + ThrowIfTemporaryOpen(); + + // The bound buffer hides the loose uniforms the setup wrote. + if (useConstantBuffer) + return; + + // Only what URP filled: a variable it never wrote keeps the engine's value. + var overwritten = new GlobalShaderVariablesDirty { varsBase = k_WrittenByCameraSetup & m_DefaultDirty.varsBase }; + + ConstantBufferPropertyWarnings.BeginPipelineWrites(); + m_StagingVars.SetGlobals(cmd, overwritten, GlobalShaderVariablesGroup.Base); + ConstantBufferPropertyWarnings.EndPipelineWrites(); + + m_StagingDirty.varsBase &= ~overwritten.varsBase; } // Only pushes what changed since the last push, staging is assumed to still match engine state for the rest. - public void PushGlobal(IBaseCommandBuffer cmd) => PushGlobal(cmd, GlobalShaderVariablesGroup.All); + public void Push(IBaseCommandBuffer cmd) => Push(cmd, GlobalShaderVariablesGroup.All); - internal void PushGlobal(IBaseCommandBuffer cmd, GlobalShaderVariablesGroup groups) + internal void Push(IBaseCommandBuffer cmd, GlobalShaderVariablesGroup groups) + { + if (m_Parent == null) + ThrowIfTemporaryOpen(); + else + { + ThrowIfDisposed(); + + // Loose uniforms: a temporary copy's first push sends the parent's pending values first, so the GPU holds + // the staged state Dispose() puts back. + if (m_TemporaryCmd == null && !useConstantBuffer) + m_Parent.PushStaged(cmd, GlobalShaderVariablesGroup.All); + m_TemporaryCmd = cmd; + } + + PushStaged(cmd, groups); + } + + private void PushStaged(IBaseCommandBuffer cmd, GlobalShaderVariablesGroup groups) { groups &= m_OwnedGroups; @@ -159,7 +257,12 @@ internal void PushGlobal(IBaseCommandBuffer cmd, GlobalShaderVariablesGroup grou } else { + ConstantBufferPropertyWarnings.BeginPipelineWrites(); m_StagingVars.SetGlobals(cmd, toPush, groups); + ConstantBufferPropertyWarnings.EndPipelineWrites(); + + if (m_Parent != null) + m_PushedByTemporary.Add(toPush); } m_StagingDirty.varsBase &= ~toPush.varsBase; @@ -178,25 +281,14 @@ internal void PushGlobal(IBaseCommandBuffer cmd, GlobalShaderVariablesGroup grou /// private void PushConstantBuffer(BaseCommandBuffer cmd) { + if (m_Parent != null) + m_TemporaryBoundGlobalSlot = true; + // No group drifted away from the defaults, so staging still is the defaults, byte for byte. if (m_DivergedGroups == GlobalShaderVariablesGroup.None) { - m_DefaultConstantBuffer ??= new ConstantBuffer(ComputeBufferMode.Dynamic); - - // Pushing the default CB once per Begin/EndFilling (i.e once per camera per frame). - if (!m_IsDefaultBufferUploaded) - { - m_DefaultConstantBuffer.UpdateData(cmd, m_StagingVars); - m_IsDefaultBufferUploaded = true; - } - - // If default buffer has been bound already and no override buffer has been bound since, free no-op! - if (!m_IsDefaultBufferBound) - { - m_DefaultConstantBuffer.SetGlobal(cmd, k_GlobalShaderVariablesID); - m_IsDefaultBufferBound = true; - } - + // A temporary copy binds its parent's defaults buffer, which already holds them. + (m_Parent ?? this).BindDefaultConstantBuffer(cmd); return; } @@ -205,7 +297,26 @@ private void PushConstantBuffer(BaseCommandBuffer cmd) m_OverrideConstantBuffer.PushGlobal(cmd, m_StagingVars, k_GlobalShaderVariablesID); // The override buffer owns the slot now, so the next defaults push has to bind again. - m_IsDefaultBufferBound = false; + (m_Parent ?? this).m_IsDefaultBufferBound = false; + } + + // Uploads the defaults once per camera render and binds them, unless they are still bound. + private void BindDefaultConstantBuffer(BaseCommandBuffer cmd) + { + m_DefaultConstantBuffer ??= new ConstantBuffer(ComputeBufferMode.Dynamic); + + // From the defaults, not staging: a temporary copy binds this buffer while this uploader's staging diverged. + if (!m_IsDefaultBufferUploaded) + { + m_DefaultConstantBuffer.UpdateData(cmd, m_DefaultVars); + m_IsDefaultBufferUploaded = true; + } + + if (!m_IsDefaultBufferBound) + { + m_DefaultConstantBuffer.SetGlobal(cmd, k_GlobalShaderVariablesID); + m_IsDefaultBufferBound = true; + } } public void ResetToDefault() => ResetToDefault(GlobalShaderVariablesGroup.All); @@ -262,6 +373,166 @@ private void Mark3DDirty(GlobalShaderVariablesOnly3DDirty flag) // m_DivergedGroups |= GlobalShaderVariablesGroup.Only2D; // } + ///////////////////////////// Temporary copies ///////////////////////////// + // + // Get(), behind UniversalGlobalShaderData.Get() and Universal2DGlobalShaderData.Get(), copies staging into a + // second uploader, and Dispose() puts back what was bound at Get(), not the camera defaults, on the command + // buffer of the copy's last push. Loose uniforms: what the copy pushed is pushed again from the parent's + // staging. Constant buffer: the copy never writes the parent's buffers, so the parent's buffer is bound again. + // PushToCompute() binds one compute shader only, which works on async compute. + + internal GlobalShaderVariablesUploader Get() + { + if (m_Parent != null) + throw new InvalidOperationException("Get() can't be called on a temporary copy. Change and push the copy you already have."); + + if (m_IsFillingDefaults) + throw new InvalidOperationException("The URP global shader variables are only available while the render graph executes. Call Get() from the render function you pass to SetRenderFunc()."); + + ThrowIfTemporaryOpen(); + + var temporary = m_Temporary ??= new GlobalShaderVariablesUploader(this); + temporary.useConstantBuffer = useConstantBuffer; + temporary.m_DefaultVars = m_DefaultVars; + temporary.m_DefaultDirty = m_DefaultDirty; + temporary.m_StagingVars = m_StagingVars; + temporary.m_DivergedGroups = m_DivergedGroups; + temporary.m_StagingDirty.Clear(); + temporary.m_PushedByTemporary.Clear(); + temporary.m_TemporaryBoundGlobalSlot = false; + temporary.m_ParentDefaultsWereBound = m_IsDefaultBufferBound; + temporary.m_TemporaryCmd = null; + temporary.m_IsOpen = true; + return temporary; + } + + public void PushToCompute(IComputeCommandBuffer cmd, ComputeShader computeShader) + { + if (m_Parent == null) + throw new InvalidOperationException("PushToCompute() is only available on a temporary copy, see Get(). Compute shaders already read what GetGlobal() pushes."); + + ThrowIfDisposed(); + + if (computeShader == null) + throw new ArgumentNullException(nameof(computeShader)); + + if (!useConstantBuffer) + { + // A compute shader reads the global value of what it doesn't set, so the values go out globally until Dispose(). + Push(cmd); + return; + } + + m_TemporaryCmd = cmd; + m_ComputeConstantBuffer ??= new ConstantBuffer(ComputeBufferMode.Dynamic); + m_ComputeConstantBuffer.UpdateData((BaseCommandBuffer)cmd, m_StagingVars); + m_ComputeConstantBuffer.Set(cmd, computeShader, k_GlobalShaderVariablesID); + + m_BoundComputeShaders ??= new List(); + if (!m_BoundComputeShaders.Contains(computeShader)) + m_BoundComputeShaders.Add(computeShader); + } + + void IDisposable.Dispose() + { + // Disposing twice is a no-op, like for any IDisposable. The renderers' uploaders have nothing to undo. + if (m_Parent == null || !m_IsOpen) + return; + + Close(m_TemporaryCmd); + } + + // Puts back what was bound at Get(), on the given command buffer: the one of the last push, or the + // camera's when the end of the camera finds the copy open. Without one, the copy never pushed, or the render graph + // drops the commands of the camera. + private void Close(IBaseCommandBuffer cmd) + { + m_IsOpen = false; + m_TemporaryCmd = null; + if (cmd == null) + return; + + if (useConstantBuffer) + { + // The parent's buffers still hold what they held then: a parent push closes the temporary copy first. + if (m_TemporaryBoundGlobalSlot) + { + if (m_ParentDefaultsWereBound || m_Parent.m_OverrideConstantBuffer == null) + m_Parent.BindDefaultConstantBuffer((BaseCommandBuffer)cmd); + else + { + m_Parent.m_OverrideConstantBuffer.SetGlobal((BaseCommandBuffer)cmd, k_GlobalShaderVariablesID); + m_Parent.m_IsDefaultBufferBound = false; + } + } + } + else if (m_PushedByTemporary.isDirty) + { + ConstantBufferPropertyWarnings.BeginPipelineWrites(); + m_Parent.m_StagingVars.SetGlobals(cmd, m_PushedByTemporary, m_OwnedGroups); + ConstantBufferPropertyWarnings.EndPipelineWrites(); + } + + UnbindComputeShaders(cmd); + } + + // Only compute and unsafe passes can unbind. A copy closed from a raster pass keeps them until the end of the camera. + private void UnbindComputeShaders(IBaseCommandBuffer cmd) + { + if (m_BoundComputeShaders != null && m_BoundComputeShaders.Count > 0 && cmd is IComputeCommandBuffer computeCmd) + { + foreach (var computeShader in m_BoundComputeShaders) + computeCmd.SetComputeConstantBufferParam(computeShader, k_GlobalShaderVariablesID, (GraphicsBuffer)null, 0, 0); + m_BoundComputeShaders.Clear(); + } + } + + // A temporary copy must still be open. + private void ThrowIfDisposed() + { + if (m_Parent != null && !m_IsOpen) + throw new ObjectDisposedException(nameof(IGlobalShaderVariablesTemporaryUploader), "This temporary copy of the global shader variables was disposed. Call Get() again."); + } + + // Neither changed nor pushed, for example only read: nothing to put back, nothing lost by closing it. + private bool isUntouched => m_TemporaryCmd == null && !m_StagingDirty.isDirty; + + // A temporary copy still open when its parent pushes or hands out a new copy was never disposed. The render graph + // drops the commands of the camera on the exception, so nothing is recorded. + private void ThrowIfTemporaryOpen() + { + if (m_Temporary == null || !m_Temporary.m_IsOpen) + return; + + bool untouched = m_Temporary.isUntouched; + m_Temporary.Close(null); + if (!untouched) + throw new InvalidOperationException(k_TemporaryNotDisposed); + } + + // Called once the render graph executed, once per camera today: what a temporary copy left behind is closed on the + // camera's command buffer, which can always unbind. Throwing there would skip the submission of the camera. + internal void EndRenderGraph(CommandBuffer cmd) + { + if (m_Temporary == null) + return; + + if (m_Temporary.m_IsOpen && m_Temporary.isUntouched) + m_Temporary.Close(null); + + if (!(m_Temporary.m_IsOpen || m_Temporary.m_BoundComputeShaders?.Count > 0)) + return; + + var unsafeCmd = CommandBufferHelpers.GetUnsafeCommandBuffer(cmd); + if (m_Temporary.m_IsOpen) + { + m_Temporary.Close(unsafeCmd); + Debug.LogException(new InvalidOperationException(k_TemporaryNotDisposed)); + } + + m_Temporary.UnbindComputeShaders(unsafeCmd); + } + /// /// Fills the environment variables from the current render settings. /// @@ -768,6 +1039,16 @@ public void SetMainLightWorldToShadow(in MainLightShadowMatrices matrices) Mark3DDirty(GlobalShaderVariablesOnly3DDirty._MainLightWorldToShadow); } + /// + /// The world to shadow matrices of the main light, one per cascade plus the trailing no-op one. + /// + public MainLightShadowMatrices _MainLightWorldToShadow + { + get => m_StagingVars.vars3D._MainLightWorldToShadow; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => SetMainLightWorldToShadow(value); + } + /// /// Bounding sphere of the first cascade, xyz = center and w = radius. /// @@ -880,6 +1161,80 @@ public Vector4 _MainLightShadowmapSize } } + /// + /// Sets the per cascade PCSS scales, x = depth2RadialScale, y = radial2DepthScale, z = maxSampleZDistance and w = maxPCSSOffset. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetMainLightPCSSParams0(in MainLightShadowCascadeVectors vectors) + { + m_StagingVars.vars3D._MainLightPCSSParams0 = vectors; + Mark3DDirty(GlobalShaderVariablesOnly3DDirty._MainLightPCSSParams0); + } + + /// + /// Sets the per cascade PCSS sampling controls, x = minFilterSizeTexels, y = minFilterRadial2DepthScale, z = blockerRadial2DepthScale and w = blockerClumpSampleExponent. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetMainLightPCSSParams1(in MainLightShadowCascadeVectors vectors) + { + m_StagingVars.vars3D._MainLightPCSSParams1 = vectors; + Mark3DDirty(GlobalShaderVariablesOnly3DDirty._MainLightPCSSParams1); + } + + /// + /// Sets the per cascade PCSS atlas rectangles, xy = the tile offset and zw = the tile scale, both in atlas UV. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetMainLightPCSSAtlas(in MainLightShadowCascadeVectors vectors) + { + m_StagingVars.vars3D._MainLightPCSSAtlas = vectors; + Mark3DDirty(GlobalShaderVariablesOnly3DDirty._MainLightPCSSAtlas); + } + + /// + /// The per cascade PCSS scales, x = depth2RadialScale, y = radial2DepthScale, z = maxSampleZDistance and w = maxPCSSOffset. + /// + public MainLightShadowCascadeVectors _MainLightPCSSParams0 + { + get => m_StagingVars.vars3D._MainLightPCSSParams0; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => SetMainLightPCSSParams0(value); + } + + /// + /// The per cascade PCSS sampling controls, x = minFilterSizeTexels, y = minFilterRadial2DepthScale, z = blockerRadial2DepthScale and w = blockerClumpSampleExponent. + /// + public MainLightShadowCascadeVectors _MainLightPCSSParams1 + { + get => m_StagingVars.vars3D._MainLightPCSSParams1; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => SetMainLightPCSSParams1(value); + } + + /// + /// The per cascade PCSS atlas rectangles, xy = the tile offset and zw = the tile scale, both in atlas UV. + /// + public MainLightShadowCascadeVectors _MainLightPCSSAtlas + { + get => m_StagingVars.vars3D._MainLightPCSSAtlas; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => SetMainLightPCSSAtlas(value); + } + + /// + /// The PCSS controls shared by every cascade, x = the tile texel size, y = the blocker sample count, z = the filter sample count and w = the temporal frame index. + /// + public Vector4 _MainLightPCSSScalars + { + get => m_StagingVars.vars3D._MainLightPCSSScalars; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set + { + m_StagingVars.vars3D._MainLightPCSSScalars = value; + Mark3DDirty(GlobalShaderVariablesOnly3DDirty._MainLightPCSSScalars); + } + } + /// /// Soft shadow sampling offsets, xy = offset0 and zw = offset1. /// diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/GlobalShaderVariables/IGlobalShaderVariablesUploader.cs b/Packages/com.unity.render-pipelines.universal/Runtime/GlobalShaderVariables/IGlobalShaderVariablesUploader.cs index 799aaf17940..50ff3d30dc4 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/GlobalShaderVariables/IGlobalShaderVariablesUploader.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/GlobalShaderVariables/IGlobalShaderVariablesUploader.cs @@ -1,109 +1,410 @@ -namespace UnityEngine.Rendering.Universal +using System; +using UnityEngine.Rendering; + +namespace UnityEngine.Experimental.Rendering { - internal interface IUniversalGlobalShaderVariablesUploader : - IGlobalShaderVariablesOnly3DUploader, IGlobalShaderVariablesCommonUploader + /// + /// Provides the global shader variables of the URP 3D renderer that every later pass of the camera reads, as the + /// calling pass reads them on the render graph execute timeline. + /// + /// + /// The values are staged. URP keeps your changes from one pass to the next, and sends them to the GPU only when you + /// call . For changes to the calling pass only, use + /// instead. + /// + /// + /// This sample code makes texture sampling sharper for every later pass of the camera, for example when the + /// camera renders at a low render scale and an upscaler restores the resolution. A negative mip bias selects more + /// detailed mipmaps. + /// + /// + /// + public interface IUniversalGlobalShaderVariablesUploader : IGlobalShaderVariablesOnly3DUploader, IGlobalShaderVariablesCommonUploader {} - internal interface IUniversal2DGlobalShaderVariablesUploader : - IGlobalShaderVariablesOnly2DUploader, IGlobalShaderVariablesCommonUploader + /// + /// Provides the global shader variables of the URP 2D renderer that every later pass of the camera reads, as the + /// calling pass reads them on the render graph execute timeline. + /// + /// + /// The values are staged. URP keeps your changes from one pass to the next, and sends them to the GPU only when you + /// call . For changes to the calling pass only, use + /// instead. + /// + /// + /// This sample code tells the later passes of the camera that the camera target changed size, for example + /// after a custom upscaling pass that outputs the full camera resolution. The pass works with both the Universal + /// Renderer and the 2D Renderer. + /// + /// + /// + public interface IUniversal2DGlobalShaderVariablesUploader : IGlobalShaderVariablesOnly2DUploader, IGlobalShaderVariablesCommonUploader {} - // Passes used by both 2D/3D renderers can use this interface. - internal interface IGlobalShaderVariablesCommonUploader : - IGlobalShaderVariablesBaseUploader, IGlobalShaderVariablesGlobalUploader + /// + /// The global shader variables shared by URP 2D and 3D, with the methods that push and reset them. + /// + /// + /// Use this interface in passes that run with both the URP 3D and 2D renderers. The objects that + /// and return + /// implement it. + /// + /// + /// This sample code tells the later passes of the camera that the camera target changed size, for example + /// after a custom upscaling pass that outputs the full camera resolution. The pass works with both the Universal + /// Renderer and the 2D Renderer. + /// + /// + /// + public interface IGlobalShaderVariablesCommonUploader : IGlobalShaderVariablesBaseUploader, IGlobalShaderVariablesGlobalUploader {} - internal interface IGlobalShaderVariablesGlobalUploader + /// + /// Pushes and resets the staged global shader variables, which every later pass of the camera reads. + /// + /// + /// A pass that pushes changes global state: it must call + /// with true, which also keeps the render graph from culling it. + /// + /// + /// This sample code makes texture sampling sharper for every later pass of the camera, for example when the + /// camera renders at a low render scale and an upscaler restores the resolution. A negative mip bias selects more + /// detailed mipmaps. + /// + /// + /// This sample code sets the variables back to the values URP filled for the camera, for every later pass of + /// the camera. If keepMipBias is true, the later passes keep the texture mip bias that an earlier pass set, + /// and a single push sends the reset and the kept mip bias to the GPU. + /// + /// + /// + public interface IGlobalShaderVariablesGlobalUploader { - void PushGlobal(IBaseCommandBuffer cmd); + /// + /// Sends the variables changed since the last push to the GPU. They stay set for every later pass of the camera. + /// + /// The command buffer of the pass. + /// Thrown when there is something to push and the pass does not allow global + /// state modification, which the render graph checks when UNITY_ENABLE_CHECKS is defined. Also thrown while a temporary + /// copy that was changed or pushed is open. + void Push(IBaseCommandBuffer cmd); + /// + /// Sets the variables URP fills for the camera back to the values it filled, without pushing them. + /// void ResetToDefault(); - void PushDefaultToGlobal(IBaseCommandBuffer cmd); + /// + /// Sets the variables URP fills for the camera back to the values it filled, and pushes them. + /// + /// The command buffer of the pass. + /// Thrown when there is something to push and the pass does not allow global + /// state modification, which the render graph checks when UNITY_ENABLE_CHECKS is defined. Also thrown while a temporary + /// copy that was changed or pushed is open. + void PushDefault(IBaseCommandBuffer cmd); } - // Shared uploader surface for the variables contained in GlobalShaderVariablesBase. - internal interface IGlobalShaderVariablesBaseUploader + /// + /// A temporary copy of the global shader variables that applies to the current pass only. + /// + /// + /// + /// The and methods return this + /// copy. Its values start as the staged ones. Disposing it restores what was bound before it. + /// + /// + /// Disposing the copy records the restore on the command buffer of its last push. A copy that never pushed has nothing + /// to put back. Get() returns the same object every time, so don't use a copy after disposing it. + /// + /// + /// Push what you changed through GetGlobal() before calling Get(). With loose uniforms, the first push of the copy also + /// sends it, and it stays after the copy is disposed. With the persistent constant buffer, it only applies while the + /// copy is bound. + /// + /// + /// Only one temporary copy can be open at a time. Dispose it before the render function returns: calling Get() again, + /// or pushing through GetGlobal(), while a copy that was changed or pushed is open throws an InvalidOperationException. + /// A copy that was only read can stay open. URP closes a copy still open at the end of the camera, and logs that + /// exception if the copy was changed or pushed. + /// + /// + /// + /// This sample code draws the opaque objects again into a half-resolution texture, for example as the source + /// of a glow effect. The shaders of the pass read the screen size of the half-resolution texture, and the shaders + /// of later passes read the screen size of the camera. The renderer feature adds the pass to the renderer. + /// + /// + /// This sample code runs a compute shader that writes a quarter-resolution texture. The compute shader reads + /// the screen size of that texture, and the other shaders keep reading the screen size of the camera. The compute + /// shader needs a CSMain kernel that writes to a _Result texture. To read the global shader + /// variables, the compute shader must include the Core.hlsl file from the URP shader library. + /// + /// + /// This sample code draws the objects of a layer with the values URP filled for the camera. It ignores values + /// that earlier passes pushed for the rest of the camera. For example, a texture mip bias that an earlier pass + /// pushed doesn't apply to these objects. To draw these objects only in this pass, remove their layer from + /// **Opaque Layer Mask** in the Universal Renderer asset. + /// + /// + /// + /// + /// + /// + public interface IGlobalShaderVariablesTemporaryUploader : IDisposable { + /// + /// Sends the temporary values to the GPU for every shader of the pass, until the temporary copy is disposed. + /// + /// + /// This changes global state: the pass must call + /// with true. Not for async compute passes: use there, see its remarks. + /// + /// The command buffer of the pass. + /// Thrown when the temporary copy was disposed. + /// Thrown when there is something to push and the pass does not allow global + /// state modification. The render graph checks it when UNITY_ENABLE_CHECKS is defined. + void Push(IBaseCommandBuffer cmd); + + /// + /// Gives the temporary values to one compute shader, until the temporary copy is disposed. + /// + /// + /// With the persistent constant buffer, only reads these values: the other shaders + /// keep reading the staged values and the pass changes no global state, so this suits async compute passes. With + /// loose uniforms, the default and the only mode on OpenGL ES 3 (except on WebGL) and OpenGL Core, a compute shader + /// reads the global value of each variable it doesn't set itself, so URP pushes the values globally instead, like + /// , until the temporary copy is disposed. A pass that calls this must therefore call + /// with true. + /// + /// The command buffer of the pass, a compute or unsafe one. + /// The compute shader that reads the temporary values. + /// Thrown when is null. + /// Thrown when the temporary copy was disposed. + /// Thrown with loose uniforms when there is something to push and the + /// pass does not allow global state modification. + void PushToCompute(IComputeCommandBuffer cmd, ComputeShader computeShader); + + /// + /// Sets the variables URP fills for the camera back to the values it filled, in this copy only, without pushing them. + /// + void ResetToDefault(); + } + + /// + /// A temporary copy of the URP 3D global shader variables. + /// + /// + /// For details, refer to . + /// + /// + /// This sample code draws the opaque objects again into a half-resolution texture, for example as the source + /// of a glow effect. The shaders of the pass read the screen size of the half-resolution texture, and the shaders + /// of later passes read the screen size of the camera. The renderer feature adds the pass to the renderer. + /// + /// + /// + public interface IUniversalGlobalShaderVariablesTemporaryUploader : + IGlobalShaderVariablesBaseUploader, IGlobalShaderVariablesOnly3DUploader, IGlobalShaderVariablesTemporaryUploader + {} + + /// + /// A temporary copy of the URP 2D global shader variables. + /// + /// + /// For details, refer to . + /// + /// + /// This sample code draws the sprites of a layer with the 2D Renderer, with their shader animations stopped + /// at a given time, for example while the application is paused. The shaders of later passes read the time of the + /// camera. + /// + /// + /// + public interface IUniversal2DGlobalShaderVariablesTemporaryUploader : + IGlobalShaderVariablesBaseUploader, IGlobalShaderVariablesOnly2DUploader, IGlobalShaderVariablesTemporaryUploader + {} + + /// + /// The global shader variables shared by URP 2D and 3D, declared in GlobalShaderVariables.hlsl. Each property is + /// named after its shader variable. + /// + /// + /// In the time variables, t is Time.time (Time.realtimeSinceStartup in Edit mode), dt is Time.deltaTime and smoothdt + /// is Time.smoothDeltaTime. + /// _DitheringTextureInvSize is read-only: it describes the dithering texture URP binds. + /// + /// + /// This sample code draws the opaque objects again into a half-resolution texture, for example as the source + /// of a glow effect. The shaders of the pass read the screen size of the half-resolution texture, and the shaders + /// of later passes read the screen size of the camera. The renderer feature adds the pass to the renderer. + /// + /// + /// + public interface IGlobalShaderVariablesBaseUploader + { + /// The time, scaled: [t/20, t, t*2, t*3]. Vector4 _Time { get; set; } + /// Sine of the time: [sin(t/8), sin(t/4), sin(t/2), sin(t)]. Vector4 _SinTime { get; set; } + /// Cosine of the time: [cos(t/8), cos(t/4), cos(t/2), cos(t)]. Vector4 _CosTime { get; set; } + /// Delta time: [dt, 1/dt, smoothdt, 1/smoothdt]. Vector4 unity_DeltaTime { get; set; } + /// Time with its sine and cosine: [t, sin(t), cos(t), 0]. Vector4 _TimeParameters { get; set; } + /// The time parameters of the previous frame: [t, sin(t), cos(t), 0]. Vector4 _LastTimeParameters { get; set; } + /// Size of the camera viewport in pixels, before render scale: [width, height, 1 + 1/width, 1 + 1/height]. Vector4 _ScreenParams { get; set; } + /// Values used to linearize the Z buffer: [1 - far/near, far/near, x/far, y/far], or [-1 + far/near, 1, x/far, 1/far] with a reversed Z buffer. Vector4 _ZBufferParams { get; set; } + /// Half extents of the orthographic view: [orthographicSize * aspect, orthographicSize, unused, 1 if orthographic else 0]. Vector4 unity_OrthoParams { get; set; } + /// Scale of the current (xy) and previous (zw) viewports relative to the RTHandle reference size. URP fills (1, 1, 1, 1). Vector4 _RTHandleScale { get; set; } + /// The screen parameters after render scale and dynamic resolution, in the same layout as _ScreenParams. Vector4 _ScaledScreenParams { get; set; } + /// Size of the camera target after render scale and dynamic resolution: [width, height, 1/width, 1/height]. After upscaling, URP sets it to the upscaled size, but PushDefault() and ResetToDefault() put back the size before upscaling. Vector4 _ScreenSize { get; set; } + /// Screen size that shaders read instead of _ScreenSize when the camera uses a screen coordinates override (SCREEN_COORD_OVERRIDE), from UniversalAdditionalCameraData.screenSizeOverride. Vector4 _ScreenSizeOverride { get; set; } + /// Scale (xy) and bias (zw) applied to screen coordinates when the camera uses a screen coordinates override, from UniversalAdditionalCameraData.screenCoordScaleBias. Vector4 _ScreenCoordScaleBias { get; set; } + /// Ambient sky color of the gradient ambient mode. Vector4 unity_AmbientSky { get; set; } + /// Ambient equator color of the gradient ambient mode. Vector4 unity_AmbientEquator { get; set; } + /// Ambient ground color of the gradient ambient mode. Vector4 unity_AmbientGround { get; set; } + /// Texture mip bias: [mip bias, 2 ^ mip bias]. Vector2 _GlobalMipBias { get; set; } - float _DitheringTextureInvSize { get; set; } + /// Inverse width of the LOD cross fade dithering texture. + float _DitheringTextureInvSize { get; } // Environment + /// Color of the glossy reflections of materials with environment reflections off: the constant term of the ambient probe times the reflection intensity. Vector4 _GlossyEnvironmentColor { get; set; } + /// Shadow color of the subtractive mixed lighting mode. Vector4 _SubtractiveShadowColor { get; set; } + /// HDR decode instructions of the default reflection cubemap. Vector4 _GlossyEnvironmentCubeMap_HDR { get; set; } - - /// - /// Fills the environment variables from the current render settings. - /// - void SetEnvironmentVars(); } - // Uploader surface for the variables contained in GlobalShaderVariablesOnly3D (URP 3D only). - internal interface IGlobalShaderVariablesOnly3DUploader + /// + /// The global shader variables only URP 3D fills, declared in GlobalShaderVariables.hlsl. Each property + /// is named after its shader variable. + /// + /// + /// The objects that and + /// return implement this interface. The URP 2D renderer doesn't fill these variables. + /// The read-only properties describe what URP binds or configures for the camera: the light lists, the shadow maps + /// and their PCSS filtering, the light cookies, the probe volumes and the rendering layers. + /// + /// + /// This sample code draws the objects of a layer with the main light shadows of the first shadow cascade + /// only. The other cascades get the values that the shaders read beyond the last cascade: a matrix that has no + /// effect, and an empty percentage-closer soft shadows (PCSS) atlas tile. + /// + /// + /// + public interface IGlobalShaderVariablesOnly3DUploader { // Main Light + /// World to light matrix of the main light cookie. Matrix4x4 _MainLightWorldToLight { get; set; } + /// Direction towards the main light with w = 0 for a directional light, position with w = 1 otherwise. Vector4 _MainLightPosition { get; set; } + /// Color of the main light times its intensity, in rgb. w is 0 when the main light uses subtractive mixed lighting, 1 otherwise. Vector4 _MainLightColor { get; set; } + /// Occlusion probe channels of the main light. Vector4 _MainLightOcclusionProbes { get; set; } + /// Rendering layer mask of the main light. uint _MainLightLayerMask { get; set; } // Forward+ - Vector4 _FPParams0 { get; set; } - Vector4 _FPParams1 { get; set; } - Vector4 _FPParams2 { get; set; } + /// Forward+ parameters: [zBinScale, zBinOffset, lightCount, directionalLightCount]. + Vector4 _FPParams0 { get; } + /// Forward+ parameters: [tileScale.x, tileScale.y, tileCountX, wordsPerTile]. + Vector4 _FPParams1 { get; } + /// Forward+ parameters: [zBinCount, tileCount, tileCountY, 0]. + Vector4 _FPParams2 { get; } // Motion Vectors + /// Non-jittered view projection matrix of the camera. Matrix4x4 _NonJitteredViewProjMatrix { get; set; } + /// Non-jittered view projection matrix of the camera in the previous frame. Matrix4x4 _PrevViewProjMatrix { get; set; } // Additional Lights - Vector4 _AdditionalLightsCount { get; set; } + /// Number of additional lights the shaders may read, in x. + Vector4 _AdditionalLightsCount { get; } // Main Light Shadows - void SetMainLightWorldToShadow(in MainLightShadowMatrices matrices); + /// The world to shadow matrices of the main light, one per cascade plus a trailing no-op matrix for indices past the last cascade. + MainLightShadowMatrices _MainLightWorldToShadow { get; set; } + /// Bounding sphere of the first cascade, xyz = center and w = radius. Vector4 _CascadeShadowSplitSpheres0 { get; set; } + /// Bounding sphere of the second cascade, xyz = center and w = radius. Vector4 _CascadeShadowSplitSpheres1 { get; set; } + /// Bounding sphere of the third cascade, xyz = center and w = radius. Vector4 _CascadeShadowSplitSpheres2 { get; set; } + /// Bounding sphere of the fourth cascade, xyz = center and w = radius. Vector4 _CascadeShadowSplitSpheres3 { get; set; } + /// Squared radii of the four cascade bounding spheres. Vector4 _CascadeShadowSplitSphereRadii { get; set; } - Vector4 _MainLightShadowOffset0 { get; set; } - Vector4 _MainLightShadowOffset1 { get; set; } - Vector4 _MainLightShadowmapSize { get; set; } + /// Soft shadow sampling offsets, xy = offset0 and zw = offset1. + Vector4 _MainLightShadowOffset0 { get; } + /// Soft shadow sampling offsets, xy = offset2 and zw = offset3. + Vector4 _MainLightShadowOffset1 { get; } + /// xy = 1/width and 1/height, zw = width and height of the main light shadow map. + Vector4 _MainLightShadowmapSize { get; } + + // Main Light Shadows, PCSS + /// For each cascade: x = depth2RadialScale, y = radial2DepthScale, z = maxSampleZDistance, w = maxPCSSOffset. + MainLightShadowCascadeVectors _MainLightPCSSParams0 { get; } + /// For each cascade: x = minFilterSizeTexels, y = minFilterRadial2DepthScale, z = blockerRadial2DepthScale, w = blockerClumpSampleExponent. + MainLightShadowCascadeVectors _MainLightPCSSParams1 { get; } + /// For each cascade: atlas tile offset (xy) and scale (zw), in UV. + MainLightShadowCascadeVectors _MainLightPCSSAtlas { get; set; } + /// x = tile texel size, y = blocker sample count, z = filter sample count, w = temporal frame index. + Vector4 _MainLightPCSSScalars { get; } // Additional Lights Shadows - Vector4 _AdditionalShadowOffset0 { get; set; } - Vector4 _AdditionalShadowOffset1 { get; set; } - Vector4 _AdditionalShadowmapSize { get; set; } + /// Soft shadow sampling offsets, xy = offset0 and zw = offset1. + Vector4 _AdditionalShadowOffset0 { get; } + /// Soft shadow sampling offsets, xy = offset2 and zw = offset3. + Vector4 _AdditionalShadowOffset1 { get; } + /// xy = 1/width and 1/height, zw = width and height of the additional lights shadow map. + Vector4 _AdditionalShadowmapSize { get; } // Misc - float _MainLightCookieTextureFormat { get; set; } - float _AdditionalLightsCookieAtlasTextureFormat { get; set; } - uint _RenderingLayerMaxInt { get; set; } - uint _EnableProbeVolumes { get; set; } + /// How shaders read the main light cookie: 0 = RGB, 1 = alpha, 2 = red, -1 when the main light has no cookie. + float _MainLightCookieTextureFormat { get; } + /// How shaders read the additional lights cookie atlas: 0 = RGB, 1 = alpha, 2 = red. + float _AdditionalLightsCookieAtlasTextureFormat { get; } + /// Highest value a rendering layer mask can hold, given the configured mask size. + uint _RenderingLayerMaxInt { get; } + /// 1 when Adaptive Probe Volume data is loaded and usable, 0 otherwise. + uint _EnableProbeVolumes { get; } } - // Uploader surface for the variables contained in GlobalShaderVariablesOnly2D (URP 2D only). + /// + /// The global shader variables only URP 2D fills. + /// + /// + /// The objects that and + /// return implement this interface. It has no members yet, because the URP 2D renderer currently fills only the + /// variables in . + /// + /// + /// This sample code draws the sprites of a layer with the 2D Renderer, with their shader animations stopped + /// at a given time, for example while the application is paused. The shaders of later passes read the time of the + /// camera. + /// + /// + /// // Empty while that struct is disabled, kept so the 2D renderer keeps its own uploader surface. - internal interface IGlobalShaderVariablesOnly2DUploader + public interface IGlobalShaderVariablesOnly2DUploader { // URP 2D-only globals, empty so disabled. // Vector4 _URPDummy2D { get; set; } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/LightCookieManager.cs b/Packages/com.unity.render-pipelines.universal/Runtime/LightCookieManager.cs index 05f64a6dd42..81f67c03dc0 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/LightCookieManager.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/LightCookieManager.cs @@ -571,7 +571,7 @@ int FilterAndValidateAdditionalLights(UniversalLightData lightData, LightCookieM continue; } - ref var visLight = ref lightData.visibleLights.UnsafeElementAtMutable(i); + ref var visLight = ref lightData.visibleLights.UnsafeElementAt(i); Light light = visLight.light; // Skip lights without a cookie texture @@ -870,7 +870,7 @@ void UploadAdditionalLights(CommandBuffer cmd, UniversalLightData lightData, ref // Update the mapping m_VisibleLightIndexToShaderDataIndex[visIndex] = bufIndex; - ref var visLight = ref lightData.visibleLights.UnsafeElementAtMutable(visIndex); + ref var visLight = ref lightData.visibleLights.UnsafeElementAt(visIndex); // Update the (cpu) data lightTypes[bufIndex] = (int)visLight.lightType; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Mesh2D-Lit-Default.mat b/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Mesh2D-Lit-Default.mat index faeb7122638..1e74f8fe0a6 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Mesh2D-Lit-Default.mat +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Mesh2D-Lit-Default.mat @@ -40,11 +40,8 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Ints: [] - m_Floats: - - _EnableExternalAlpha: 0 + m_Floats: [] m_Colors: - _Color: {r: 1, g: 1, b: 1, a: 1} - - _Flip: {r: 1, g: 1, b: 1, a: 1} - - _RendererColor: {r: 1, g: 1, b: 1, a: 1} m_BuildTextureStacks: [] m_AllowLocking: 1 diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Mesh2D-Unlit-Default.mat b/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Mesh2D-Unlit-Default.mat index c6fa8644a67..0810c6899f1 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Mesh2D-Unlit-Default.mat +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Mesh2D-Unlit-Default.mat @@ -78,7 +78,6 @@ Material: - _Cutoff: 0.5 - _DetailNormalMapScale: 1 - _DstBlend: 0 - - _EnableExternalAlpha: 0 - _GlossMapScale: 1 - _Glossiness: 0.5 - _GlossyReflections: 1 @@ -94,7 +93,5 @@ Material: m_Colors: - _Color: {r: 1, g: 1, b: 1, a: 1} - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} - - _Flip: {r: 1, g: 1, b: 1, a: 1} - - _RendererColor: {r: 1, g: 1, b: 1, a: 1} m_BuildTextureStacks: [] m_AllowLocking: 1 diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Materials/RenderAs2D-Flattening.mat b/Packages/com.unity.render-pipelines.universal/Runtime/Materials/RenderAs2D-Flattening.mat index cef09c11af7..68cd8714c16 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Materials/RenderAs2D-Flattening.mat +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Materials/RenderAs2D-Flattening.mat @@ -40,11 +40,8 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Ints: [] - m_Floats: - - _EnableExternalAlpha: 0 + m_Floats: [] m_Colors: - _Color: {r: 1, g: 1, b: 1, a: 1} - - _Flip: {r: 1, g: 1, b: 1, a: 1} - - _RendererColor: {r: 1, g: 1, b: 1, a: 1} m_BuildTextureStacks: [] m_AllowLocking: 1 diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Sprite-Lit-Default.mat b/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Sprite-Lit-Default.mat index 2d0d49b678f..a99306a9e1b 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Sprite-Lit-Default.mat +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Sprite-Lit-Default.mat @@ -11,8 +11,7 @@ Material: m_Shader: {fileID: 4800000, guid: e260cfa7296ee7642b167f1eb5be5023, type: 3} m_Parent: {fileID: 0} m_ModifiedSerializedProperties: 0 - m_ValidKeywords: - - ETC1_EXTERNAL_ALPHA + m_ValidKeywords: [] m_InvalidKeywords: [] m_LightmapFlags: 4 m_EnableInstancingVariants: 0 @@ -42,11 +41,8 @@ Material: m_Offset: {x: 0, y: 0} m_Ints: [] m_Floats: - - _EnableExternalAlpha: 0 - _ZWrite: 0 m_Colors: - _Color: {r: 1, g: 1, b: 1, a: 1} - - _Flip: {r: 1, g: 1, b: 1, a: 1} - - _RendererColor: {r: 1, g: 1, b: 1, a: 1} m_BuildTextureStacks: [] m_AllowLocking: 1 diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Sprite-Unlit-Default.mat b/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Sprite-Unlit-Default.mat index ce10ad8f043..7a92f09ff56 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Sprite-Unlit-Default.mat +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Sprite-Unlit-Default.mat @@ -9,7 +9,7 @@ Material: m_PrefabAsset: {fileID: 0} m_Name: Sprite-Unlit-Default m_Shader: {fileID: 4800000, guid: 13c02b14c4d048fa9653293d54f6e0e1, type: 3} - m_ShaderKeywords: ETC1_EXTERNAL_ALPHA + m_ShaderKeywords: m_LightmapFlags: 4 m_EnableInstancingVariants: 0 m_DoubleSidedGI: 0 @@ -38,9 +38,6 @@ Material: m_Ints: [] m_Floats: - PixelSnap: 0 - - _EnableExternalAlpha: 0 m_Colors: - _Color: {r: 1, g: 1, b: 1, a: 1} - - _Flip: {r: 1, g: 1, b: 1, a: 1} - - _RendererColor: {r: 1, g: 1, b: 1, a: 1} m_BuildTextureStacks: [] diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Materials/SpriteMask-Default.mat b/Packages/com.unity.render-pipelines.universal/Runtime/Materials/SpriteMask-Default.mat index 993716feb57..7faa52887db 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Materials/SpriteMask-Default.mat +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Materials/SpriteMask-Default.mat @@ -38,9 +38,6 @@ Material: m_Ints: [] m_Floats: - _Cutoff: 0 - - _EnableExternalAlpha: 0 m_Colors: - _Color: {r: 1, g: 1, b: 1, a: 1} - - _Flip: {r: 1, g: 1, b: 1, a: 1} - - _RendererColor: {r: 1, g: 1, b: 1, a: 1} m_BuildTextureStacks: [] diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Overrides/ExposureVolume.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Overrides/ExposureVolume.cs index 7fe1639ae31..b93d2c0edb3 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Overrides/ExposureVolume.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Overrides/ExposureVolume.cs @@ -28,11 +28,20 @@ public enum Mode /// [Tooltip("Specifies the method that is used to process exposure.")] public EnumParameter mode = new(Mode.Fixed); + // Largest EV where both 2^EV and 2^-EV are finite, normal floats + internal const float k_MinFixedExposure = -126f; + internal const float k_MaxFixedExposure = 126f; + /// - /// An exposure value for Cameras in this Volume, in EV units. + /// An exposure value for Cameras in this Volume, in EV units, clamped to the range [-126, 126]. /// This parameter is used only when is set. /// [Tooltip("An exposure value for Cameras in this Volume, in EV units.")] public FloatParameter fixedExposure = new(0f); + + internal float GetClampedFixedExposure() + { + return Mathf.Clamp(fixedExposure.value, k_MinFixedExposure, k_MaxFixedExposure); + } } } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Overrides/ShadowsVolumeOverride.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Overrides/ShadowsVolumeOverride.cs new file mode 100644 index 00000000000..5739c8a1f9e --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Overrides/ShadowsVolumeOverride.cs @@ -0,0 +1,64 @@ +using System; + +namespace UnityEngine.Rendering.Universal +{ + /// + /// A volume component that holds the maximum shadow distance and the main light shadow cascade settings. + /// + [Serializable, VolumeComponentMenu("Lighting/Shadows")] + [SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))] + [DisplayInfo(name = "Shadows")] + public sealed class ShadowsVolumeOverride : VolumeComponent + { + /// + /// Maximum distance from the camera at which URP renders shadows, in meters. + /// + [Tooltip("Maximum distance from the camera at which URP renders shadows, in meters.")] + public NoInterpMinFloatParameter maxShadowDistance = new NoInterpMinFloatParameter(50f, 0f); + + /// + /// Number of cascades URP uses for main light shadows. + /// + [Tooltip("Number of cascades URP uses for main light shadows.")] + public NoInterpClampedIntParameter cascadeCount = new NoInterpClampedIntParameter(1, UniversalRenderPipelineAsset.k_ShadowCascadeMinCount, UniversalRenderPipelineAsset.k_ShadowCascadeMaxCount); + + /// + /// End of the first cascade as a fraction of the maximum shadow distance. + /// + [Tooltip("Where the first cascade ends and the second cascade starts.")] + public NoInterpClampedFloatParameter cascadeSplit0 = new NoInterpClampedFloatParameter(0.067f, 0f, 1f); + + /// + /// End of the second cascade as a fraction of the maximum shadow distance. + /// + [Tooltip("Where the second cascade ends and the third cascade starts.")] + public NoInterpClampedFloatParameter cascadeSplit1 = new NoInterpClampedFloatParameter(0.2f, 0f, 1f); + + /// + /// End of the third cascade as a fraction of the maximum shadow distance. + /// + [Tooltip("Where the third cascade ends and the fourth cascade starts.")] + public NoInterpClampedFloatParameter cascadeSplit2 = new NoInterpClampedFloatParameter(0.467f, 0f, 1f); + + /// + /// Fraction of the last cascade over which shadows fade out. + /// + [Tooltip("Fraction of the last cascade over which shadows fade out.")] + public NoInterpClampedFloatParameter lastCascadeBorder = new NoInterpClampedFloatParameter(0.2f, 0f, 1f); + + internal Vector3 GetCascadeSplit() + { + float s0 = cascadeSplit0.value; + float s1 = Mathf.Max(cascadeSplit1.value, s0); + float s2 = Mathf.Max(cascadeSplit2.value, s1); + + switch (cascadeCount.value) + { + case 1: return new Vector3(1f, 0f, 0f); + case 2: return new Vector3(s0, 1f, 0f); + case 3: return new Vector3(s0, s1, 0f); + default: return new Vector3(s0, s1, s2); + } + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Overrides/ShadowsVolumeOverride.cs.meta b/Packages/com.unity.render-pipelines.universal/Runtime/Overrides/ShadowsVolumeOverride.cs.meta new file mode 100644 index 00000000000..d54de1c728d --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Overrides/ShadowsVolumeOverride.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 6a8f8364e4564d979b2a63400c85adea diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Overrides/SurfaceCacheGIVolumeOverride.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Overrides/SurfaceCacheGIVolumeOverride.cs index 800040f7620..4ba65081fd9 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Overrides/SurfaceCacheGIVolumeOverride.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Overrides/SurfaceCacheGIVolumeOverride.cs @@ -8,6 +8,9 @@ namespace UnityEngine.Rendering.Universal /// [Serializable, VolumeComponentMenu("Lighting/Surface Cache Global Illumination")] [SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))] +#if SURFACE_CACHE_SUPPORTED || UNITY_EDITOR + [VolumeRequiresRendererFeatures(typeof(SurfaceCacheGIRendererFeature))] +#endif [DisplayInfo(name = "Surface Cache Global Illumination")] public class SurfaceCacheGIVolumeOverride : VolumeComponent { @@ -17,9 +20,10 @@ public class SurfaceCacheGIVolumeOverride : VolumeComponent /// Enables or disables Surface Cache Global Illumination for the cameras this volume affects. /// When enabled, it calculates indirect lighting at any value, which keeps /// the Surface Cache warm. When disabled, it does no per-frame work and discards its Surface Cache, - /// so enabling it again costs a warm-up. + /// so enabling it again costs a warm-up. While disabled, indirect lighting comes from the other + /// sources in the scene, such as lightmaps, light probes, and the ambient probe. /// - [Tooltip("When Enabled, Surface Cache Global Illumination calculates indirect lighting at any Intensity value. When Disabled, it does not.")] + [Tooltip("When Enabled, Surface Cache Global Illumination calculates indirect lighting at any Intensity value. When Disabled, it does not, and indirect lighting comes from lightmaps, light probes, and the ambient probe instead.")] public BoolParameter enabled = new BoolParameter(true, BoolParameter.DisplayType.EnumPopup); /// @@ -31,6 +35,12 @@ public class SurfaceCacheGIVolumeOverride : VolumeComponent [Tooltip("Scales the indirect lighting from Surface Cache Global Illumination. At 0 it adds no indirect lighting to the scene.")] public ClampedFloatParameter intensity = new ClampedFloatParameter(1.0f, 0.0f, 4.0f); + /// + /// Controls how Surface Cache GI handles transparent objects. 'Opaques And Cutouts' allows rays to pass through objects with cutout materials, but incurs a performance penalty. + /// + [Tooltip("Controls how Surface Cache GI handles transparent objects. Opaques and Cutouts allows rays to pass through objects with cutout materials, but incurs a performance penalty.")] + public EnumParameter transparencyMode = new(TransparencyMode.OpaquesOnly); + // ========================== // Light Transport Parameters // ========================== @@ -79,6 +89,14 @@ public class SurfaceCacheGIVolumeOverride : VolumeComponent [Tooltip("Number of punctual light candidates considered for each punctual light sample. Higher values reduce noise at a minor performance cost.")] public ClampedIntParameter lightTransportPunctualLightCandidateCount = new ClampedIntParameter(k_Presets[(int)k_defaultPresetQuality].lightTransportPunctualLightCandidateCount, 1, 32); + /// + /// Offsets ray origins along the surface normal, in world units. Increase this to fix dark artifacts when the ray tracing geometry + /// differs from the rasterized geometry, for example when an object is rasterized with a less detailed mesh LOD, because ray tracing always uses mesh LOD 0. High values can cause light leaking. + /// + [AdditionalProperty] + [Tooltip("Offsets ray origins along the surface normal, in world units. Increase this to fix dark artifacts when the ray tracing geometry differs from the rasterized geometry, for example when an object is rasterized with a less detailed mesh LOD, because ray tracing always uses mesh LOD 0. High values can cause light leaking.")] + public MinFloatParameter lightTransportRayTracingNormalBias = new MinFloatParameter(0.0f, 0.0f); + // ============================ // Patch Filtering Parameters // ============================ @@ -161,6 +179,126 @@ public class SurfaceCacheGIVolumeOverride : VolumeComponent [Tooltip("Reduces flickering on flat surfaces lined up with the voxel grid (e.g. a floor at height 0). When off, no warping is applied.")] public BoolParameter volumePatchWarpingEnabled = new BoolParameter(true); + /// + /// Describes how Surface Cache GI handles transparent objects. + /// + public enum TransparencyMode + { + /// + /// All geometry is treated as opaque. + /// + OpaquesOnly, + + /// + /// Rays may pass through objects using cutout materials. + /// + OpaquesAndCutouts, + } + + // ======================= + // Entity Culling + // ======================= + + /// + /// How the distance beyond which entities are culled is set. + /// Entities that are too far away or too small as seen from every camera are left out of the Surface Cache + /// world, which makes it cheaper to update. GameObjects are not affected. + /// + /// + public enum EntityCullingSphereMode + { + /// + /// Entities are not culled by distance. + /// + None, + + /// + /// The distance is half the , the radius of the Surface Cache volume, plus . + /// + VolumePlusMargin, + + /// + /// The distance is . + /// + Fixed, + } + + /// + /// Whether entities are culled by distance, and whether the distance follows the Surface Cache volume plus a margin or is fixed. + /// + [AdditionalProperty] + [Tooltip("Leave out entities beyond a distance from every camera, following the Surface Cache volume plus a margin or at a fixed distance.")] + public EnumParameter entityCullingSphereMode = new(EntityCullingSphereMode.None); + + /// + /// Distance beyond the Surface Cache volume within which entities are kept. + /// Entities whose bounds are farther than half the plus this margin from every camera are culled. + /// When a Focus Target is set, the distance is measured from it instead of the camera. + /// Used when is . + /// + [AdditionalProperty] + [Tooltip("How far beyond the Surface Cache volume entities are kept.")] + public MinFloatParameter entityCullingDistanceMargin = new MinFloatParameter(100.0f, 0.0f); + + /// + /// Entities whose bounds are farther than this distance from every camera are culled. + /// When a Focus Target is set, the distance is measured from it instead of the camera. + /// Used when is . + /// + [AdditionalProperty] + [Tooltip("Entities farther than this from every camera are left out.")] + public MinFloatParameter entityCullingDistance = new MinFloatParameter(150.0f, 0.0f); + + /// + /// The unit of the minimum size below which entities are culled. + /// + /// + public enum EntityCullingSmallObjectUnit + { + /// + /// Entities are not culled by size. + /// + None, + + /// + /// The minimum size is , in pixels on screen. + /// + Pixels, + + /// + /// The minimum size is , an angle in degrees. + /// + Degrees, + } + + /// + /// Whether entities are culled by size, and whether the minimum size is set in pixels on screen or as an angle in degrees. + /// + [AdditionalProperty] + [Tooltip("Leave out entities smaller than a minimum size for every camera, in pixels on screen or in degrees.")] + public EnumParameter entityCullingSmallObjectUnit = new(EntityCullingSmallObjectUnit.None); + + /// + /// Entities whose bounds would cover fewer pixels than this on screen, as seen from every camera, are culled. + /// The size is converted to an angle using each camera's vertical field of view and pixel height. + /// When a Focus Target is set, the angle is measured from it instead of the camera. + /// Orthographic cameras do not cull by size. At 0, entities are never culled because of their size. + /// Used when is . + /// + [AdditionalProperty] + [Tooltip("Entities smaller than this many pixels on screen for every camera are left out.")] + public MinFloatParameter entityCullingMinScreenSize = new MinFloatParameter(16.0f, 0.0f); + + /// + /// Entities whose bounds cover a smaller angle than this, in degrees, as seen from every camera are culled. + /// When a Focus Target is set, the angle is measured from it instead of the camera. + /// At 0, entities are never culled because of their size. + /// Used when is . + /// + [AdditionalProperty] + [Tooltip("Entities covering a smaller angle than this, in degrees, for every camera are left out.")] + public ClampedFloatParameter entityCullingMinSolidAngle = new ClampedFloatParameter(1.0f, 0.0f, 90.0f); + // ======================= // Preset Utility // ======================= diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/AdditionalLightsShadowCasterPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/AdditionalLightsShadowCasterPass.cs index 38592151f8e..fe09ca0653f 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/AdditionalLightsShadowCasterPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/AdditionalLightsShadowCasterPass.cs @@ -51,6 +51,15 @@ static void ResetStaticsOnLoad() private Vector4[] m_AdditionalLightIndexToShadowParams; // per-additional-light shadow info passed to the lighting shader (x: shadowStrength, y: softShadows, z: light type, w: perLightFirstShadowSliceIndex) private Vector4[] m_ExtraForwardAdditionalLightIndexToShadowParams; // same as m_AdditionalLightIndexToShadowParams, but always indexed by visible light index. m_AdditionalLightIndexToShadowParams is indexed by shadowcasting light index when using deferred rendering. private bool m_NeedExtraForwardShadowParamsCopy; // do we need to populate m_ExtraForwardAdditionalLightIndexToShadowParams? + private short[] m_AdditionalLightIndexToForwardLightIndex; // maps an additional light index back to its forward light index, so the extra forward copies can be filled outside the light loop + private UniversalAdditionalLightData[] m_AdditionalLightIndexToAdditionalLightData; // the component the light loop already fetched, reused when the atlas layout is known + private Vector4[] m_AdditionalLightIndexToPCSSParams; // per-additional-light PCSS info (x: softness, y: min filter radius, z: blocker sample count, w: filter sample count) + private Vector4[] m_AdditionalLightIndexToPCSSZParams; // per-additional-light blocker depth linearization + private Vector4[] m_ExtraForwardAdditionalLightIndexToPCSSParams; // same as m_AdditionalLightIndexToPCSSParams, indexed like m_ExtraForwardAdditionalLightIndexToShadowParams + private Vector4[] m_ExtraForwardAdditionalLightIndexToPCSSZParams; // same as m_AdditionalLightIndexToPCSSZParams, indexed like m_ExtraForwardAdditionalLightIndexToShadowParams + private Vector4[] m_AdditionalLightShadowSliceIndexToPCSSAtlas; // per-shadow-slice atlas tile rectangle in UV, which the PCSS blocker search needs because it reads raw depth + private bool m_AnyAdditionalLightPCSS; // does any shadow casting additional light take the PCSS path this frame? + private int m_PCSSTemporalFrameIndex; // seeds the PCSS sample rotation private Vector4[] m_AdditionalLightReceiverNormalBiases; // per-additional-light world-space receiver normal bias, four lights packed per Vector4 to keep the uniform budget low (all zero in caster mode) private Vector4[] m_ExtraForwardAdditionalLightReceiverNormalBiases; // same as m_AdditionalLightReceiverNormalBiases, but indexed like m_ExtraForwardAdditionalLightIndexToShadowParams private bool m_ReceiverNormalBiasesCleared; // lets caster mode clear the arrays once instead of every frame @@ -74,8 +83,7 @@ static void ResetStaticsOnLoad() // Keep in sync with CBUFFER_START(AdditionalLightShadows) in com.unity.render-pipelines.universal/ShaderLibrary/Shadows.hlsl private const int k_WorldToShadowChannel = 0; private const int k_ShadowParamsChannel = 4; - private const int k_PCSSChannel = 5; - private const int k_AdditionalLightShadowsChannelCount = k_PCSSChannel + 3; // 4 (matrix) + 1 (shadow params) + 3 (PCSS) + private const int k_AdditionalLightShadowsChannelCount = k_ShadowParamsChannel + 1; // 4 (matrix) + 1 (shadow params), then the packed receiver normal biases private const int k_ReceiverNormalBiasesPerVector = 4; private readonly int m_ReceiverNormalBiasOffset; private readonly int m_AdditionalLightShadowsBufferLength; @@ -83,14 +91,28 @@ static void ResetStaticsOnLoad() private const string k_EmptyAdditionalLightShadowsCBName = "Empty Additional Light Shadows Buffer"; private const string k_ExtraForwardAdditionalLightShadowsCBName = "Extra Forward Additional Light Shadows Buffer"; + // Keep in sync with _AdditionalLightsPCSSData in com.unity.render-pipelines.universal/ShaderLibrary/Shadows.hlsl + private const int k_PCSSParamsChannel = 0; + private const int k_PCSSZParamsChannel = 1; + private const int k_PCSSAtlasChannel = 2; + private const int k_AdditionalLightPCSSChannelCount = k_PCSSAtlasChannel + 1; // params + z params + atlas + private const string k_AdditionalLightPCSSBufferName = "Additional Light PCSS Buffer"; + private const string k_ExtraForwardAdditionalLightPCSSBufferName = "Extra Forward Additional Light PCSS Buffer"; + private NativeArray m_AdditionalLightShadowsScratch; // write-only on CPU, just used to upload to GraphicsBuffer without allocating + private NativeArray m_AdditionalLightPCSSScratch; // same as m_AdditionalLightShadowsScratch, for _AdditionalLightsPCSSData private GraphicsBuffer m_AdditionalLightShadowsBuffer; private GraphicsBuffer m_ExtraForwardAdditionalLightShadowsBuffer; // only used with deferred renderer, see m_ExtraForwardAdditionalLightIndexToShadowParams private GraphicsBuffer m_EmptyAdditionalLightShadowsBuffer; + private GraphicsBuffer m_AdditionalLightPCSSBuffer; // created on every device that supports PCSS, only uploaded on frames where a light takes the PCSS path + private GraphicsBuffer m_ExtraForwardAdditionalLightPCSSBuffer; // same as m_ExtraForwardAdditionalLightShadowsBuffer, for _AdditionalLightsPCSSData // x is used in RenderAdditionalShadowMapAtlas to skip shadow map rendering for non-shadow-casting lights. // w is perLightFirstShadowSliceIndex, used in Lighting shader to find if Additional light casts shadows. private static readonly Vector4 c_DefaultShadowParams = new (0, 0, 0, -1); + + // zw are sample counts the shader divides by, so unused slots hold 1 + private static readonly Vector4 c_DefaultPCSSParams = new (0, 0, 1, 1); private static Vector4 s_EmptyAdditionalShadowFadeParams; private static bool s_ReceiverNormalBiasGlobalCleared; private static Vector4[] s_EmptyAdditionalLightIndexToShadowParams; @@ -105,6 +127,7 @@ private static class AdditionalShadowsConstantBuffer public static readonly int _AdditionalShadowFadeParams = Shader.PropertyToID("_AdditionalShadowFadeParams"); public static readonly int _AdditionalLightsShadowmapID = Shader.PropertyToID(k_AdditionalLightShadowMapTextureName); public static readonly int _AdditionalLightShadowsBufferID = Shader.PropertyToID("AdditionalLightShadows"); + public static readonly int _AdditionalLightsPCSSData = Shader.PropertyToID("_AdditionalLightsPCSSData"); } private class PassData @@ -131,6 +154,8 @@ public AdditionalLightsShadowCasterPass(RenderPassEvent evt) renderPassEvent = evt; m_UsePersistentConstantBuffer = RenderingUtils.usePersistentConstantBuffer; + // The PCSS data is only uploaded on the persistent constant buffer path + Debug.Assert(m_UsePersistentConstantBuffer || !ShadowUtils.isPCSSSupported, "PCSS needs the persistent constant buffer path."); m_MaxVisibleAdditionalLights = UniversalRenderPipeline.maxVisibleAdditionalLights; m_ReceiverNormalBiasOffset = m_MaxVisibleAdditionalLights * k_AdditionalLightShadowsChannelCount; m_AdditionalLightShadowsBufferLength = m_ReceiverNormalBiasOffset + GetReceiverNormalBiasVectorCount(m_MaxVisibleAdditionalLights); @@ -147,6 +172,8 @@ public AdditionalLightsShadowCasterPass(RenderPassEvent evt) m_VisibleLightIndexToAdditionalLightIndex = new short[maxVisibleLights]; m_VisibleLightIndexToIsCastingShadows = new bool[maxVisibleLights]; m_AdditionalLightIndexToShadowParams = new Vector4[maxAdditionalLightShadowParams]; + m_AdditionalLightIndexToForwardLightIndex = new short[maxAdditionalLightShadowParams]; + m_AdditionalLightIndexToAdditionalLightData = new UniversalAdditionalLightData[maxAdditionalLightShadowParams]; m_AdditionalLightReceiverNormalBiases = new Vector4[GetReceiverNormalBiasVectorCount(maxAdditionalLightShadowParams)]; s_EmptyAdditionalLightIndexToShadowParams = new Vector4[maxAdditionalLightShadowParams]; @@ -155,6 +182,11 @@ public AdditionalLightsShadowCasterPass(RenderPassEvent evt) m_AdditionalLightShadowSliceIndexTo_WorldShadowMatrix = new Matrix4x4[m_MaxVisibleAdditionalLights]; + // Full size, PackPCSSBuffer copies whole arrays + m_AdditionalLightIndexToPCSSParams = new Vector4[m_MaxVisibleAdditionalLights]; + m_AdditionalLightIndexToPCSSZParams = new Vector4[m_MaxVisibleAdditionalLights]; + m_AdditionalLightShadowSliceIndexToPCSSAtlas = new Vector4[m_MaxVisibleAdditionalLights]; + EnsureBuffersCreated(); } @@ -171,6 +203,8 @@ private void EnsureBuffersCreated() if (length <= 0) return; + int pcssLength = m_MaxVisibleAdditionalLights * k_AdditionalLightPCSSChannelCount; + if (m_NeedExtraForwardShadowParamsCopy && m_ExtraForwardAdditionalLightShadowsBuffer == null) { m_ExtraForwardAdditionalLightShadowsBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Constant, length, UnsafeUtility.SizeOf()) @@ -179,6 +213,28 @@ private void EnsureBuffersCreated() }; } + // Created and bound on every device that supports PCSS, even when the asset disables PCSS: with _SHADOWS_PCSS + // converted to a dynamic branch, every Lit variant keeps the read, and Metal and Vulkan skip the draws of a + // shader whose structured buffer isn't bound. The global binding covers the frames where this pass doesn't run. + if (m_AdditionalLightPCSSBuffer == null && ShadowUtils.isPCSSSupported) + { + m_AdditionalLightPCSSScratch = new NativeArray(pcssLength, Allocator.Persistent); + + m_AdditionalLightPCSSBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, pcssLength, UnsafeUtility.SizeOf()) + { + name = k_AdditionalLightPCSSBufferName + }; + Shader.SetGlobalBuffer(AdditionalShadowsConstantBuffer._AdditionalLightsPCSSData, m_AdditionalLightPCSSBuffer); + } + + if (m_NeedExtraForwardShadowParamsCopy && m_AdditionalLightPCSSBuffer != null && m_ExtraForwardAdditionalLightPCSSBuffer == null) + { + m_ExtraForwardAdditionalLightPCSSBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, pcssLength, UnsafeUtility.SizeOf()) + { + name = k_ExtraForwardAdditionalLightPCSSBufferName + }; + } + if (m_AdditionalLightShadowsBuffer != null) return; @@ -217,7 +273,11 @@ public void Dispose() if (m_AdditionalLightShadowsScratch.IsCreated) m_AdditionalLightShadowsScratch.Dispose(); + if (m_AdditionalLightPCSSScratch.IsCreated) + m_AdditionalLightPCSSScratch.Dispose(); + Shader.SetGlobalConstantBuffer(AdditionalShadowsConstantBuffer._AdditionalLightShadowsBufferID, (ComputeBuffer)null, 0, 0); + Shader.SetGlobalBuffer(AdditionalShadowsConstantBuffer._AdditionalLightsPCSSData, (GraphicsBuffer)null); m_AdditionalLightShadowsBuffer?.Dispose(); m_AdditionalLightShadowsBuffer = null; @@ -227,6 +287,12 @@ public void Dispose() m_EmptyAdditionalLightShadowsBuffer?.Dispose(); m_EmptyAdditionalLightShadowsBuffer = null; + + m_AdditionalLightPCSSBuffer?.Dispose(); + m_AdditionalLightPCSSBuffer = null; + + m_ExtraForwardAdditionalLightPCSSBuffer?.Dispose(); + m_ExtraForwardAdditionalLightPCSSBuffer = null; } } @@ -487,6 +553,7 @@ internal bool Setup(UniversalRenderingData renderingData, UniversalCameraData ca // Left null when there is nothing extra to bind, the empty shadowmap path already sets the params. bool bindExtraForwardShadowParams = m_NeedExtraForwardShadowParamsCopy && m_ShadowPassMode != ShadowPassMode.Empty; shadowData.extraForwardAdditionalLightShadowsBuffer = bindExtraForwardShadowParams ? m_ExtraForwardAdditionalLightShadowsBuffer : null; + shadowData.extraForwardAdditionalLightPCSSBuffer = bindExtraForwardShadowParams ? m_ExtraForwardAdditionalLightPCSSBuffer : null; shadowData.extraForwardAdditionalLightShadowParams = bindExtraForwardShadowParams ? m_ExtraForwardAdditionalLightIndexToShadowParams : null; shadowData.extraForwardAdditionalLightReceiverNormalBiases = bindExtraForwardShadowParams && shadowData.normalBiasMode == ShadowNormalBiasMode.Receiver ? m_ExtraForwardAdditionalLightReceiverNormalBiases : null; @@ -506,7 +573,11 @@ bool SetupShadowPassMode(UniversalRenderingData renderingData, UniversalCameraDa // Populate shadowData with empty buffer info for TransparentSettingsPass shadowData.emptyAdditionalLightShadowsBuffer = m_EmptyAdditionalLightShadowsBuffer; - shadowmapDepthStencilFormat = ShadowUtils.GetShadowmapDepthStencilFormat(stencilBuffer); + shadowmapDepthStencilFormat = ShadowUtils.GetShadowmapDepthStencilFormat(shadowData.additionalLightsShadowmapDepthBits, stencilBuffer); + shadowData.additionalLightsShadowmapFormat = shadowmapDepthStencilFormat; + + // Per frame, so the rotation keeps advancing while a cached atlas is reused + m_PCSSTemporalFrameIndex = ShadowUtils.GetPCSSTemporalFrameIndex(cameraData); bool shadowsEnabled = shadowData.additionalLightShadowsEnabled; bool stripShadowsOffVariants = cameraData.renderer.stripShadowsOffVariants; @@ -537,6 +608,9 @@ bool SetupShadowPassMode(UniversalRenderingData renderingData, UniversalCameraDa Clear(); + // Below the cached atlas early-out, so a reused atlas keeps the flag of the pass that filled it + m_AnyAdditionalLightPCSS = false; + renderTargetWidth = shadowData.additionalLightsShadowmapWidth; renderTargetHeight = shadowData.additionalLightsShadowmapHeight; @@ -580,6 +654,8 @@ bool SetupShadowPassMode(UniversalRenderingData renderingData, UniversalCameraDa { m_AdditionalLightIndexToVisibleLightIndex = new short[maxAdditionalLightShadowParams]; m_AdditionalLightIndexToShadowParams = new Vector4[maxAdditionalLightShadowParams]; + m_AdditionalLightIndexToForwardLightIndex = new short[maxAdditionalLightShadowParams]; + m_AdditionalLightIndexToAdditionalLightData = new UniversalAdditionalLightData[maxAdditionalLightShadowParams]; m_AdditionalLightReceiverNormalBiases = new Vector4[GetReceiverNormalBiasVectorCount(maxAdditionalLightShadowParams)]; } @@ -621,6 +697,12 @@ bool SetupShadowPassMode(UniversalRenderingData renderingData, UniversalCameraDa for (int i = 0; i < m_AdditionalLightIndexToShadowParams.Length; ++i) m_AdditionalLightIndexToShadowParams[i] = c_DefaultShadowParams; + Array.Fill(m_AdditionalLightIndexToForwardLightIndex, (short)-1); + Array.Clear(m_AdditionalLightIndexToAdditionalLightData, 0, m_AdditionalLightIndexToAdditionalLightData.Length); + Array.Fill(m_AdditionalLightIndexToPCSSParams, c_DefaultPCSSParams); + Array.Clear(m_AdditionalLightIndexToPCSSZParams, 0, m_AdditionalLightIndexToPCSSZParams.Length); + Array.Clear(m_AdditionalLightShadowSliceIndexToPCSSAtlas, 0, m_AdditionalLightShadowSliceIndexToPCSSAtlas.Length); + if (m_NeedExtraForwardShadowParamsCopy) { // Match length of m_AdditionalLightIndexToShadowParams, so the array can be copied into the constant buffer as-is. @@ -631,6 +713,15 @@ bool SetupShadowPassMode(UniversalRenderingData renderingData, UniversalCameraDa } Array.Copy(m_AdditionalLightIndexToShadowParams, m_ExtraForwardAdditionalLightIndexToShadowParams, maxAdditionalLightShadowParams); + + if (m_ExtraForwardAdditionalLightIndexToPCSSParams == null) + { + m_ExtraForwardAdditionalLightIndexToPCSSParams = new Vector4[m_MaxVisibleAdditionalLights]; + m_ExtraForwardAdditionalLightIndexToPCSSZParams = new Vector4[m_MaxVisibleAdditionalLights]; + } + + Array.Copy(m_AdditionalLightIndexToPCSSParams, m_ExtraForwardAdditionalLightIndexToPCSSParams, m_MaxVisibleAdditionalLights); + Array.Copy(m_AdditionalLightIndexToPCSSZParams, m_ExtraForwardAdditionalLightIndexToPCSSZParams, m_MaxVisibleAdditionalLights); } for (int i = 0; i < m_VisibleLightIndexToAdditionalLightIndex.Length; ++i) { @@ -659,6 +750,7 @@ bool SetupShadowPassMode(UniversalRenderingData renderingData, UniversalCameraDa continue; m_AdditionalLightIndexToVisibleLightIndex[lightIndexToUse] = (short) visibleLightIndex; + m_AdditionalLightIndexToForwardLightIndex[lightIndexToUse] = forwardLightIndex; if (m_ShadowSliceToAdditionalLightIndex.Count >= totalShadowSlicesCount) continue; @@ -667,6 +759,7 @@ bool SetupShadowPassMode(UniversalRenderingData renderingData, UniversalCameraDa if (light == null) break; light.TryGetComponent(out UniversalAdditionalLightData additionalLightData); + m_AdditionalLightIndexToAdditionalLightData[lightIndexToUse] = additionalLightData; LightType lightType = visibleLight.lightType; bool usesBakedShadows = UsesBakedShadows(light); @@ -812,6 +905,10 @@ bool SetupShadowPassMode(UniversalRenderingData renderingData, UniversalCameraDa float oneOverAtlasWidth = 1.0f / renderTargetWidth; float oneOverAtlasHeight = 1.0f / renderTargetHeight; + // The slices of one light are contiguous + int lastPCSSAdditionalLightIndex = -1; + UniversalRenderPipelineAsset asset = UniversalRenderPipeline.asset; + for (int globalShadowSliceIndex = 0; globalShadowSliceIndex < shadowCastingLightsBufferCount; ++globalShadowSliceIndex) { int additionalLightIndex = m_ShadowSliceToAdditionalLightIndex[globalShadowSliceIndex]; @@ -836,6 +933,39 @@ bool SetupShadowPassMode(UniversalRenderingData renderingData, UniversalCameraDa sliceTransform.m03 = m_AdditionalLightsShadowSlices[globalShadowSliceIndex].offsetX * oneOverAtlasWidth; sliceTransform.m13 = m_AdditionalLightsShadowSlices[globalShadowSliceIndex].offsetY * oneOverAtlasHeight; + // The first slice of a PCSS light already replaced its packed quality + bool usesPCSS = additionalLightIndex == lastPCSSAdditionalLightIndex || ShadowUtils.IsAdditionalLightPCSSEnabled(m_AdditionalLightIndexToShadowParams[additionalLightIndex].y, asset); + if (usesPCSS) + { + m_AnyAdditionalLightPCSS = true; + + // The blocker search reads raw depth, so it needs the tile rectangle on its own + m_AdditionalLightShadowSliceIndexToPCSSAtlas[globalShadowSliceIndex] = new Vector4(sliceTransform.m03, sliceTransform.m13, sliceTransform.m00, sliceTransform.m11); + + if (additionalLightIndex != lastPCSSAdditionalLightIndex) + { + ShadowUtils.ComputeAdditionalLightPCSSParams(visibleLights.UnsafeElementAt(visibleLightIndex).light.shapeRadius, + m_AdditionalLightIndexToAdditionalLightData[additionalLightIndex], sliceResolution, + m_AdditionalLightsShadowSlices[globalShadowSliceIndex].projectionMatrix, + out m_AdditionalLightIndexToPCSSParams[additionalLightIndex], + out m_AdditionalLightIndexToPCSSZParams[additionalLightIndex]); + m_AdditionalLightIndexToShadowParams[additionalLightIndex].y = ShadowUtils.k_SoftShadowQualityPCSS; + + if (m_NeedExtraForwardShadowParamsCopy) + { + short forwardLightIndex = m_AdditionalLightIndexToForwardLightIndex[additionalLightIndex]; + if (forwardLightIndex >= 0 && forwardLightIndex < m_ExtraForwardAdditionalLightIndexToPCSSParams.Length) + { + m_ExtraForwardAdditionalLightIndexToShadowParams[forwardLightIndex].y = ShadowUtils.k_SoftShadowQualityPCSS; + m_ExtraForwardAdditionalLightIndexToPCSSParams[forwardLightIndex] = m_AdditionalLightIndexToPCSSParams[additionalLightIndex]; + m_ExtraForwardAdditionalLightIndexToPCSSZParams[forwardLightIndex] = m_AdditionalLightIndexToPCSSZParams[additionalLightIndex]; + } + } + + lastPCSSAdditionalLightIndex = additionalLightIndex; + } + } + // We bake scale and bias to each shadow map in the atlas in the matrix. // saves some instructions in shader. m_AdditionalLightShadowSliceIndexTo_WorldShadowMatrix[globalShadowSliceIndex] = sliceTransform * m_AdditionalLightShadowSliceIndexTo_WorldShadowMatrix[globalShadowSliceIndex]; @@ -993,7 +1123,13 @@ internal static void BindAdditionalShadowParamsForForwardRendering(RasterCommand { GraphicsBuffer constantBuffer = shadowData.extraForwardAdditionalLightShadowsBuffer; if (constantBuffer != null) + { cmd.SetGlobalConstantBuffer(constantBuffer, AdditionalShadowsConstantBuffer._AdditionalLightShadowsBufferID, 0, constantBuffer.count * constantBuffer.stride); + + GraphicsBuffer pcssBuffer = shadowData.extraForwardAdditionalLightPCSSBuffer; + if (pcssBuffer != null) + cmd.SetGlobalBuffer(AdditionalShadowsConstantBuffer._AdditionalLightsPCSSData, pcssBuffer); + } else { if (shadowData.extraForwardAdditionalLightShadowParams != null) @@ -1038,6 +1174,9 @@ internal void ApplyEmptyShadowmapGlobals(IBaseCommandBuffer cmd) cmd.EnableKeyword(ShaderGlobalKeywords.AdditionalLightShadows); SetShadowParamsForEmptyShadowmap(cmd, m_EmptyAdditionalLightShadowsBuffer); + + if (m_AdditionalLightPCSSBuffer != null) + cmd.SetGlobalBuffer(AdditionalShadowsConstantBuffer._AdditionalLightsPCSSData, m_AdditionalLightPCSSBuffer); } internal void UpdateGlobalShaderVariables(GlobalShaderVariablesUploader vars, bool supportsSoftShadows) @@ -1109,7 +1248,7 @@ private void RenderAdditionalShadowmapAtlas(RasterCommandBuffer cmd, ref PassDat float slopeScaleDepthBias = ShadowUtils.GetSlopeScaleDepthBias(ref shadowLight, data.shadowData, visibleLightIndex); RendererList shadowRendererList = data.shadowRendererListsHdl[globalShadowSliceIndex]; - ShadowUtils.RenderShadowSlice(cmd, ref shadowSliceData, ref shadowRendererList, shadowSliceData.projectionMatrix, shadowSliceData.viewMatrix, slopeScaleDepthBias); + ShadowUtils.RenderShadowSlice(cmd, ref shadowSliceData, ref shadowRendererList, shadowSliceData.projectionMatrix, shadowSliceData.viewMatrix, slopeScaleDepthBias, useDepthClamp: false); additionalLightHasSoftShadows |= shadowLight.light.shadows == LightShadows.Soft; anyShadowSliceRenderer = true; } @@ -1135,6 +1274,7 @@ private void SetShadowGlobalKeywordsAndConstants(RasterCommandBuffer cmd, ref Pa bool softShadows = data.shadowData.supportsSoftShadows && (mainLightHasSoftShadows || additionalLightHasSoftShadows); data.shadowData.isKeywordSoftShadowsEnabled = softShadows; + data.shadowData.isAdditionalLightsPCSSEnabled = m_AnyAdditionalLightPCSS && anyShadowSliceRenderer; ShadowUtils.SetSoftShadowQualityShaderKeywords(cmd, data.shadowData); if (anyShadowSliceRenderer) @@ -1164,6 +1304,16 @@ private void PackShadowsConstantBuffer(GraphicsBuffer constantBuffer, Matrix4x4[ constantBuffer.SetData(m_AdditionalLightShadowsScratch); } + // Fills a graphics buffer with the data corresponding to the _AdditionalLightsPCSSData layout. + private void PackPCSSBuffer(GraphicsBuffer buffer, Vector4[] pcssParams, Vector4[] pcssZParams) + { + m_AdditionalLightPCSSScratch.GetSubArray(m_MaxVisibleAdditionalLights * k_PCSSParamsChannel, m_MaxVisibleAdditionalLights).CopyFrom(pcssParams); + m_AdditionalLightPCSSScratch.GetSubArray(m_MaxVisibleAdditionalLights * k_PCSSZParamsChannel, m_MaxVisibleAdditionalLights).CopyFrom(pcssZParams); + m_AdditionalLightPCSSScratch.GetSubArray(m_MaxVisibleAdditionalLights * k_PCSSAtlasChannel, m_MaxVisibleAdditionalLights).CopyFrom(m_AdditionalLightShadowSliceIndexToPCSSAtlas); + + buffer.SetData(m_AdditionalLightPCSSScratch); + } + // Set constant buffer data that will be used during the lighting/shadowing pass private void SetupAdditionalLightsShadowReceiverConstants(RasterCommandBuffer cmd, ref PassData data) { @@ -1185,7 +1335,7 @@ private void SetupAdditionalLightsShadowReceiverConstants(RasterCommandBuffer cm } ShadowUtils.GetScaleAndBiasForLinearDistanceFade(m_MaxShadowDistanceSq, m_CascadeBorder, out float shadowFadeScale, out float shadowFadeBias); - cmd.SetGlobalVector(AdditionalShadowsConstantBuffer._AdditionalShadowFadeParams, new Vector4(shadowFadeScale, shadowFadeBias, 0, 0)); + cmd.SetGlobalVector(AdditionalShadowsConstantBuffer._AdditionalShadowFadeParams, new Vector4(shadowFadeScale, shadowFadeBias, m_PCSSTemporalFrameIndex, 0)); if (data.usePersistentConstantBuffer) { @@ -1194,10 +1344,19 @@ private void SetupAdditionalLightsShadowReceiverConstants(RasterCommandBuffer cm PackShadowsConstantBuffer(m_AdditionalLightShadowsBuffer, m_AdditionalLightShadowSliceIndexTo_WorldShadowMatrix, m_AdditionalLightIndexToShadowParams, m_AdditionalLightReceiverNormalBiases); cmd.SetGlobalConstantBuffer(m_AdditionalLightShadowsBuffer, AdditionalShadowsConstantBuffer._AdditionalLightShadowsBufferID, 0, m_AdditionalLightShadowsScratch.Length * UnsafeUtility.SizeOf()); + if (m_AnyAdditionalLightPCSS) + PackPCSSBuffer(m_AdditionalLightPCSSBuffer, m_AdditionalLightIndexToPCSSParams, m_AdditionalLightIndexToPCSSZParams); + + // Bound even without a PCSS light, because the PCSS variants still reference it + if (m_AdditionalLightPCSSBuffer != null) + cmd.SetGlobalBuffer(AdditionalShadowsConstantBuffer._AdditionalLightsPCSSData, m_AdditionalLightPCSSBuffer); + if (m_NeedExtraForwardShadowParamsCopy && m_ExtraForwardAdditionalLightShadowsBuffer != null) { // Will be bound later in the frame, in BindAdditionalShadowParamsForForwardRendering PackShadowsConstantBuffer(m_ExtraForwardAdditionalLightShadowsBuffer, m_AdditionalLightShadowSliceIndexTo_WorldShadowMatrix, m_ExtraForwardAdditionalLightIndexToShadowParams, m_ExtraForwardAdditionalLightReceiverNormalBiases); + if (m_AnyAdditionalLightPCSS) + PackPCSSBuffer(m_ExtraForwardAdditionalLightPCSSBuffer, m_ExtraForwardAdditionalLightIndexToPCSSParams, m_ExtraForwardAdditionalLightIndexToPCSSZParams); } } } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/ColorGradingLutPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/ColorGradingLutPass.cs index e47f79b78df..8fdeb275622 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/ColorGradingLutPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/ColorGradingLutPass.cs @@ -13,8 +13,8 @@ public partial class ColorGradingLutPass : ScriptableRenderPass { const string k_InternalColorLutName = "_InternalColorGradingLut"; - readonly Material m_LutBuilderLdr; - readonly Material m_LutBuilderHdr; + readonly PostProcessMaterial m_LutBuilderLdr; + readonly PostProcessMaterial m_LutBuilderHdr; internal readonly GraphicsFormat m_HdrLutFormat; internal readonly GraphicsFormat m_LdrLutFormat; @@ -37,8 +37,8 @@ public ColorGradingLutPass(RenderPassEvent evt, PostProcessData data) profilingSampler = new ProfilingSampler("Blit Color LUT"); renderPassEvent = evt; - m_LutBuilderLdr = PostProcessUtils.LoadShader(data.shaders.lutBuilderLdrPS, passName); - m_LutBuilderHdr = PostProcessUtils.LoadShader(data.shaders.lutBuilderHdrPS, passName); + m_LutBuilderLdr = new PostProcessMaterial(data.shaders.lutBuilderLdrPS, passName); + m_LutBuilderHdr = new PostProcessMaterial(data.shaders.lutBuilderHdrPS, passName); // Warm up lut format as IsFormatSupported adds GC pressure... // UUM-41070: We require `Linear | Render` but with the deprecated FormatUsage this was checking `Blend` @@ -254,6 +254,9 @@ internal void Render(RenderGraph renderGraph, ContextContainer frameData, out Te UniversalCameraData cameraData = frameData.Get(); UniversalPostProcessingData postProcessingData = frameData.Get(); + bool hdrGrading = postProcessingData.gradingMode == ColorGradingMode.HighDynamicRange; + (hdrGrading ? m_LutBuilderHdr : m_LutBuilderLdr).Validate(); + this.ConfigureDescriptor(in postProcessingData, out var lutDesc, out var filterMode); #if ENABLE_VR && ENABLE_XR_MODULE @@ -295,11 +298,11 @@ internal void Render(RenderGraph renderGraph, ContextContainer frameData, out Te passData.internalColorLut = internalColorLut; builder.SetRenderAttachment(internalColorLut, 0, AccessFlags.WriteAll); - passData.lutBuilderLdr = m_LutBuilderLdr; - passData.lutBuilderHdr = m_LutBuilderHdr; + passData.lutBuilderLdr = m_LutBuilderLdr.material; + passData.lutBuilderHdr = m_LutBuilderHdr.material; passData.allowColorGradingACESHDR = m_AllowColorGradingACESHDR; passData.lutSize = postProcessingData.lutSize; - passData.hdrGrading = postProcessingData.gradingMode == ColorGradingMode.HighDynamicRange; + passData.hdrGrading = hdrGrading; // TODO RENDERGRAPH: culling? force culling off for testing builder.AllowPassCulling(false); @@ -329,8 +332,8 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer /// public void Cleanup() { - CoreUtils.Destroy(m_LutBuilderLdr); - CoreUtils.Destroy(m_LutBuilderHdr); + m_LutBuilderLdr.Dispose(); + m_LutBuilderHdr.Dispose(); #if ENABLE_VR && ENABLE_XR_MODULE m_QuadViewsColorLutHandle?.Release(); #endif diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DepthNormalOnlyPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DepthNormalOnlyPass.cs index 0c18a973ee6..e4ef02e2a6b 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DepthNormalOnlyPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DepthNormalOnlyPass.cs @@ -12,7 +12,6 @@ public partial class DepthNormalOnlyPass : ScriptableRenderPass { internal List shaderTagIds { get; set; } internal bool enableRenderingLayers { get; set; } = false; - internal RenderingLayerUtils.MaskSize renderingLayersMaskSize { get; set; } private FilteringSettings m_FilteringSettings; // Statics @@ -21,8 +20,8 @@ public partial class DepthNormalOnlyPass : ScriptableRenderPass internal static readonly string k_CameraNormalsTextureName = "_CameraNormalsTexture"; private static readonly int s_CameraDepthTextureID = Shader.PropertyToID("_CameraDepthTexture"); - private static readonly int s_CameraNormalsTextureID = Shader.PropertyToID(k_CameraNormalsTextureName); - private static readonly int s_CameraRenderingLayersTextureID = Shader.PropertyToID("_CameraRenderingLayersTexture"); + internal static readonly int s_CameraNormalsTextureID = Shader.PropertyToID(k_CameraNormalsTextureName); + internal static readonly int s_CameraRenderingLayersTextureID = Shader.PropertyToID("_CameraRenderingLayersTexture"); // Publishes a valid default as the normals global, for the frames where this pass isn't recorded internal static void SetDefaultNormalsGlobalTexture(IBaseRenderGraphBuilder builder, TextureHandle defaultNormalsTexture) @@ -122,7 +121,6 @@ private class PassData { internal bool enableRenderingLayers; internal bool outputSmoothness; - internal RenderingLayerUtils.MaskSize maskSize; internal RendererListHandle rendererList; } @@ -157,10 +155,7 @@ internal void Render(RenderGraph renderGraph, ContextContainer frameData, in Tex passData.outputSmoothness = renderingData.writesSmoothnessToDepthNormalsAlpha; if (passData.enableRenderingLayers) - { builder.SetRenderAttachment(renderingLayersTexture, 1, AccessFlags.Write); - passData.maskSize = renderingLayersMaskSize; - } var param = InitRendererListParams(renderingData, cameraData, lightData); param.filteringSettings.batchLayerMask = batchLayerMask; @@ -187,14 +182,12 @@ internal void Render(RenderGraph renderGraph, ContextContainer frameData, in Tex if (setGlobalDepth) builder.SetGlobalTextureAfterPass(depthTexture, s_CameraDepthTextureID); - // Required here because of RenderingLayerUtils.SetupProperties, and for setting keywords in ExecutePass + // Required here for setting keywords in ExecutePass if (passData.enableRenderingLayers || passData.outputSmoothness) builder.AllowGlobalStateModification(true); builder.SetRenderFunc(static (PassData data, RasterGraphContext context) => { - if (data.enableRenderingLayers) - RenderingLayerUtils.SetupProperties(context.cmd, data.maskSize); ExecutePass(context.cmd, data, data.rendererList); }); } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DepthOnlyPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DepthOnlyPass.cs index b184018245d..87b7cf07c6b 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DepthOnlyPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DepthOnlyPass.cs @@ -18,7 +18,7 @@ public partial class DepthOnlyPass : ScriptableRenderPass // Statics private static readonly ShaderTagId k_ShaderTagId = new ShaderTagId("DepthOnly"); - private static readonly int s_CameraDepthTextureID = Shader.PropertyToID("_CameraDepthTexture"); + internal static readonly int s_CameraDepthTextureID = Shader.PropertyToID("_CameraDepthTexture"); /// /// Creates a new DepthOnlyPass instance. diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DrawObjectsPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DrawObjectsPass.cs index ce8e86dfd69..62faf43c618 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DrawObjectsPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DrawObjectsPass.cs @@ -131,10 +131,7 @@ internal static void ExecutePass(RasterCommandBuffer cmd, PassData data, Rendere : new Vector4(flipSign, 0.0f, 1.0f, 1.0f); cmd.SetGlobalVector(ShaderPropertyId.scaleBiasRt, scaleBias); - // Set a value that can be used by shaders to identify when AlphaToMask functionality may be active - // The material shader alpha clipping logic requires this value in order to function correctly in all cases. - float alphaToMaskAvailable = ((data.cameraData.cameraTargetDescriptor.msaaSamples > 1) && data.isOpaque) ? 1.0f : 0.0f; - cmd.SetGlobalFloat(ShaderPropertyId.alphaToMaskAvailable, alphaToMaskAvailable); + RenderingUtils.SetAlphaToMaskAvailable(cmd, data.alphaToMaskAvailable); var activeDebugHandler = GetActiveDebugHandler(data.cameraData); if (activeDebugHandler != null) @@ -147,6 +144,9 @@ internal static void ExecutePass(RasterCommandBuffer cmd, PassData data, Rendere // Render objects that did not match any shader pass with error shader RenderingUtils.DrawRendererListObjectsWithError(cmd, ref objectsWithErrorRendererList); } + + if (data.alphaToMaskAvailable) + RenderingUtils.SetAlphaToMaskAvailable(cmd, false); } /// @@ -163,6 +163,7 @@ internal class PassData internal UniversalCameraData cameraData; internal UniversalShadowData shadowData; internal bool isOpaque; + internal bool alphaToMaskAvailable; internal bool shouldTransparentsReceiveShadows; internal bool shouldTransparentsReceiveSSR; internal uint batchLayerMask; @@ -252,6 +253,8 @@ internal void Render(RenderGraph renderGraph, ContextContainer frameData, in Tex builder.UseAllGlobalTextures(true); InitPassData(cameraData, shadowData, ref passData, batchLayerMask, resourceData.isActiveTargetBackBuffer); + TextureHandle msaaTarget = colorTarget.IsValid() ? colorTarget : depthTarget; + passData.alphaToMaskAvailable = m_IsOpaque && renderGraph.GetRenderTargetInfo(msaaTarget).msaaSamples > 1; if (colorTarget.IsValid()) { @@ -348,8 +351,9 @@ internal void Render(RenderGraph renderGraph, ContextContainer frameData, in Tex // Currently we only need to call this when the user doesn't want transparent objects to receive shadows if (!data.isOpaque && !data.shouldTransparentsReceiveShadows) { - MainLightShadowCasterPass.SetShadowParamsForEmptyShadowmap(context.cmd); + MainLightShadowCasterPass.SetShadowParamsForTransparentsNotReceivingShadows(context.cmd); AdditionalLightsShadowCasterPass.SetShadowParamsForEmptyShadowmap(context.cmd, data.shadowData.emptyAdditionalLightShadowsBuffer); + context.cmd.SetKeyword(ShaderGlobalKeywords.ShadowsPCSS, false); } bool yFlip = RenderingUtils.IsHandleYFlipped(context, in (data.albedoHdl.IsValid() ? ref data.albedoHdl : ref data.depthHdl)); @@ -401,7 +405,6 @@ internal DrawObjectsWithRenderingLayersPass(ProfilingSampler sampler, bool opaqu private class RenderingLayersPassData { internal PassData basePassData; - internal RenderingLayerUtils.MaskSize maskSize; public RenderingLayersPassData() { @@ -410,7 +413,7 @@ public RenderingLayersPassData() } internal void Render(RenderGraph renderGraph, ContextContainer frameData, in TextureHandle colorTarget, in TextureHandle renderingLayersTexture, in TextureHandle depthTarget, - in TextureHandle mainShadowsTexture, in TextureHandle additionalShadowsTexture, RenderingLayerUtils.MaskSize maskSize, uint batchLayerMask = uint.MaxValue) + in TextureHandle mainShadowsTexture, in TextureHandle additionalShadowsTexture, uint batchLayerMask = uint.MaxValue) { using (var builder = renderGraph.AddRasterRenderPass(passName, out var passData, profilingSampler)) { @@ -421,8 +424,7 @@ internal void Render(RenderGraph renderGraph, ContextContainer frameData, in Tex UniversalShadowData shadowData = frameData.Get(); InitPassData(cameraData, shadowData, ref passData.basePassData, batchLayerMask); - - passData.maskSize = maskSize; + passData.basePassData.alphaToMaskAvailable = passData.basePassData.isOpaque && renderGraph.GetRenderTargetInfo(colorTarget).msaaSamples > 1; passData.basePassData.albedoHdl = colorTarget; builder.SetRenderAttachment(colorTarget, 0, AccessFlags.Write); @@ -467,7 +469,7 @@ internal void Render(RenderGraph renderGraph, ContextContainer frameData, in Tex builder.UseRendererList(passData.basePassData.objectsWithErrorRendererListHdl); } - // Required here because of RenderingLayerUtils.SetupProperties + // Required here because of the WriteRenderingLayers keyword builder.AllowGlobalStateModification(true); if (cameraData.xr.enabled) @@ -486,14 +488,13 @@ internal void Render(RenderGraph renderGraph, ContextContainer frameData, in Tex // Enable Rendering Layers context.cmd.SetKeyword(ShaderGlobalKeywords.WriteRenderingLayers, true); - RenderingLayerUtils.SetupProperties(context.cmd, data.maskSize); - // Currently we only need to call this additional pass when the user // doesn't want transparent objects to receive shadows if (!data.basePassData.isOpaque && !data.basePassData.shouldTransparentsReceiveShadows) { - MainLightShadowCasterPass.SetShadowParamsForEmptyShadowmap(context.cmd); + MainLightShadowCasterPass.SetShadowParamsForTransparentsNotReceivingShadows(context.cmd); AdditionalLightsShadowCasterPass.SetShadowParamsForEmptyShadowmap(context.cmd, data.basePassData.shadowData.emptyAdditionalLightShadowsBuffer); + context.cmd.SetKeyword(ShaderGlobalKeywords.ShadowsPCSS, false); } bool yFlip = RenderingUtils.IsHandleYFlipped(context, in (data.basePassData.albedoHdl.IsValid() ? ref data.basePassData.albedoHdl : ref data.basePassData.depthHdl)); diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/ExposurePass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/ExposurePass.cs index f3f1fa87634..75a635e7f55 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/ExposurePass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/ExposurePass.cs @@ -30,26 +30,29 @@ private TextureHandle CreateTexture(RenderGraph renderGraph) public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) { + var cameraData = frameData.Get(); + var probe = cameraData.cameraType == CameraType.Reflection ? cameraData.camera.reflectionProbeRendered : null; + if (!GraphicsSettings.TryGetRenderPipelineSettings(out var exposureSetting) || !exposureSetting.UseExposure) + { + // This capture is not pre-exposed. Reset the probe's EV so it doesn't keep the value from an earlier + // capture made with exposure enabled, which would be applied once exposure is enabled again. + if (probe != null) + probe.exposureValue = 0f; return; + } var exposureVolume = VolumeManager.instance.stack.GetComponent(); if (exposureVolume.mode.value == ExposureVolume.Mode.Fixed) { - float exposureMultiplier = Mathf.Pow(2.0f, -exposureVolume.fixedExposure.value); + float fixedExposure = exposureVolume.GetClampedFixedExposure(); + float exposureMultiplier = Mathf.Pow(2.0f, -fixedExposure); var resourceData = frameData.Get(); - var cameraData = frameData.Get(); resourceData.exposureMultiplier = CreateTexture(renderGraph); - if (cameraData.cameraType == CameraType.Reflection) - { - var probe = cameraData.camera.reflectionProbeRendered; - if (probe != null) - { - probe.exposureValue = exposureVolume.fixedExposure.value; - } - } + if (probe != null) + probe.exposureValue = fixedExposure; using (var builder = renderGraph.AddRasterRenderPass("Set Fixed Exposure", out PassData passData)) { 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 aedb359bbb1..feb6f85f201 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/FinalBlitPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/FinalBlitPass.cs @@ -114,10 +114,26 @@ private static void ExecutePass(RasterCommandBuffer cmd, PassData data, RTHandle CoreUtils.SetKeyword(data.blitMaterialData.material, ShaderKeywordStrings._ENABLE_ALPHA_OUTPUT, data.enableAlphaOutput); - int shaderPassIndex = source.rt?.filterMode == FilterMode.Bilinear ? data.blitMaterialData.bilinearSamplerPass : data.blitMaterialData.nearestSamplerPass; + int shaderPassIndex = RequiresBilinearSampling(source, pixelRect) ? data.blitMaterialData.bilinearSamplerPass : data.blitMaterialData.nearestSamplerPass; Blitter.BlitTexture(cmd, source, scaleBias, data.blitMaterialData.material, shaderPassIndex); } + static bool RequiresBilinearSampling(RTHandle source, Rect destinationRect) + { + if (source.rt == null || source.rt.filterMode != FilterMode.Bilinear) + return false; + + Vector2Int sourceSize = source.useScaling + ? source.GetScaledSize(source.rtHandleProperties.currentViewportSize) + : new Vector2Int(source.rt.width, source.rt.height); + Vector4 dynamicallyScaledSourceSize = PostProcessUtils.CalcShaderSourceSize(sourceSize.x, sourceSize.y, source.rt); + int sourceWidth = Mathf.CeilToInt(dynamicallyScaledSourceSize.x); + int sourceHeight = Mathf.CeilToInt(dynamicallyScaledSourceSize.y); + int destinationWidth = Mathf.RoundToInt(destinationRect.xMax) - Mathf.RoundToInt(destinationRect.xMin); + int destinationHeight = Mathf.RoundToInt(destinationRect.yMax) - Mathf.RoundToInt(destinationRect.yMin); + return sourceWidth != destinationWidth || sourceHeight != destinationHeight; + } + private class PassData { internal TextureHandle source; @@ -231,7 +247,8 @@ internal void Render(RenderGraph renderGraph, UniversalCameraData cameraData, Un RTHandle sourceTex = data.source; Vector2 viewportScale = sourceTex.useScaling ? new Vector2(sourceTex.rtHandleProperties.rtHandleScale.x, sourceTex.rtHandleProperties.rtHandleScale.y) : Vector2.one; - int shaderPassIndex = sourceTex.rt?.filterMode == FilterMode.Bilinear ? data.blitMaterialData.bilinearSamplerPass : data.blitMaterialData.nearestSamplerPass; + var debugScreenRect = new Rect(0f, 0f, data.cameraData.pixelWidth, data.cameraData.pixelHeight); + int shaderPassIndex = RequiresBilinearSampling(sourceTex, debugScreenRect) ? data.blitMaterialData.bilinearSamplerPass : data.blitMaterialData.nearestSamplerPass; Blitter.BlitTexture(context.cmd, sourceTex, viewportScale, data.blitMaterialData.material, shaderPassIndex); } else diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/MainLightShadowCasterPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/MainLightShadowCasterPass.cs index 323b5cc068e..2dd1a44aeb3 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/MainLightShadowCasterPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/MainLightShadowCasterPass.cs @@ -27,6 +27,11 @@ public partial class MainLightShadowCasterPass : ScriptableRenderPass [NoAutoStaticsCleanup] private static readonly ProfilingSampler s_ProfilingSetupSampler = new("Setup Main Shadowmap"); [NoAutoStaticsCleanup] private static readonly ProfilingSampler s_SetKeywordsSampler = new("Set Main Light Shadow Keywords"); private readonly ShadowSliceData[] m_CascadeSlices; + private bool m_UsePCSS; + private MainLightShadowCascadeVectors m_PCSSParams0; + private MainLightShadowCascadeVectors m_PCSSParams1; + private MainLightShadowCascadeVectors m_PCSSAtlas; + private Vector4 m_PCSSScalars; // Constants and Statics private const int k_EmptyShadowMapDimensions = 1; @@ -62,6 +67,7 @@ private static class MainLightShadowConstantBuffer public static readonly int _MainLightShadowmapID = Shader.PropertyToID(k_MainLightShadowMapTextureName); public static readonly int _ShadowParams = Shader.PropertyToID("_MainLightShadowParams"); public static readonly int _ReceiverNormalBias = Shader.PropertyToID("_MainLightShadowReceiverNormalBias"); + public static readonly int _SoftShadowKernelParams = Shader.PropertyToID("_MainLightSoftShadowKernelParams"); } private class PassData @@ -190,7 +196,8 @@ internal bool Setup(UniversalRenderingData renderingData, UniversalCameraData ca { using var profScope = new ProfilingScope(s_ProfilingSetupSampler); - m_ShadowmapDepthStencilFormat = ShadowUtils.GetShadowmapDepthStencilFormat(stencilBuffer); + m_ShadowmapDepthStencilFormat = ShadowUtils.GetShadowmapDepthStencilFormat(shadowData.mainLightShadowmapDepthBits, stencilBuffer); + shadowData.mainLightShadowmapFormat = m_ShadowmapDepthStencilFormat; bool isOffscreenDepthTexture = cameraData.camera.targetTexture != null && cameraData.camera.targetTexture.format == RenderTextureFormat.Depth; bool willRenderShadowGeometry = shadowsEnabledByCamera && !isOffscreenDepthTexture && ShouldRenderShadowGeometry(renderingData, cameraData, lightData, shadowData); @@ -240,6 +247,19 @@ void SetupForShadowmapRendering(UniversalCameraData cameraData, UniversalLightDa m_MaxShadowDistanceSq = cameraData.maxShadowDistance * cameraData.maxShadowDistance; m_CascadeBorder = shadowData.mainLightShadowCascadeBorder; m_ShadowPassMode = ShadowPassMode.DrawGeometry; + + SetupPCSS(ref shadowLight, shadowData); + } + + void SetupPCSS(ref VisibleLight shadowLight, UniversalShadowData shadowData) + { + shadowLight.light.TryGetComponent(out UniversalAdditionalLightData additionalLightData); + m_UsePCSS = ShadowUtils.IsPCSSEnabled(ref shadowLight, additionalLightData, shadowData.supportsSoftShadows, UniversalRenderPipeline.asset); + if (!m_UsePCSS) + return; + + ShadowUtils.ComputeMainLightPCSSParams(additionalLightData, m_CascadeSlices, m_ShadowCasterCascadesCount, m_RenderTargetWidth, m_RenderTargetHeight, ref m_PCSSParams0, ref m_PCSSParams1, ref m_PCSSAtlas); + m_PCSSScalars = ShadowUtils.GetMainLightPCSSScalars(additionalLightData, m_CascadeSlices[0].resolution); } static bool MainLightHasMixedShadows(Light mainLight) @@ -262,6 +282,7 @@ void SetupForEmptyRendering(UniversalCameraData cameraData, Light mainLight, Uni #endif m_ShadowPassMode = ShadowPassMode.Empty; + m_UsePCSS = false; bool stripShadowsOffVariants = cameraData.renderer.stripShadowsOffVariants; m_SetKeywordForEmptyShadowmap = ShadowUtils.ShouldEnableKeywordForEmptyShadowmap(stripShadowsOffVariants, shadowData.mainLightShadowsEnabled); @@ -279,11 +300,11 @@ static Light GetMainLight(UniversalLightData lightData) return shadowLightIndex != -1 ? lightData.visibleLights[shadowLightIndex].light : null; } - static Vector4 ComputeShadowParamsForEmptyRendering(Light light, UniversalCameraData cameraData, UniversalShadowData shadowData) + internal static Vector4 ComputeShadowParamsForEmptyRendering(Light light, UniversalCameraData cameraData, UniversalShadowData shadowData) { bool softShadows = light.shadows == LightShadows.Soft && shadowData.supportsSoftShadows; ShadowUtils.GetMainLightShadowParams(light, softShadows, out float softShadowsProp, out float shadowStrength); - ShadowUtils.GetScaleAndBiasForLinearDistanceFade(cameraData.maxShadowDistance, shadowData.mainLightShadowCascadeBorder, out float shadowFadeScale, out float shadowFadeBias); + ShadowUtils.GetScaleAndBiasForLinearDistanceFade(cameraData.maxShadowDistance * cameraData.maxShadowDistance, shadowData.mainLightShadowCascadeBorder, out float shadowFadeScale, out float shadowFadeBias); return new Vector4(shadowStrength, softShadowsProp, shadowFadeScale, shadowFadeBias); } @@ -314,6 +335,13 @@ internal static void SetShadowParamsForEmptyShadowmap(IBaseCommandBuffer cmd) { cmd.SetGlobalVector(MainLightShadowConstantBuffer._ShadowParams, s_EmptyShadowParams); cmd.SetGlobalVector(MainLightShadowConstantBuffer._ReceiverNormalBias, Vector4.zero); + cmd.SetGlobalVector(MainLightShadowConstantBuffer._SoftShadowKernelParams, Vector4.zero); + } + + internal static void SetShadowParamsForTransparentsNotReceivingShadows(IBaseCommandBuffer cmd) + { + cmd.SetGlobalVector(MainLightShadowConstantBuffer._ShadowParams, k_DefaultEmptyShadowParams); + cmd.SetGlobalVector(MainLightShadowConstantBuffer._ReceiverNormalBias, Vector4.zero); } // Binds the default (1x1) shadowmap as the global main light shadow texture. Called from the renderer's @@ -338,7 +366,7 @@ internal void ApplyEmptyShadowmapGlobals(IBaseCommandBuffer cmd) SetShadowParamsForEmptyShadowmap(cmd); } - internal void UpdateGlobalShaderVariables(GlobalShaderVariablesUploader vars, UniversalLightData lightData, UniversalShadowData shadowData) + internal void UpdateGlobalShaderVariables(GlobalShaderVariablesUploader vars, UniversalCameraData cameraData, UniversalLightData lightData, UniversalShadowData shadowData) { if (m_ShadowPassMode == ShadowPassMode.Empty) { @@ -352,6 +380,21 @@ internal void UpdateGlobalShaderVariables(GlobalShaderVariablesUploader vars, Un VisibleLight shadowLight = lightData.visibleLights[shadowLightIndex]; FillMainLightShadowReceiverVars(ref shadowLight, shadowData, vars); + + if (m_UsePCSS) + FillMainLightPCSSVars(cameraData, vars); + } + + void FillMainLightPCSSVars(UniversalCameraData cameraData, GlobalShaderVariablesUploader vars) + { + vars.SetMainLightPCSSParams0(in m_PCSSParams0); + vars.SetMainLightPCSSParams1(in m_PCSSParams1); + vars.SetMainLightPCSSAtlas(in m_PCSSAtlas); + + // Per frame, so the rotation keeps advancing while a cached atlas is reused + Vector4 scalars = m_PCSSScalars; + scalars.w = ShadowUtils.GetPCSSTemporalFrameIndex(cameraData); + vars._MainLightPCSSScalars = scalars; } void FillMainLightShadowReceiverVars(ref VisibleLight shadowLight, UniversalShadowData shadowData, GlobalShaderVariablesUploader vars) @@ -408,7 +451,7 @@ void SetMainLightShadowGlobals(RasterCommandBuffer cmd, ref PassData data) return; VisibleLight shadowLight = data.lightData.visibleLights[shadowLightIndex]; - SetShadowGlobalKeywordsAndConstants(cmd, ref shadowLight, shadowLightIndex, data.shadowData); + SetShadowGlobalKeywordsAndConstants(cmd, ref shadowLight, shadowLightIndex, data.cameraData, data.shadowData); } void RenderMainLightCascadeShadowmap(RasterCommandBuffer cmd, ref PassData data) @@ -424,6 +467,7 @@ void RenderMainLightCascadeShadowmap(RasterCommandBuffer cmd, ref PassData data) ShadowUtils.SetCameraPosition(cmd, data.cameraData.worldSpaceCameraPos); float slopeScaleDepthBias = ShadowUtils.GetSlopeScaleDepthBias(ref shadowLight, data.shadowData, shadowLightIndex); + bool useDepthClamp = ShadowUtils.ShouldUseShadowDepthClamp(isDirectional: true); for (int cascadeIndex = 0; cascadeIndex < m_ShadowCasterCascadesCount; ++cascadeIndex) { @@ -431,27 +475,31 @@ void RenderMainLightCascadeShadowmap(RasterCommandBuffer cmd, ref PassData data) ShadowUtils.SetupShadowCasterConstantBuffer(cmd, ref shadowLight, shadowBias); cmd.SetKeyword(ShaderGlobalKeywords.CastingPunctualLightShadow, false); RendererList shadowRendererList = data.shadowRendererListsHandle[cascadeIndex]; - ShadowUtils.RenderShadowSlice(cmd, ref m_CascadeSlices[cascadeIndex], ref shadowRendererList, m_CascadeSlices[cascadeIndex].projectionMatrix, m_CascadeSlices[cascadeIndex].viewMatrix, slopeScaleDepthBias); + ShadowUtils.RenderShadowSlice(cmd, ref m_CascadeSlices[cascadeIndex], ref shadowRendererList, m_CascadeSlices[cascadeIndex].projectionMatrix, m_CascadeSlices[cascadeIndex].viewMatrix, slopeScaleDepthBias, useDepthClamp); } - SetShadowGlobalKeywordsAndConstants(cmd, ref shadowLight, shadowLightIndex, data.shadowData); + + SetShadowGlobalKeywordsAndConstants(cmd, ref shadowLight, shadowLightIndex, data.cameraData, data.shadowData); } } - internal void SetShadowGlobalKeywordsAndConstants(RasterCommandBuffer cmd, ref VisibleLight shadowLight, int shadowLightIndex, UniversalShadowData shadowData) + internal void SetShadowGlobalKeywordsAndConstants(RasterCommandBuffer cmd, ref VisibleLight shadowLight, int shadowLightIndex, UniversalCameraData cameraData, UniversalShadowData shadowData) { shadowData.isKeywordSoftShadowsEnabled = shadowLight.light.shadows == LightShadows.Soft && shadowData.supportsSoftShadows; + shadowData.isMainLightPCSSEnabled = m_UsePCSS; cmd.SetKeyword(ShaderGlobalKeywords.MainLightShadows, shadowData.mainLightShadowCascadesCount == 1); cmd.SetKeyword(ShaderGlobalKeywords.MainLightShadowCascades, shadowData.mainLightShadowCascadesCount > 1); ShadowUtils.SetSoftShadowQualityShaderKeywords(cmd, shadowData); - SetupMainLightShadowReceiverConstants(cmd, ref shadowLight, shadowLightIndex, shadowData); + SetupMainLightShadowReceiverConstants(cmd, ref shadowLight, shadowLightIndex, cameraData, shadowData); } - void SetupMainLightShadowReceiverConstants(RasterCommandBuffer cmd, ref VisibleLight shadowLight, int shadowLightIndex, UniversalShadowData shadowData) + void SetupMainLightShadowReceiverConstants(RasterCommandBuffer cmd, ref VisibleLight shadowLight, int shadowLightIndex, UniversalCameraData cameraData, UniversalShadowData shadowData) { Light light = shadowLight.light; bool softShadows = light.shadows == LightShadows.Soft && shadowData.supportsSoftShadows; ShadowUtils.GetMainLightShadowParams(light, softShadows, out float softShadowsProp, out float shadowStrength); + if (m_UsePCSS) + softShadowsProp = ShadowUtils.k_SoftShadowQualityPCSS; ShadowUtils.GetScaleAndBiasForLinearDistanceFade(m_MaxShadowDistanceSq, m_CascadeBorder, out float shadowFadeScale, out float shadowFadeBias); cmd.SetGlobalVector(MainLightShadowConstantBuffer._ShadowParams, new Vector4(shadowStrength, softShadowsProp, shadowFadeScale, shadowFadeBias)); @@ -463,6 +511,11 @@ void SetupMainLightShadowReceiverConstants(RasterCommandBuffer cmd, ref VisibleL receiverNormalBias[i] = ShadowUtils.GetReceiverNormalBias(ref shadowLight, shadowLightIndex, shadowData, m_CascadeSlices[i].projectionMatrix, m_CascadeSlices[i].resolution); } cmd.SetGlobalVector(MainLightShadowConstantBuffer._ReceiverNormalBias, receiverNormalBias); + + // A kernel radius of 0 keeps the soft shadow quality's fixed kernel. Every cascade tile has the same resolution. + bool useSoftShadowKernelRadius = softShadows && !m_UsePCSS && shadowData.softShadowKernelRadiusPercent > 0.0f; + float softShadowKernelRadius = useSoftShadowKernelRadius ? ShadowUtils.GetSoftShadowKernelRadius(shadowData.softShadowKernelRadiusPercent, m_CascadeSlices[0].resolution) : 0.0f; + cmd.SetGlobalVector(MainLightShadowConstantBuffer._SoftShadowKernelParams, new Vector4(softShadowKernelRadius, ShadowUtils.GetPCSSTemporalFrameIndex(cameraData), 0.0f, 0.0f)); } private void InitPassData( diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/MotionVectorRenderPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/MotionVectorRenderPass.cs index 899b23a7225..53299bced63 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/MotionVectorRenderPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/MotionVectorRenderPass.cs @@ -209,7 +209,8 @@ internal static void SetRenderGraphMotionVectorGlobalMatrices(RenderGraph render if (!cameraData.xr.enabled || !cameraData.xr.singlePassEnabled) return; - if (cameraData.camera.TryGetComponent(out var additionalCameraData)) + var additionalCameraData = cameraData.additionalCameraData; + if (additionalCameraData != null) { using (var builder = renderGraph.AddRasterRenderPass(s_SetMotionMatrixProfilingSampler.name, out var passData, s_SetMotionMatrixProfilingSampler)) { diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/BloomPostProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/BloomPostProcessPass.cs index ff157f0dbec..7827ec1ae6e 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/BloomPostProcessPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/BloomPostProcessPass.cs @@ -14,15 +14,15 @@ internal sealed class BloomPostProcessPass : PostProcessPass /// Generates bloom mipmap chain using dual filtering (downsample then upsample with tent filter) for efficient wide-radius bloom. static readonly ProfilingSampler k_ProfilingSamplerDual = ProfilingSampler.Create("Blit Bloom Mipmaps (Dual)", MarkerFlags.Default); - Material m_Material; - Material[] m_MaterialPyramid; + PostProcessMaterial m_Material; + PostProcessMaterial[] m_MaterialPyramid; // Cached bloom params from previous frame to avoid unnecessary material updates MaterialParams m_PrevParams; BloomMipPyramid m_MipPyramid; - bool m_IsValid; + bool m_IsDependency; public BloomMipPyramid mipPyramid => m_MipPyramid; @@ -34,33 +34,36 @@ public BloomPostProcessPass(Shader shader) this.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing - 1; this.profilingSampler = URPProfilingSamplers.Bloom; - m_Material = PostProcessUtils.LoadShader(shader, passName, logLevel: LogType.Log); + m_Material = new PostProcessMaterial(shader, passName); // Array for bloom pyramid materials. // Materials are references in the command buffer, so we need a separate material for each mip level. - m_MaterialPyramid = new Material[k_MaxPyramidSize]; + m_MaterialPyramid = new PostProcessMaterial[k_MaxPyramidSize]; for (uint i = 0; i < k_MaxPyramidSize; ++i) - m_MaterialPyramid[i] = PostProcessUtils.LoadShader(shader, passName, logLevel: LogType.Log); - - // Check if the pass init was successful. - m_IsValid = m_Material != null; - for(int i = 0; i < k_MaxPyramidSize; i++) - m_IsValid &= m_MaterialPyramid[i] != null; + m_MaterialPyramid[i] = new PostProcessMaterial(shader, passName); m_MipPyramid = new BloomMipPyramid(k_MaxPyramidSize); + + m_IsDependency = false; } public override void Dispose() { - CoreUtils.Destroy(m_Material); + m_Material.Dispose(); for(int i = 0; i < k_MaxPyramidSize; i++) - CoreUtils.Destroy(m_MaterialPyramid[i]); + m_MaterialPyramid[i].Dispose(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Setup(bool runAsDependency) + { + m_IsDependency = runAsDependency; } private class BloomPassData { internal Material material; - internal Material[] mipMaterials; + internal PostProcessMaterial[] mipMaterials; internal TextureHandle sourceTexture; @@ -69,11 +72,12 @@ private class BloomPassData public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) { - if (!m_IsValid) + var bloom = volumeStack.GetComponent(); + if (!bloom.IsActive() && !m_IsDependency) return; - var bloom = volumeStack.GetComponent(); - if (!bloom.IsActive()) + // The pyramid materials use the same shader, so they are valid if m_Material is. + if (!m_Material.Validate()) return; UniversalResourceData resourceData = frameData.Get(); @@ -111,18 +115,18 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer // Setting keywords can be somewhat expensive on low-end platforms. // Previous params are cached to avoid setting the same keywords every frame. bool paramsDirty = !m_PrevParams.Equals(ref newParams); - bool isParamsPropertySet = m_Material.HasProperty(ShaderConstants._Params); + bool isParamsPropertySet = m_Material.material.HasProperty(ShaderConstants._Params); if (paramsDirty || !isParamsPropertySet) { - m_Material.SetVector(ShaderConstants._Params, newParams.parameters); - m_Material.SetVector(ShaderConstants._Params2, newParams.parameters2); - CoreUtils.SetKeyword(m_Material, ShaderKeywordStrings.BloomHQ, newParams.highQualityFiltering); - CoreUtils.SetKeyword(m_Material, ShaderKeywordStrings._ENABLE_ALPHA_OUTPUT, newParams.enableAlphaOutput); + m_Material.material.SetVector(ShaderConstants._Params, newParams.parameters); + m_Material.material.SetVector(ShaderConstants._Params2, newParams.parameters2); + CoreUtils.SetKeyword(m_Material.material, ShaderKeywordStrings.BloomHQ, newParams.highQualityFiltering); + CoreUtils.SetKeyword(m_Material.material, ShaderKeywordStrings._ENABLE_ALPHA_OUTPUT, newParams.enableAlphaOutput); // These materials are duplicate just to allow different bloom blits to use different textures. for (uint i = 0; i < k_MaxPyramidSize; ++i) { - var materialPyramid = m_MaterialPyramid[i]; + var materialPyramid = m_MaterialPyramid[i].material; materialPyramid.SetVector(ShaderConstants._Params, newParams.parameters); CoreUtils.SetKeyword(materialPyramid, ShaderKeywordStrings.BloomHQ, newParams.highQualityFiltering); CoreUtils.SetKeyword(materialPyramid, ShaderKeywordStrings._ENABLE_ALPHA_OUTPUT, newParams.enableAlphaOutput); @@ -197,7 +201,7 @@ TextureHandle BloomGaussian(RenderGraph renderGraph, in TextureHandle source) using (var builder = renderGraph.AddUnsafePass(passName, out var passData, profilingSampler)) { passData.sourceTexture = source; - passData.material = m_Material; + passData.material = m_Material.material; passData.mipMaterials = m_MaterialPyramid; passData.mipPyramid = m_MipPyramid; @@ -262,7 +266,7 @@ TextureHandle BloomGaussian(RenderGraph renderGraph, in TextureHandle source) // gets overriden by the time the render func is executed. // Material is a reference, so all the blits would share the same material state in the cmdbuf. // NOTE: another option would be to use cmd.SetGlobalTexture(). - var upMaterial = data.mipMaterials[i]; + var upMaterial = data.mipMaterials[i].material; upMaterial.SetTexture(ShaderConstants._SourceTexLowMip, lowMip); Blitter.BlitCameraTexture(cmd, highMip, dst, loadAction, storeAction, upMaterial, ShaderPass.k_Upsample); @@ -281,7 +285,7 @@ TextureHandle BloomKawase(RenderGraph renderGraph, in TextureHandle source) using (var builder = renderGraph.AddUnsafePass(k_PassNameKawase, out var passData, k_ProfilingSamplerKawase)) { passData.sourceTexture = source; - passData.material = m_Material; + passData.material = m_Material.material; passData.mipMaterials = m_MaterialPyramid; passData.mipPyramid = m_MipPyramid; @@ -316,7 +320,7 @@ TextureHandle BloomKawase(RenderGraph renderGraph, in TextureHandle source) { TextureHandle src = ((i & 1) == 0) ? mipDownTextures[0] : mipUpTextures[0]; TextureHandle dst = ((i & 1) == 0) ? mipUpTextures[0] : mipDownTextures[0]; - Material mat = data.mipMaterials[i]; + Material mat = data.mipMaterials[i].material; Blitter.BlitCameraTexture(cmd, src, dst, loadAction, storeAction, mat, ShaderPass.k_Kawase); } @@ -335,7 +339,7 @@ TextureHandle BloomDual(RenderGraph renderGraph, in TextureHandle source) using (var builder = renderGraph.AddUnsafePass(k_PassNameDual, out var passData, k_ProfilingSamplerDual)) { passData.sourceTexture = source; - passData.material = m_Material; + passData.material = m_Material.material; passData.mipMaterials = m_MaterialPyramid; passData.mipPyramid = m_MipPyramid; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/DepthOfFieldBokehProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/DepthOfFieldBokehProcessPass.cs index f6e5c913e60..ca96eaf8ddd 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/DepthOfFieldBokehProcessPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/DepthOfFieldBokehProcessPass.cs @@ -9,8 +9,7 @@ internal sealed class DepthOfFieldBokehPostProcessPass : PostProcessPass public const string k_TargetName = "CameraColorDepthOfFieldBokeh"; const int k_DownSample = 2; - Material m_Material; - bool m_IsValid; + PostProcessMaterial m_Material; Vector4[] m_BokehKernel; int m_BokehHash; @@ -23,14 +22,12 @@ public DepthOfFieldBokehPostProcessPass(Shader shader) { this.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing - 1; this.profilingSampler = URPProfilingSamplers.BokehDepthOfField; - m_Material = PostProcessUtils.LoadShader(shader, passName, logLevel: LogType.Log); - m_IsValid = m_Material != null; + m_Material = new PostProcessMaterial(shader, passName); } public override void Dispose() { - CoreUtils.Destroy(m_Material); - m_IsValid = false; + m_Material.Dispose(); } private class DoFBokehPassData @@ -58,9 +55,6 @@ private class DoFBokehPassData public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) { - if (!m_IsValid) - return; - var depthOfField = volumeStack.GetComponent(); if (!depthOfField.IsActive() || depthOfField.mode.value != DepthOfFieldMode.Bokeh) return; @@ -69,6 +63,9 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer if (cameraData.isSceneViewCamera) return; + if (!m_Material.Validate()) + return; + var postProcessingData = frameData.Get(); var resourceData = frameData.Get(); @@ -127,7 +124,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer passData.depthTexture = resourceData.cameraDepthTexture; builder.UseTexture(resourceData.cameraDepthTexture, AccessFlags.Read); - passData.material = m_Material; + passData.material = m_Material.material; // Pass Textures passData.fullCoCTexture = fullCoCTexture; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/DepthOfFieldGaussianPostProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/DepthOfFieldGaussianPostProcessPass.cs index def16de768f..5f960bda1d6 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/DepthOfFieldGaussianPostProcessPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/DepthOfFieldGaussianPostProcessPass.cs @@ -10,9 +10,8 @@ internal sealed class DepthOfFieldGaussianPostProcessPass : PostProcessPass public const string k_TargetName = "CameraColorDepthOfFieldGaussian"; const int k_DownSample = 2; - Material m_Material; - Material m_MaterialCoc; - bool m_IsValid; + PostProcessMaterial m_Material; + PostProcessMaterial m_MaterialCoc; Experimental.Rendering.GraphicsFormat m_CoCFormat; @@ -21,9 +20,8 @@ public DepthOfFieldGaussianPostProcessPass(Shader shader) this.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing - 1; this.profilingSampler = URPProfilingSamplers.GaussianDepthOfField; - m_Material = PostProcessUtils.LoadShader(shader, passName, logLevel: LogType.Log); - m_MaterialCoc = PostProcessUtils.LoadShader(shader, passName, logLevel: LogType.Log); - m_IsValid = m_Material != null && m_MaterialCoc != null; + m_Material = new PostProcessMaterial(shader, passName); + m_MaterialCoc = new PostProcessMaterial(shader, passName); // Depth of Field // @@ -40,9 +38,8 @@ public DepthOfFieldGaussianPostProcessPass(Shader shader) public override void Dispose() { - CoreUtils.Destroy(m_Material); - CoreUtils.Destroy(m_MaterialCoc); - m_IsValid = false; + m_Material.Dispose(); + m_MaterialCoc.Dispose(); } private class DoFGaussianPassData @@ -68,9 +65,6 @@ private class DoFGaussianPassData }; public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) { - if (!m_IsValid) - return; - var depthOfField = volumeStack.GetComponent(); if (!depthOfField.IsActive() || depthOfField.mode.value != DepthOfFieldMode.Gaussian) return; @@ -79,6 +73,10 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer if (cameraData.isSceneViewCamera) return; + // m_MaterialCoc uses the same shader, so it is valid if m_Material is. + if (!m_Material.Validate()) + return; + UniversalResourceData resourceData = frameData.Get(); var sourceTexture = resourceData.cameraColor; @@ -117,8 +115,8 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer passData.highQualitySamplingValue = depthOfField.highQualitySampling.value; passData.enableAlphaOutput = cameraData.isAlphaOutputEnabled; - passData.material = m_Material; - passData.materialCoC = m_MaterialCoc; + passData.material = m_Material.material; + passData.materialCoC = m_MaterialCoc.material; // Inputs passData.sourceTexture = sourceTexture; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/FinalPostProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/FinalPostProcessPass.cs index 9e78cf86aea..4e2ba27457a 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/FinalPostProcessPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/FinalPostProcessPass.cs @@ -10,9 +10,8 @@ internal sealed class FinalPostProcessPass : PostProcessPass /// Blits the final post-processed image to the camera target, applying FXAA, upscaling, or format conversion as the last rendering step. static readonly ProfilingSampler k_ProfilingSampler = ProfilingSampler.Create("Blit Final Post Processing", MarkerFlags.Default); - Material m_Material; + PostProcessMaterial m_Material; Texture2D[] m_FilmGrainTextures; - bool m_IsValid; public enum FilteringOperation { @@ -34,8 +33,7 @@ public FinalPostProcessPass(Shader shader, Texture2D[] filmGrainTextures) this.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing - 1; this.profilingSampler = k_ProfilingSampler; - m_Material = PostProcessUtils.LoadShader(shader, passName); - m_IsValid = m_Material != null; + m_Material = new PostProcessMaterial(shader, passName); m_FilmGrainTextures = filmGrainTextures; // Defaults @@ -48,8 +46,7 @@ public FinalPostProcessPass(Shader shader, Texture2D[] filmGrainTextures) public override void Dispose() { - CoreUtils.Destroy(m_Material); - m_IsValid = false; + m_Material.Dispose(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -82,7 +79,7 @@ private class PostProcessingFinalBlitPassData } public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) { - if (!m_IsValid) + if (!m_Material.Validate()) return; var tonemapping = volumeStack.GetComponent(); @@ -108,7 +105,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer if (m_RenderOverlayUI) builder.UseTexture(resourceData.overlayUITexture, AccessFlags.Read); - passData.material = m_Material; + passData.material = m_Material.material; passData.cameraData = cameraData; passData.tonemapping = tonemapping; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/Fsr1UpscalePostProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/Fsr1UpscalePostProcessPass.cs index 9299750d8f2..bd8ccaa1ddd 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/Fsr1UpscalePostProcessPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/Fsr1UpscalePostProcessPass.cs @@ -8,8 +8,7 @@ internal sealed class Fsr1UpscalePostProcessPass : PostProcessPass { public const string k_TargetName = "CameraColorUpscaled"; - Material m_Material; - bool m_IsValid; + PostProcessMaterial m_Material; TextureDesc m_UpscaledDesc; @@ -18,8 +17,7 @@ public Fsr1UpscalePostProcessPass(Shader shader) this.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing - 1; this.profilingSampler = new ProfilingSampler("Blit FSR Upscaling"); - m_Material = PostProcessUtils.LoadShader(shader, passName); - m_IsValid = m_Material != null; + m_Material = new PostProcessMaterial(shader, passName); // Default PostProcessUtils.MakeCompatible(ref m_UpscaledDesc); @@ -30,8 +28,7 @@ public Fsr1UpscalePostProcessPass(Shader shader) public override void Dispose() { - CoreUtils.Destroy(m_Material); - m_IsValid = false; + m_Material.Dispose(); } private class PostProcessingFinalFSRScalePassData @@ -51,7 +48,7 @@ public void Setup(TextureDesc upscaledDesc) public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) { - if (!m_IsValid) + if (!m_Material.Validate()) return; var cameraData = frameData.Get(); @@ -70,7 +67,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer builder.SetRenderAttachment(destinationTexture, 0, AccessFlags.Write); passData.sourceTexture = sourceTexture; builder.UseTexture(sourceTexture, AccessFlags.Read); - passData.material = m_Material; + passData.material = m_Material.material; passData.fsrInputSize = new Vector2(srcDesc.width, srcDesc.height); passData.fsrOutputSize = new Vector2(dstDesc.width, dstDesc.height); passData.enableAlphaOutput = cameraData.isAlphaOutputEnabled; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/LensFlareDataDrivenPostProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/LensFlareDataDrivenPostProcessPass.cs index 09724391942..3312180e913 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/LensFlareDataDrivenPostProcessPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/LensFlareDataDrivenPostProcessPass.cs @@ -6,8 +6,7 @@ namespace UnityEngine.Rendering.Universal { internal sealed class LensFlareDataDrivenPostProcessPass : PostProcessPass { - Material m_Material; - bool m_IsValid; + PostProcessMaterial m_Material; const string k_passNameOcclusion = "Blit Lens Flare Occlusion"; @@ -16,14 +15,12 @@ public LensFlareDataDrivenPostProcessPass(Shader shader) this.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing - 1; this.profilingSampler = URPProfilingSamplers.LensFlareDataDriven; - m_Material = PostProcessUtils.LoadShader(shader, passName); - m_IsValid = m_Material != null; + m_Material = new PostProcessMaterial(shader, passName); } public override void Dispose() { - CoreUtils.Destroy(m_Material); - m_IsValid = false; + m_Material.Dispose(); } private class LensFlarePassData @@ -41,13 +38,13 @@ private class LensFlarePassData public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) { - if (!m_IsValid) - return; - var postProcessingData = frameData.Get(); if (LensFlareCommonSRP.Instance.IsEmpty() || !postProcessingData.supportDataDrivenLensFlare) return; + if (!m_Material.Validate()) + return; + var cameraData = frameData.Get(); var resourceData = frameData.Get(); @@ -55,7 +52,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer var destinationTexture = resourceData.cameraColor; // Reset keywords - m_Material.shaderKeywords = null; + m_Material.material.shaderKeywords = null; var desc = destinationTexture.GetDescriptor(renderGraph); @@ -76,7 +73,7 @@ void LensFlareDataDrivenComputeOcclusion(RenderGraph renderGraph, UniversalResou builder.UseTexture(occlusionHandle, AccessFlags.Write); passData.cameraData = cameraData; passData.viewport = cameraData.pixelRect; - passData.material = m_Material; + passData.material = m_Material.material; passData.width = (float)dstDesc.width; passData.height = (float)dstDesc.height; if (paniniProjection.IsActive()) @@ -171,7 +168,7 @@ void RenderLensFlareDataDriven(RenderGraph renderGraph, UniversalResourceData re passData.destinationTexture = destination; builder.UseTexture(destination, AccessFlags.Write); passData.cameraData = cameraData; - passData.material = m_Material; + passData.material = m_Material.material; passData.width = (float)srcDesc.width; passData.height = (float)srcDesc.height; passData.viewport.x = 0.0f; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/LensFlareScreenSpacePostProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/LensFlareScreenSpacePostProcessPass.cs index 7de25810018..dfce83de3ad 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/LensFlareScreenSpacePostProcessPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/LensFlareScreenSpacePostProcessPass.cs @@ -6,8 +6,7 @@ namespace UnityEngine.Rendering.Universal { internal sealed class LensFlareScreenSpacePostProcessPass : PostProcessPass { - Material m_Material; - bool m_IsValid; + PostProcessMaterial m_Material; // Post-processing main color-buffer texture desc. Can be different from downsampled bloom/flare textures. int m_ColorBufferWidth; @@ -19,8 +18,7 @@ public LensFlareScreenSpacePostProcessPass(Shader shader) this.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing - 1; this.profilingSampler = URPProfilingSamplers.LensFlareScreenSpace; - m_Material = PostProcessUtils.LoadShader(shader, passName); - m_IsValid = m_Material != null; + m_Material = new PostProcessMaterial(shader, passName); // Default values m_ColorBufferWidth = 1; // Unknown at pipe/pass construction time. Safe default. Avoid division by zero. @@ -30,8 +28,7 @@ public LensFlareScreenSpacePostProcessPass(Shader shader) public override void Dispose() { - CoreUtils.Destroy(m_Material); - m_IsValid = false; + m_Material.Dispose(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -59,10 +56,10 @@ private class LensFlareScreenSpacePassData public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) { - if (!m_IsValid) + if (!IsActive(volumeStack, frameData)) return; - if (!IsActive(volumeStack, frameData)) + if (!m_Material.Validate()) return; var lensFlareScreenSpace = volumeStack.GetComponent(); @@ -112,7 +109,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer passData.actualColorWidth = m_ColorBufferWidth; passData.actualColorHeight = m_ColorBufferHeight; passData.camera = cameraData.camera; - passData.material = m_Material; + passData.material = m_Material.material; passData.lensFlareScreenSpace = lensFlareScreenSpace; // NOTE: reference, assumed constant until executed. passData.downsample = downsample; passData.flareResultTmp = resultTmpTexture; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/MotionBlurPostProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/MotionBlurPostProcessPass.cs index 6aaf38a179c..7d5cbc2028c 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/MotionBlurPostProcessPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/MotionBlurPostProcessPass.cs @@ -8,28 +8,25 @@ internal sealed class MotionBlurPostProcessPass : PostProcessPass { public const string k_TargetName = "CameraColorMotionBlur"; - Material m_Material; - bool m_IsValid; + PostProcessMaterial m_Material; public MotionBlurPostProcessPass(Shader shader) { this.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing - 1; this.profilingSampler = URPProfilingSamplers.MotionBlur; - m_Material = PostProcessUtils.LoadShader(shader, passName, logLevel: LogType.Log); - m_IsValid = m_Material != null; + m_Material = new PostProcessMaterial(shader, passName); } public override void Dispose() { - CoreUtils.Destroy(m_Material); - m_IsValid = false; + m_Material.Dispose(); } private class MotionBlurPassData { internal Material material; - internal Camera camera; + internal MotionVectorsPersistentData motionData; internal TextureHandle sourceTexture; internal int passIndex; internal float intensity; @@ -39,9 +36,6 @@ private class MotionBlurPassData } public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) { - if(!m_IsValid) - return; - // Disable MotionBlur in EditMode, so that editing remains clear and readable. // NOTE: HDRP does the same via CoreUtils::AreAnimatedMaterialsEnabled(). // Disable MotionBlurMode.CameraAndObjects on renderers that do not support motion vectors @@ -56,6 +50,9 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer if (cameraData.isSceneViewCamera) return; + if (!m_Material.Validate()) + return; + UniversalResourceData resourceData = frameData.Get(); TextureHandle motionVectorColor = resourceData.motionVectorColor; @@ -97,9 +94,10 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer Debug.Assert(cameraDepthTexture.IsValid(), "Camera depth texture is invalid. Per-camera motion blur requires a depth texture."); builder.UseTexture(cameraDepthTexture, AccessFlags.Read); - passData.material = m_Material; + passData.material = m_Material.material; passData.passIndex = passIndex; - passData.camera = cameraData.camera; + var additionalCameraData = cameraData.additionalCameraData; + passData.motionData = additionalCameraData != null ? additionalCameraData.motionVectorsPersistentData : null; passData.enableAlphaOutput = cameraData.isAlphaOutputEnabled; passData.intensity = motionBlur.intensity.value; passData.clamp = motionBlur.clamp.value; @@ -109,7 +107,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer var cmd = context.cmd; RTHandle sourceTextureHdl = data.sourceTexture; - UpdateMotionBlurMatrices(data.material, data.camera, data.xr); + UpdateMotionBlurMatrices(data.material, data.motionData, data.xr); var sourceSize = PostProcessUtils.CalcShaderSourceSize(sourceTextureHdl); data.material.SetVector(ShaderConstants._SourceSize, sourceSize); @@ -126,13 +124,8 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer } [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void UpdateMotionBlurMatrices(Material material, Camera camera, Experimental.Rendering.XRPass xr) + public static void UpdateMotionBlurMatrices(Material material, MotionVectorsPersistentData motionData, Experimental.Rendering.XRPass xr) { - MotionVectorsPersistentData motionData = null; - - if(camera.TryGetComponent(out var additionalCameraData)) - motionData = additionalCameraData.motionVectorsPersistentData; - if (motionData == null) return; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/PaniniProjectionPostProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/PaniniProjectionPostProcessPass.cs index a8a4f77a60a..28928f051f4 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/PaniniProjectionPostProcessPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/PaniniProjectionPostProcessPass.cs @@ -8,22 +8,19 @@ internal sealed class PaniniProjectionPostProcessPass : PostProcessPass { public const string k_TargetName = "CameraColorPaniniProjection"; - Material m_Material; - bool m_IsValid; + PostProcessMaterial m_Material; public PaniniProjectionPostProcessPass(Shader shader) { this.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing - 1; this.profilingSampler = URPProfilingSamplers.PaniniProjection; - m_Material = PostProcessUtils.LoadShader(shader, passName, logLevel: LogType.Log); - m_IsValid = m_Material != null; + m_Material = new PostProcessMaterial(shader, passName); } public override void Dispose() { - CoreUtils.Destroy(m_Material); - m_IsValid = false; + m_Material.Dispose(); } private class PaniniProjectionPassData @@ -35,9 +32,6 @@ private class PaniniProjectionPassData } public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) { - if(!m_IsValid) - return; - var paniniProjection = volumeStack.GetComponent(); if(!paniniProjection.IsActive()) @@ -47,6 +41,9 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer if (cameraData.isSceneViewCamera) return; + if (!m_Material.Validate()) + return; + UniversalResourceData resourceData = frameData.Get(); var sourceTexture = resourceData.cameraColor; var destinationTexture = PostProcessUtils.CreateCompatibleTexture(renderGraph, sourceTexture, k_TargetName, true, FilterMode.Bilinear); @@ -72,7 +69,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer builder.SetRenderAttachment(destinationTexture, 0, AccessFlags.Write); passData.sourceTexture = sourceTexture; builder.UseTexture(sourceTexture, AccessFlags.Read); - passData.material = m_Material; + passData.material = m_Material.material; passData.paniniParams = new Vector4(viewExtents.x, viewExtents.y, paniniD, paniniS); passData.isPaniniGeneric = 1f - Mathf.Abs(paniniD) > float.Epsilon; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/ScalingSetupPostProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/ScalingSetupPostProcessPass.cs index 64801d7cf16..1f052c11aa7 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/ScalingSetupPostProcessPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/ScalingSetupPostProcessPass.cs @@ -8,8 +8,7 @@ internal sealed class ScalingSetupPostProcessPass : PostProcessPass { public const string k_TargetName = "SetupUpscaling"; - Material m_Material; - bool m_IsValid; + PostProcessMaterial m_Material; HDROutputUtils.Operation m_HdrOperations; @@ -18,8 +17,7 @@ public ScalingSetupPostProcessPass(Shader shader) this.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing - 1; this.profilingSampler = new ProfilingSampler("Setup Final Post Processing"); - m_Material = PostProcessUtils.LoadShader(shader, passName); - m_IsValid = m_Material != null; + m_Material = new PostProcessMaterial(shader, passName); // Defaults m_HdrOperations = HDROutputUtils.Operation.None; // HDR disabled. @@ -27,8 +25,7 @@ public ScalingSetupPostProcessPass(Shader shader) public override void Dispose() { - CoreUtils.Destroy(m_Material); - m_IsValid = false; + m_Material.Dispose(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -50,7 +47,7 @@ private class PostProcessingFinalSetupPassData public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) { - if (!m_IsValid) + if (!m_Material.Validate()) return; var tonemapping = volumeStack.GetComponent(); @@ -81,7 +78,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer passData.sourceTexture = sourceTexture; builder.UseTexture(sourceTexture, AccessFlags.Read); - passData.material = m_Material; + passData.material = m_Material.material; passData.cameraData = cameraData; passData.tonemapping = tonemapping; passData.hdrOperations = m_HdrOperations; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/SmaaPostProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/SmaaPostProcessPass.cs index 4a27b13f14a..b00353dc7b8 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/SmaaPostProcessPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/SmaaPostProcessPass.cs @@ -9,8 +9,7 @@ internal sealed class SmaaPostProcessPass : PostProcessPass { public const string k_TargetName = "CameraColorSMAA"; - Material m_Material; - bool m_IsValid; + PostProcessMaterial m_Material; // Static resource textures for SMAA technique Texture2D m_AreaTexture; @@ -26,8 +25,7 @@ public SmaaPostProcessPass(Shader shader, Texture2D smaaAreaTexture, Texture2D s this.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing - 1; this.profilingSampler = URPProfilingSamplers.SMAANeighborhoodBlend; - m_Material = PostProcessUtils.LoadShader(shader, passName); - m_IsValid = m_Material != null; + m_Material = new PostProcessMaterial(shader, passName); m_AreaTexture = smaaAreaTexture; m_SearchTexture = smaaSearchTexture; @@ -42,8 +40,7 @@ public SmaaPostProcessPass(Shader shader, Texture2D smaaAreaTexture, Texture2D s public override void Dispose() { - CoreUtils.Destroy(m_Material); - m_IsValid = false; + m_Material.Dispose(); } private class SMAASetupPassData @@ -67,13 +64,13 @@ private class SMAAPassData public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) { - if (!m_IsValid) - return; - var cameraData = frameData.Get(); if (cameraData.antialiasing != AntialiasingMode.SubpixelMorphologicalAntiAliasing) return; + if (!m_Material.Validate()) + return; + var resourceData = frameData.Get(); var sourceTexture = resourceData.cameraColor; @@ -109,7 +106,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer passData.stencilMask = (float)kStencilBit; passData.antialiasingQuality = cameraData.antialiasingQuality; - passData.material = m_Material; + passData.material = m_Material.material; builder.SetRenderAttachment(edgeTexture, 0, AccessFlags.Write); builder.SetRenderAttachmentDepth(edgeTextureStencil, AccessFlags.Write); @@ -138,7 +135,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer builder.SetRenderAttachmentDepth(edgeTextureStencil, AccessFlags.Read); passData.sourceTexture = edgeTexture; builder.UseTexture(edgeTexture, AccessFlags.Read); - passData.material = m_Material; + passData.material = m_Material.material; builder.SetRenderFunc(static (SMAAPassData data, RasterGraphContext context) => { @@ -159,7 +156,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer builder.UseTexture(sourceTexture, AccessFlags.Read); passData.blendTexture = blendTexture; builder.UseTexture(blendTexture, AccessFlags.Read); - passData.material = m_Material; + passData.material = m_Material.material; builder.SetRenderFunc(static (SMAAPassData data, RasterGraphContext context) => { diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/StopNanPostProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/StopNanPostProcessPass.cs index bd653d285f0..5238899826e 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/StopNanPostProcessPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/StopNanPostProcessPass.cs @@ -8,22 +8,19 @@ internal sealed class StopNanPostProcessPass : PostProcessPass { public const string k_TargetName = "CameraColorStopNaNs"; - Material m_Material; - bool m_IsValid; + PostProcessMaterial m_Material; public StopNanPostProcessPass(Shader shader) { this.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing - 1; this.profilingSampler = URPProfilingSamplers.StopNaNs; - m_Material = PostProcessUtils.LoadShader(shader, passName); - m_IsValid = m_Material != null; + m_Material = new PostProcessMaterial(shader, passName); } public override void Dispose() { - CoreUtils.Destroy(m_Material); - m_IsValid = false; + m_Material.Dispose(); } private class StopNaNsPassData @@ -33,13 +30,13 @@ private class StopNaNsPassData } public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) { - if (!m_IsValid) - return; - var cameraData = frameData.Get(); if (!cameraData.isStopNaNEnabled) return; + if (!m_Material.Validate()) + return; + var resourceData = frameData.Get(); var sourceTexture = resourceData.cameraColor; var destinationTexture = PostProcessUtils.CreateCompatibleTexture(renderGraph, sourceTexture, k_TargetName, true, FilterMode.Bilinear); @@ -50,7 +47,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer builder.SetRenderAttachment(destinationTexture, 0, AccessFlags.ReadWrite); passData.sourceTexture = sourceTexture; builder.UseTexture(sourceTexture, AccessFlags.Read); - passData.stopNaN = m_Material; + passData.stopNaN = m_Material.material; builder.SetRenderFunc(static (StopNaNsPassData data, RasterGraphContext context) => { var cmd = context.cmd; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/TemporalAntiAliasingPostProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/TemporalAntiAliasingPostProcessPass.cs index 9053ce1c004..ff1a2b7f79a 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/TemporalAntiAliasingPostProcessPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/TemporalAntiAliasingPostProcessPass.cs @@ -8,8 +8,7 @@ internal sealed class TemporalAntiAliasingPostProcessPass : PostProcessPass { public const string k_TargetName = "CameraColorTemporalAA"; - Material m_Material; - bool m_IsValid; + PostProcessMaterial m_Material; uint m_WarnCounter; public TemporalAntiAliasingPostProcessPass(Shader shader) @@ -17,23 +16,18 @@ public TemporalAntiAliasingPostProcessPass(Shader shader) this.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing - 1; this.profilingSampler = null; - m_Material = PostProcessUtils.LoadShader(shader, passName); - m_IsValid = m_Material != null; + m_Material = new PostProcessMaterial(shader, passName); m_WarnCounter = 0; } public override void Dispose() { - CoreUtils.Destroy(m_Material); - m_IsValid = false; + m_Material.Dispose(); } public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) { - if (!m_IsValid) - return; - UniversalCameraData cameraData = frameData.Get(); var postProcessingData = frameData.Get(); if (postProcessingData.activeUpscaler != null && postProcessingData.activeUpscaler.isTemporal) @@ -50,6 +44,9 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer return; } + if (!m_Material.Validate()) + return; + UniversalResourceData resourceData = frameData.Get(); var sourceTexture = resourceData.cameraColor; @@ -60,7 +57,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer Debug.Assert(motionVectors.IsValid(), "MotionVectors are invalid. TAA requires a motion vector texture."); - TemporalAA.Render(renderGraph, m_Material, cameraData, sourceTexture, in cameraDepth, in motionVectors, destinationTexture); + TemporalAA.Render(renderGraph, m_Material.material, cameraData, sourceTexture, in cameraDepth, in motionVectors, destinationTexture); resourceData.cameraColor = destinationTexture; } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/UberPostProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/UberPostProcessPass.cs index dbd24496393..366e7d6ee8e 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/UberPostProcessPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/UberPostProcessPass.cs @@ -7,7 +7,7 @@ namespace UnityEngine.Rendering.Universal { internal sealed class UberPostProcessPass : PostProcessPass { - Material m_Material; + PostProcessMaterial m_Material; Texture2D[] m_FilmGrainTextures; public enum FilteringOperation @@ -20,18 +20,17 @@ public enum FilteringOperation RTHandle m_UserLut; FilteringOperation m_FilteringOperation; HDROutputUtils.Operation m_HdrOperations; - bool m_IsValid; bool m_IsFinalPass; bool m_RequireSRGBConversionBlit; bool m_RenderOverlayUI; + float? m_BloomIntensityOverride; public UberPostProcessPass(Shader shader, Texture2D[] filmGrainTextures) { this.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing - 1; this.profilingSampler = URPProfilingSamplers.UberPostProcess; - m_Material = PostProcessUtils.LoadShader(shader, passName); - m_IsValid = m_Material != null; + m_Material = new PostProcessMaterial(shader, passName); m_FilmGrainTextures = filmGrainTextures; // Defaults @@ -41,13 +40,13 @@ public UberPostProcessPass(Shader shader, Texture2D[] filmGrainTextures) m_RequireSRGBConversionBlit = false; // sRGB conversion is typically automatic based on format. m_IsFinalPass = false; // Assume other passes. m_RenderOverlayUI = false; // HDR disabled. HDR only. + m_BloomIntensityOverride = null; // Bloom volume intensity. } public override void Dispose() { m_UserLut?.Release(); - CoreUtils.Destroy(m_Material); - m_IsValid = false; + m_Material.Dispose(); } public void Setup(Texture ditherTexture, @@ -55,7 +54,8 @@ public void Setup(Texture ditherTexture, HDROutputUtils.Operation hdrOperations, bool requireSRGBConversionBlit, bool isFinalPass, - bool renderOverlayUI) + bool renderOverlayUI, + float? bloomIntensityOverride = null) { m_DitherTexture = ditherTexture; m_FilteringOperation = filteringOperation; @@ -63,6 +63,7 @@ public void Setup(Texture ditherTexture, m_RequireSRGBConversionBlit = requireSRGBConversionBlit; m_IsFinalPass = isFinalPass; m_RenderOverlayUI = renderOverlayUI; + m_BloomIntensityOverride = bloomIntensityOverride; } private class UberPostPassData @@ -98,7 +99,7 @@ private class UberPostPassData /// public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) { - if(!m_IsValid) + if (!m_Material.Validate()) return; var colorLookup = volumeStack.GetComponent(); @@ -208,7 +209,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer if(bloomTexture.IsValid()) builder.UseTexture(bloomTexture, AccessFlags.Read); - passData.material = m_Material; + passData.material = m_Material.material; passData.cameraData = cameraData; passData.useFastSRGBLinearConversion = postProcessingData.useFastSRGBLinearConversion; passData.requireSRGBConversionBlit = m_RequireSRGBConversionBlit; @@ -220,7 +221,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer passData.isHdrGrading = postProcessingData.gradingMode == ColorGradingMode.HighDynamicRange; passData.lut.Setup(colorAdjustments, colorLookup, postProcessingData.lutSize, internalColorLut, userColorLut); - passData.bloom.Setup(bloom, in srcDesc, bloomTexture); + passData.bloom.Setup(bloom, in srcDesc, bloomTexture, m_BloomIntensityOverride); passData.lensDistortion.Setup(lensDistortion, cameraData.isSceneViewCamera); passData.chromaticAberration.Setup(chromaticAberration); passData.vignette.Setup(vignette, srcDesc.width, srcDesc.height, cameraData.xr); @@ -411,10 +412,12 @@ public bool IsActive() } [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Setup(Bloom bloom, in TextureDesc srcDesc, TextureHandle activeBloomTexture) + public void Setup(Bloom bloom, in TextureDesc srcDesc, TextureHandle activeBloomTexture, float? intensityOverride = null) { this.activeBloomTexture = activeBloomTexture; CalcBloomParams(bloom, in srcDesc, out bloomParams, out highQualityFiltering, out dirtTexture, out dirtScaleOffset, out dirtIntensity); + if (intensityOverride.HasValue) + bloomParams.x = intensityOverride.Value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/UpscalerPostProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/UpscalerPostProcessPass.cs index cec9118757d..391549c1204 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/UpscalerPostProcessPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/UpscalerPostProcessPass.cs @@ -11,10 +11,11 @@ internal sealed class UpscalerPostProcessPass : PostProcessPass public const string k_UpscaledColorTargetName = "CameraColorUpscaled"; Texture2D[] m_BlueNoise16LTex; - Material m_UpscalerReactiveMaskMaterial; + PostProcessMaterial m_UpscalerReactiveMaskMaterial; bool m_IsValid; bool m_WarnedHardwareDrsTemporalUnsupported; + bool m_WarnedMsaaAndTemporalUpscalerNotCompatible; bool m_WarnedMissingMotionData; bool m_WarnedMissingOpaqueTexture; bool m_WarnedOpaqueDownsamplingNotCompatible; @@ -25,24 +26,20 @@ public UpscalerPostProcessPass(Shader reactiveMaskShader, Texture2D[] blueNoise1 this.profilingSampler = null; // Use default name m_BlueNoise16LTex = blueNoise16LTex; - m_UpscalerReactiveMaskMaterial = PostProcessUtils.LoadShader(reactiveMaskShader, passName, logLevel: LogType.Log); + m_UpscalerReactiveMaskMaterial = new PostProcessMaterial(reactiveMaskShader, passName); - m_IsValid = m_BlueNoise16LTex != null && m_BlueNoise16LTex.Length > 0 - && m_UpscalerReactiveMaskMaterial != null; + m_IsValid = m_BlueNoise16LTex != null && m_BlueNoise16LTex.Length > 0; } public override void Dispose() { - CoreUtils.Destroy(m_UpscalerReactiveMaskMaterial); + m_UpscalerReactiveMaskMaterial.Dispose(); m_IsValid = false; } public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) { - if (!m_IsValid) - return; - UniversalPostProcessingData postProcessingData = frameData.Get(); if (postProcessingData.activeUpscaler == null) return; @@ -75,10 +72,26 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer if (Debug.isDebugBuild) m_WarnedHardwareDrsTemporalUnsupported = false; + if (!m_IsValid || !m_UpscalerReactiveMaskMaterial.Validate()) + return; + UniversalResourceData resourceData = frameData.Get(); var sourceTexture = resourceData.cameraColor; var srcDesc = sourceTexture.GetDescriptor(renderGraph); + // E.g., MSAA and DLSS are incompatible. + if ((srcDesc.msaaSamples != MSAASamples.None || resourceData.cameraDepth.GetDescriptor(renderGraph).msaaSamples != MSAASamples.None) && postProcessingData.activeUpscaler.isTemporal) + { + if (Debug.isDebugBuild && !m_WarnedMsaaAndTemporalUpscalerNotCompatible) + { + m_WarnedMsaaAndTemporalUpscalerNotCompatible = true; + Debug.LogWarning($"MSAA is not compatible with temporal upscaler '{postProcessingData.activeUpscaler.name}'. Turn off MSAA in the current RP asset."); + } + return; + } + if (Debug.isDebugBuild) + m_WarnedMsaaAndTemporalUpscalerNotCompatible = false; + // Create a context item containing upscaling inputs UpscalingIO io = frameData.Create(); io.cameraColor = sourceTexture; @@ -112,7 +125,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer // (preUpscaleResolution) is a sub-rect of it; without DRS they're equal. Upscalers allocate history at this. io.maxPreUpscaleResolution = new Vector2Int(cameraData.cameraTargetDescriptor.width, cameraData.cameraTargetDescriptor.height); - cameraData.camera.TryGetComponent(out var additionalCameraData); + var additionalCameraData = cameraData.additionalCameraData; MotionVectorsPersistentData motionData = additionalCameraData != null ? additionalCameraData.motionVectorsPersistentData : null; if (motionData == null) // Per-camera motion data is required for upscaling (camera matrices, positions, previous-frame sizes). { @@ -216,7 +229,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer { if (resourceData.cameraOpaqueTexture.IsValid()) { - io.reactiveMask = UpscalerReactiveMaskPass(renderGraph, frameData, m_UpscalerReactiveMaskMaterial, upscaler.reactiveMaskSource, upscalerOptions, io.enableTexArray); + io.reactiveMask = UpscalerReactiveMaskPass(renderGraph, frameData, m_UpscalerReactiveMaskMaterial.material, upscaler.reactiveMaskSource, upscalerOptions, io.enableTexArray); m_WarnedMissingOpaqueTexture = false; } else if (Debug.isDebugBuild && !m_WarnedMissingOpaqueTexture) @@ -286,9 +299,9 @@ static internal void UpdateCameraResolution(RenderGraph renderGraph, ContextCont // _ScreenSize lives in the centralized global shader variables, potentially stored in a global constant buffer. IGlobalShaderVariablesCommonUploader vars; if (data.shaderData != null) - vars = data.shaderData.Get(); + vars = data.shaderData.GetGlobal(); else - vars = data.shaderData2D.Get(); + vars = data.shaderData2D.GetGlobal(); vars._ScreenSize = new Vector4( data.newCameraTargetSize.x, @@ -296,7 +309,7 @@ static internal void UpdateCameraResolution(RenderGraph renderGraph, ContextCont 1.0f / data.newCameraTargetSize.x, 1.0f / data.newCameraTargetSize.y ); - vars.PushGlobal(ctx.cmd); + vars.Push(ctx.cmd); }); } } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/RenderObjectsPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/RenderObjectsPass.cs index b6c7430adea..02362045137 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/RenderObjectsPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/RenderObjectsPass.cs @@ -212,6 +212,8 @@ private static void ExecutePass(PassData passData, RasterCommandBuffer cmd, Rend } } + RenderingUtils.SetAlphaToMaskAvailable(cmd, passData.alphaToMaskAvailable); + var activeDebugHandler = GetActiveDebugHandler(passData.cameraData); if (activeDebugHandler != null) { @@ -222,6 +224,9 @@ private static void ExecutePass(PassData passData, RasterCommandBuffer cmd, Rend cmd.DrawRendererList(rendererList); } + if (passData.alphaToMaskAvailable) + RenderingUtils.SetAlphaToMaskAvailable(cmd, false); + if (passData.cameraSettings.overrideCamera && passData.cameraSettings.restoreCamera && !passData.cameraData.xr.enabled) { RenderingUtils.SetViewAndProjectionMatrices(cmd, passData.cameraData.GetViewMatrix(), GL.GetGPUProjectionMatrix(passData.cameraData.GetProjectionMatrix(0), isYFlipped), false); @@ -244,6 +249,7 @@ private class PassData internal bool depthInputAttachment; internal bool isActiveTargetBackBuffer; + internal bool alphaToMaskAvailable; } private void InitPassData(UniversalCameraData cameraData, ref PassData passData, bool isActiveTargetBackBuffer = false) @@ -295,6 +301,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer InitPassData(cameraData, ref passData, resourceData.isActiveTargetBackBuffer); passData.color = resourceData.activeColorTexture; + passData.alphaToMaskAvailable = renderQueueType == RenderQueueType.Opaque && renderGraph.GetRenderTargetInfo(resourceData.activeColorTexture).msaaSamples > 1; builder.SetRenderAttachment(resourceData.activeColorTexture, 0, AccessFlags.Write); if (resourceData.activeDepthTexture.IsValid()) diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/ScreenSpaceAmbientOcclusion/GTAOPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/ScreenSpaceAmbientOcclusion/GTAOPass.cs index d255ba55e97..a988a935f13 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/ScreenSpaceAmbientOcclusion/GTAOPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/ScreenSpaceAmbientOcclusion/GTAOPass.cs @@ -68,6 +68,7 @@ internal static class ShaderIDs public static readonly int _GTAOPrefilterSourceSize = Shader.PropertyToID("_GTAOPrefilterSourceSize"); public static readonly int _GTAOPrefilterFalloff = Shader.PropertyToID("_GTAOPrefilterFalloff"); public static readonly int _GTAOPrefilterOrthoRemap = Shader.PropertyToID("_GTAOPrefilterOrthoRemap"); + public static readonly int _ZBufferParams = Shader.PropertyToID("_ZBufferParams"); public static readonly int _GTAOPrefilterDownsample = Shader.PropertyToID("_GTAOPrefilterDownsample"); public static readonly int _GTAOPrefilterMipCount = Shader.PropertyToID("_GTAOPrefilterMipCount"); } @@ -219,6 +220,7 @@ private class GTAODepthPrefilterPassData public Vector4 prefilterSourceSize; // xy = source depth allocation size, zw = its reciprocal public Vector4 prefilterFalloff; // x = falloff multiplier, y = falloff addend, z = max storable depth public Vector4 orthoRemap; // xy = orthographic eye depth remap, x + y * rawDepth + public Vector4 zBufferParams; // the camera's _ZBufferParams public Vector4[] depthPyramidMipLevelOffsets = new Vector4[SSAOUtils.k_GTAODepthPyramidMipCount]; // xy = where each MIP sits in the packed pyramid public int downsample; public int mipCount; @@ -739,6 +741,8 @@ private void RecordDepthPrefilterPass(RenderGraph renderGraph, TextureHandle dep float farPlane = cameraData.camera.farClipPlane; passData.orthoRemap = SystemInfo.usesReversedZBuffer ? new Vector4(farPlane, nearPlane - farPlane, 0.0f, 0.0f) : new Vector4(nearPlane, farPlane - nearPlane, 0.0f, 0.0f); + passData.zBufferParams = RenderingUtils.ComputeZBufferParams(cameraData.camera); + passData.disableTexture2DArrayKeyword = m_DepthPrefilterState.disableTexture2DArray; passData.pyramidIsArray = pyramidIsArray; passData.downsample = m_CurrentSettings.Downsample ? 2 : 1; @@ -774,6 +778,7 @@ private void RecordDepthPrefilterPass(RenderGraph renderGraph, TextureHandle dep cmd.SetComputeVectorParam(cs, ShaderIDs._GTAOPrefilterSourceSize, data.prefilterSourceSize); cmd.SetComputeVectorParam(cs, ShaderIDs._GTAOPrefilterFalloff, data.prefilterFalloff); cmd.SetComputeVectorParam(cs, ShaderIDs._GTAOPrefilterOrthoRemap, data.orthoRemap); + cmd.SetComputeVectorParam(cs, ShaderIDs._ZBufferParams, data.zBufferParams); cmd.SetComputeVectorArrayParam(cs, SSAOUtils.ShaderConstants._GTAODepthPyramidMipLevelOffsets, data.depthPyramidMipLevelOffsets); cmd.SetComputeIntParam(cs, ShaderIDs._GTAOPrefilterDownsample, data.downsample); cmd.SetComputeIntParam(cs, ShaderIDs._GTAOPrefilterMipCount, data.mipCount); diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/ScreenSpaceAmbientOcclusion/SSAOUtils.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/ScreenSpaceAmbientOcclusion/SSAOUtils.cs index 4bb40e6233b..c6f0953ccba 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/ScreenSpaceAmbientOcclusion/SSAOUtils.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/ScreenSpaceAmbientOcclusion/SSAOUtils.cs @@ -126,7 +126,7 @@ internal SSAOMaterialParams(ScreenSpaceAmbientOcclusionSettings settings, Univer if (isGTAOMode) { - // GTAO always uses depth normals + // GTAO always uses depth normals, which ShaderScriptableStripper relies on sourceDepthNormals = true; this.useDepthPyramid = useDepthPyramid; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/ScriptableRenderPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/ScriptableRenderPass.cs index 840e1fd3dbf..1c799496851 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/ScriptableRenderPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/ScriptableRenderPass.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.ComponentModel; using Unity.Collections; -using Unity.Scripting.LifecycleManagement; using UnityEngine.Scripting.APIUpdating; using UnityEngine.Experimental.Rendering; using UnityEngine.Rendering.RenderGraphModule; @@ -175,7 +174,6 @@ internal enum FramebufferFetchEvent internal static class RenderPassEventsEnumValues { // we cache the values in this array at construction time to avoid runtime allocations, which we would cause if we accessed valuesInternal directly - [NoAutoStaticsCleanup] // Clearing the array is not necessary when entering play mode because it's reflection data. public static readonly int[] values; static RenderPassEventsEnumValues() diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/XRDepthMotionPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/XRDepthMotionPass.cs index 210b9350ea3..9d3801af6f3 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/XRDepthMotionPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/XRDepthMotionPass.cs @@ -13,6 +13,7 @@ public class XRDepthMotionPass : ScriptableRenderPass public const string k_MotionOnlyShaderTagIdName = "XRMotionVectors"; private static readonly int k_XRDepthTextureNameID = Shader.PropertyToID("_XRDepthTexture"); private LocalKeyword m_SubsampleDepthKeyword; + private LocalKeyword m_QuadViewInnerDepthKeyword; private static readonly ShaderTagId k_MotionOnlyShaderTagId = new ShaderTagId(k_MotionOnlyShaderTagIdName); private static readonly int k_SpaceWarpNDCModifier = Shader.PropertyToID("_SpaceWarpNDCModifier"); // Stencil bit the object-motion passes use as the "has object motion" marker. Kept in sync with @@ -20,6 +21,7 @@ public class XRDepthMotionPass : ScriptableRenderPass private const uint k_ObjectMotionMarkerMask = 0x1; private static readonly int k_XRDepthTextureUVScale = Shader.PropertyToID("_XRDepthTextureUVScale"); private static readonly int k_QuadViewMVTex = Shader.PropertyToID("_QuadViewMVTex"); + private static readonly int k_QuadViewOuterDepthTex = Shader.PropertyToID("_QuadViewOuterDepthTex"); private static readonly int k_QuadViewUVScales = Shader.PropertyToID("_QuadViewUVScales"); private static readonly int k_QuadViewUVOffsets = Shader.PropertyToID("_QuadViewUVOffsets"); private static readonly int k_QuadViewPrevUVOffsets = Shader.PropertyToID("_QuadViewPrevUVOffsets"); @@ -56,6 +58,7 @@ public XRDepthMotionPass(RenderPassEvent evt, Shader xrMotionVector, LayerMask t m_XRMotionVectorDepth = null; m_transparentlayerMask = transparentLayerMask; m_SubsampleDepthKeyword = new LocalKeyword(xrMotionVector, "_SUBSAMPLE_DEPTH"); + m_QuadViewInnerDepthKeyword = new LocalKeyword(xrMotionVector, "_QUADVIEW_INNER_DEPTH"); } private const int k_XRViewCountPerPass = 2; @@ -77,6 +80,14 @@ private class ReprojectionPassData { internal TextureHandle outerMVSrc; internal TextureHandle outerDepthSrc; + internal TextureHandle innerDepthSrc; + internal bool useInnerDepth; + internal Vector4 innerDepthUVScale; + internal Vector4 uvScales; + internal Vector4 uvOffsets; + internal Vector4 prevUVOffsets; + internal Matrix4x4[] previousViewProjectionStereo; + internal Matrix4x4[] viewProjectionStereo; } /// View projection data @@ -278,7 +289,7 @@ internal void Render(RenderGraph renderGraph, ContextContainer frameData) // Skipped under TPS because reprojection does not yet write the stencil bits needed to exclude transparents from temporal reuse. if (m_QuadViewOuterMV != null && !cameraData.xr.isTemporalPixelSynthesisActive) { - RecordReprojectionPass(renderGraph, cameraData); + RecordReprojectionPass(renderGraph, cameraData, resourceData); m_PreviousQuadViewUVOffsets = cameraData.xr.uvOffsets; return; } @@ -431,7 +442,7 @@ internal void Render(RenderGraph renderGraph, ContextContainer frameData) } } - private void RecordReprojectionPass(RenderGraph renderGraph, UniversalCameraData cameraData) + private void RecordReprojectionPass(RenderGraph renderGraph, UniversalCameraData cameraData, UniversalResourceData resourceData) { // The outer and inner cameras run in separate RecordAndExecuteRenderGraph executions so TextureHandles cannot be shared across them. // Import fresh read-only handles for the outer MV within the inner pass execution. @@ -441,11 +452,6 @@ private void RecordReprojectionPass(RenderGraph renderGraph, UniversalCameraData outerDepthImportInfo.format = cameraData.xr.motionVectorRenderTargetDesc.depthStencilFormat; var outerDepthHandle = renderGraph.ImportTexture(m_QuadViewOuterMV, outerDepthImportInfo, importParams); - var uvScales = cameraData.xr.uvScales; - var uvOffsets = cameraData.xr.uvOffsets; - // Fall back to the current offset if we don't have the immediately previous frame. - var prevUVOffsets = float.IsNaN(m_PreviousQuadViewUVOffsets.x) ? uvOffsets : m_PreviousQuadViewUVOffsets; - using (var builder = renderGraph.AddRasterRenderPass( "XR MotionVector QuadView Reprojection", out var passData, base.profilingSampler)) { @@ -457,14 +463,44 @@ private void RecordReprojectionPass(RenderGraph renderGraph, UniversalCameraData passData.outerMVSrc = outerMVHandle; passData.outerDepthSrc = outerDepthHandle; + passData.uvScales = cameraData.xr.uvScales; + passData.uvOffsets = cameraData.xr.uvOffsets; + // Fall back to the current offset if we don't have the immediately previous frame. + passData.prevUVOffsets = float.IsNaN(m_PreviousQuadViewUVOffsets.x) ? passData.uvOffsets : m_PreviousQuadViewUVOffsets; + + // Inner depth rejects outer MVs hidden by split-culled occluders, which only go missing when the outer MV pass reuses copied depth + passData.useInnerDepth = cameraData.xr.copyDepth; + if (passData.useInnerDepth) + { + builder.UseTexture(resourceData.backBufferDepth, AccessFlags.Read); + passData.innerDepthSrc = resourceData.backBufferDepth; + + var innerDepthInfo = renderGraph.GetRenderTargetInfo(resourceData.backBufferDepth); + passData.innerDepthUVScale = new Vector4(cameraData.pixelRect.width / innerDepthInfo.width, cameraData.pixelRect.height / innerDepthInfo.height, 0f, 0f); + + // Inner view matrices for the camera-motion fallback; the globals may hold outer pass or MotionVectors.cs values + var viewStartIndex = cameraData.xr.viewCount * cameraData.xr.multipassId; + Array.Copy(m_PreviousViewProjection, viewStartIndex, m_PreviousStagingMatrixArray, 0, cameraData.xr.viewCount); + passData.previousViewProjectionStereo = m_PreviousStagingMatrixArray; + Array.Copy(m_ViewProjection, viewStartIndex, m_StagingMatrixArray, 0, cameraData.xr.viewCount); + passData.viewProjectionStereo = m_StagingMatrixArray; + } builder.SetRenderFunc((ReprojectionPassData data, RasterGraphContext context) => { + context.cmd.SetKeyword(m_XRMotionVectorMaterial, m_QuadViewInnerDepthKeyword, data.useInnerDepth); + if (data.useInnerDepth) + { + context.cmd.SetGlobalMatrixArray(ShaderPropertyId.previousViewProjectionNoJitterStereo, data.previousViewProjectionStereo); + context.cmd.SetGlobalMatrixArray(ShaderPropertyId.viewProjectionNoJitterStereo, data.viewProjectionStereo); + context.cmd.SetGlobalTexture(k_XRDepthTextureNameID, data.innerDepthSrc, RenderTextureSubElement.Depth); + context.cmd.SetGlobalVector(k_XRDepthTextureUVScale, data.innerDepthUVScale); + } context.cmd.SetGlobalTexture(k_QuadViewMVTex, data.outerMVSrc); - context.cmd.SetGlobalTexture(k_XRDepthTextureNameID, data.outerDepthSrc, RenderTextureSubElement.Depth); - context.cmd.SetGlobalVector(k_QuadViewUVScales, uvScales); - context.cmd.SetGlobalVector(k_QuadViewUVOffsets, uvOffsets); - context.cmd.SetGlobalVector(k_QuadViewPrevUVOffsets, prevUVOffsets); + context.cmd.SetGlobalTexture(k_QuadViewOuterDepthTex, data.outerDepthSrc, RenderTextureSubElement.Depth); + context.cmd.SetGlobalVector(k_QuadViewUVScales, data.uvScales); + context.cmd.SetGlobalVector(k_QuadViewUVOffsets, data.uvOffsets); + context.cmd.SetGlobalVector(k_QuadViewPrevUVOffsets, data.prevUVOffsets); context.cmd.DrawProcedural(Matrix4x4.identity, m_XRMotionVectorMaterial, shaderPass: 2, MeshTopology.Triangles, 3, 1); }); diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/PostProcess.cs b/Packages/com.unity.render-pipelines.universal/Runtime/PostProcess.cs index e0edb712030..298d4ebb8f9 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/PostProcess.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/PostProcess.cs @@ -174,30 +174,37 @@ public void RenderPostProcessing(RenderGraph renderGraph, ContextContainer frame m_PaniniProjectionPass.RecordRenderGraph(renderGraph, frameData); // Bloom & Screen Space Lens Flares + float? bloomIntensityOverride = null; { var volumeStack = VolumeManager.instance.stack; var bloom = volumeStack.GetComponent(); var lensFlareScreenSpace = volumeStack.GetComponent(); - // NOTE: Even if bloom is not active we might need to run it for the texture if the lensFlareScreenSpace pass is active. - if (!bloom.IsActive() && LensFlareScreenSpacePostProcessPass.IsActive(volumeStack, frameData)) - bloom.intensity = lensFlareScreenSpace.intensity; // Set Bloom Active to true. + // Screen space lens flares use a bloom mip as their source, so bloom runs as their dependency and is composited at the flare intensity. + bool bloomRequiredByFlares = !bloom.IsActive() && LensFlareScreenSpacePostProcessPass.IsActive(volumeStack, frameData); + if (bloomRequiredByFlares) + bloomIntensityOverride = lensFlareScreenSpace.intensity.value; + m_BloomPass.Setup(bloomRequiredByFlares); m_BloomPass.RecordRenderGraph(renderGraph, frameData); - // We need to take into account how many valid mips the bloom pass produced. - var mipPyramid = m_BloomPass.mipPyramid; - int bloomMipCount = mipPyramid.mipCount; - int bloomMipMax = Mathf.Clamp(bloomMipCount - 1, 0, bloom.maxIterations.value / 2); - int bloomMipIndex = Mathf.Clamp(lensFlareScreenSpace.bloomMip.value, 0, bloomMipMax); + // Bloom produces no output if it is inactive or its shader is missing, e.g. stripped from the build. + if (resourceData.bloom.IsValid()) + { + // We need to take into account how many valid mips the bloom pass produced. + var mipPyramid = m_BloomPass.mipPyramid; + int bloomMipCount = mipPyramid.mipCount; + int bloomMipMax = Mathf.Clamp(bloomMipCount - 1, 0, bloom.maxIterations.value / 2); + int bloomMipIndex = Mathf.Clamp(lensFlareScreenSpace.bloomMip.value, 0, bloomMipMax); - var prevCameraColor = resourceData.cameraColor; - resourceData.cameraColor = mipPyramid.GetResultMip(bloomMipIndex);; + var prevCameraColor = resourceData.cameraColor; + resourceData.cameraColor = mipPyramid.GetResultMip(bloomMipIndex); - m_LensFlareScreenSpacePass.Setup(colorSourceDesc.width, colorSourceDesc.height, bloomMipIndex); - m_LensFlareScreenSpacePass.RecordRenderGraph(renderGraph, frameData); + m_LensFlareScreenSpacePass.Setup(colorSourceDesc.width, colorSourceDesc.height, bloomMipIndex); + m_LensFlareScreenSpacePass.RecordRenderGraph(renderGraph, frameData); - resourceData.cameraColor = prevCameraColor; + resourceData.cameraColor = prevCameraColor; + } } // Lens Flares are procedurally generated and blended to the destination texture. @@ -228,7 +235,7 @@ public void RenderPostProcessing(RenderGraph renderGraph, ContextContainer frame } bool renderOverlayUI = requireHDROutput && enableColorEncodingIfNeeded; - m_UberPass.Setup(ditherTexture, filteringOperation, hdrOperations, applySrgbEncoding, !hasFinalPass, renderOverlayUI); + m_UberPass.Setup(ditherTexture, filteringOperation, hdrOperations, applySrgbEncoding, !hasFinalPass, renderOverlayUI, bloomIntensityOverride); m_UberPass.RecordRenderGraph(renderGraph, frameData); } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/PostProcessUtils.cs b/Packages/com.unity.render-pipelines.universal/Runtime/PostProcessUtils.cs index 885b914ec6c..625057f77d3 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/PostProcessUtils.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/PostProcessUtils.cs @@ -1,3 +1,4 @@ +using System; using UnityEngine.Experimental.Rendering; using UnityEngine.Rendering.RenderGraphModule; using System.Runtime.CompilerServices; // AggressiveInlining @@ -9,29 +10,6 @@ namespace UnityEngine.Rendering.Universal /// public static class PostProcessUtils { - /// - /// Creates a post-processing pass material from a shader. Shader is error checked for device support. - /// - /// Shader used for the material - /// Pass name for error messages. - /// LogType for the message if the shader is not supported. - /// A new Material instance using the provided shader. Null if the shader is not supported or it's missing. - internal static Material LoadShader(Shader shader, string passName = "", LogType logLevel = LogType.Warning) - { - if (shader == null) - { - Debug.LogError($"Missing shader (in '{passName}'). PostProcessing render passes will not execute. Check for missing reference in the Renderer and/or PostProcessData resources."); - return null; - } - else if (!shader.isSupported) - { - Debug.unityLogger.Log(logLevel, $"Shader '{shader.name}' is not supported or has been stripped from the build (in '{passName}'). PostProcessing render passes will not execute."); - return null; - } - - return CoreUtils.CreateEngineMaterial(shader); - } - /// /// Creates a texture compatible with post-processing effects. /// @@ -400,4 +378,55 @@ static class ShaderConstants public static readonly int _SourceSize = Shader.PropertyToID("_SourceSize"); } } + + /// + /// Helper material class for a post-processing materials. + /// Handles checks and logging in case the shader is missing, unsupported or stripped from the build. + /// + internal sealed class PostProcessMaterial : IDisposable + { + readonly Shader m_Shader; + readonly string m_PassName; + Material m_Material; + bool m_LoggedFailure; + + public Shader shader => m_Shader; + public Material material => m_Material; + public bool isValid => m_Material != null; + + public PostProcessMaterial(Shader shader, string passName) + { + m_Shader = shader; + m_PassName = passName; + + // Note: isSupported is also false when all variants of the shader were stripped from the build. + if (shader != null && shader.isSupported) + m_Material = CoreUtils.CreateEngineMaterial(shader); + } + + /// + /// Returns whether the material can be used, and logs the reason once if it can't. + /// + public bool Validate() + { + if (isValid) + return true; + + if (!m_LoggedFailure) + { + m_LoggedFailure = true; + if (m_Shader == null) + Debug.LogError($"Missing shader (in '{m_PassName}'). This post-processing pass will not execute. Check for missing reference in the Renderer and/or PostProcessData resources."); + else if (!m_Shader.isSupported) + Debug.LogWarning($"Shader '{m_Shader.name}' is not supported or has been stripped from the build (in '{m_PassName}'). This post-processing pass will not execute."); + } + return false; + } + + public void Dispose() + { + CoreUtils.Destroy(m_Material); + m_Material = null; + } + } } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/ReflectionProbeManager.cs b/Packages/com.unity.render-pipelines.universal/Runtime/ReflectionProbeManager.cs index 1ce0d7e2b0e..af42a3638c8 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/ReflectionProbeManager.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/ReflectionProbeManager.cs @@ -33,6 +33,7 @@ struct ReflectionProbeManager : IDisposable const int k_ReflectionProbeChannelCount = k_ExposureMultiplierChannel + 1; NativeArray m_ReflectionProbeData; GraphicsBuffer m_ReflectionProbeBuffer; + bool m_ReflectionProbeBufferUploaded; // loose uniform fallback path Vector4[] m_BoxMax; @@ -76,8 +77,6 @@ static class ShaderProperties public static readonly int ProbePosition = Shader.PropertyToID("urp_ReflProbes_ProbePosition"); public static readonly int MipScaleOffset = Shader.PropertyToID("urp_ReflProbes_MipScaleOffset"); public static readonly int Rotation = Shader.PropertyToID("urp_ReflProbes_Rotation"); - - public static readonly int Count = Shader.PropertyToID("urp_ReflProbes_Count"); public static readonly int Atlas = Shader.PropertyToID("urp_ReflProbes_Atlas"); public static readonly int ExposureMultipliers = Shader.PropertyToID("urp_ReflProbes_ExposureMultipliers"); } @@ -95,7 +94,6 @@ public void PreSetup() if (m_UseConstantBuffer) { DisposeReflectionProbeConstantBuffer(); - CreateReflectionProbeConstantBuffer(); } else { @@ -151,17 +149,21 @@ void Init() m_NeedsUpdate = new List(m_MaxReflectionProbes); m_NeedsRemove = new List(m_MaxReflectionProbes); - if (m_UseConstantBuffer) - CreateReflectionProbeConstantBuffer(); - else + // The constant buffer is allocated on first use, a Forward+ renderer that never runs the reflection + // probe atlas path does not pay for it. + if (!m_UseConstantBuffer) CreateReflectionProbeLooseUniformArrays(); } - void CreateReflectionProbeConstantBuffer() + void EnsureReflectionProbeConstantBuffer() { + if (m_ReflectionProbeData.IsCreated) + return; + int length = m_MaxReflectionProbes * k_ReflectionProbeChannelCount; m_ReflectionProbeData = new NativeArray(length, Allocator.Persistent); + m_ReflectionProbeBufferUploaded = false; // GraphicsBuffer ctor will throw for zero length if (length > 0) @@ -204,6 +206,11 @@ public unsafe void UpdateGpuData(UniversalCameraData cameraData, CommandBuffer c var frameIndex = Time.renderedFrameCount; var probeBeingRendered = cameraData.cameraType == CameraType.Reflection ? cameraData.camera.reflectionProbeRendered : null; + // Created on the first camera that runs the atlas path, even if it sees no probe, and bound for every such + // camera from then on. + if (m_UseConstantBuffer) + EnsureReflectionProbeConstantBuffer(); + // Populate list of probes we need to remove to avoid modifying dictionary while iterating. foreach (var (id, cachedProbe) in m_Cache) { @@ -447,11 +454,25 @@ public unsafe void UpdateGpuData(UniversalCameraData cameraData, CommandBuffer c } } + var validProbeCount = probeCount - skipCount; + if (m_UseConstantBuffer) { if (m_ReflectionProbeBuffer != null) { - m_ReflectionProbeBuffer.SetData(m_ReflectionProbeData); + // Without a valid probe the loop above writes nothing, so m_ReflectionProbeData still holds + // what was last uploaded and the GPU copy already matches it. The shader can still read the + // buffer, since the clusters are built from all visible probes, including the skipped ones, + // but re-uploading the same data would be pure overhead. This matters for every camera that + // sees no probe at all, camera stacks in particular where each camera runs this path. + // The first upload is always performed so the GPU buffer is never left uninitialized. + if (validProbeCount > 0 || !m_ReflectionProbeBufferUploaded) + { + m_ReflectionProbeBuffer.SetData(m_ReflectionProbeData); + m_ReflectionProbeBufferUploaded = true; + } + + // The buffer stays bound even when empty. cmd.SetGlobalConstantBuffer(m_ReflectionProbeBuffer, ShaderProperties.ReflectionProbeBuffer, 0, m_ReflectionProbeData.Length * UnsafeUtility.SizeOf()); } } @@ -464,7 +485,6 @@ public unsafe void UpdateGpuData(UniversalCameraData cameraData, CommandBuffer c cmd.SetGlobalVectorArray(ShaderProperties.Rotation, m_Rotations); cmd.SetGlobalVectorArray(ShaderProperties.ExposureMultipliers, m_ExposureMultipliers); } - cmd.SetGlobalFloat(ShaderProperties.Count, probeCount - skipCount); cmd.SetGlobalTexture(ShaderProperties.Atlas, m_AtlasTexture0); } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Passes/FogVolumesPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Passes/FogVolumesPass.cs new file mode 100644 index 00000000000..8ea751d6fa2 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Passes/FogVolumesPass.cs @@ -0,0 +1,182 @@ +#if VOLUMETRIC_FOG + +using System; +using Unity.Collections.LowLevel.Unsafe; +using UnityEngine.Experimental.Rendering; +using UnityEngine.Rendering.RenderGraphModule; +using SharedIDs = UnityEngine.Rendering.Universal.VolumetricFogRendererFeature.ShaderIDs; + +namespace UnityEngine.Rendering.Universal +{ + internal class FogVolumesPass : ScriptableRenderPass, IDisposable + { + static class ShaderIDs + { + public static readonly int _FogVolumes = Shader.PropertyToID("_FogVolumes"); + public static readonly int _FogVolumeRunStart = Shader.PropertyToID("_FogVolumeRunStart"); + public static readonly int _FogVolumeDensityTexture = Shader.PropertyToID("_FogVolumeDensityTexture"); + public static readonly int _FogVolumeDensityTextureMode = Shader.PropertyToID("_FogVolumeDensityTextureMode"); + } + + // Must match k_DensityTextureMode* in FogVolume.shader. + enum DensityTextureMode + { + None, + Color, + Alpha, + Red, + } + + const int k_QuadVertexCount = 6; + + readonly MaterialPropertyBlock m_PropertyBlock = new MaterialPropertyBlock(); + Material m_Material; + + class PassData + { + public Material material; + public MaterialPropertyBlock propertyBlock; + + public FogVolumeManager fogVolumeManager; + + public Matrix4x4 coordToViewDirWS; + + public BufferHandle fogVolumeBuffer; + public TextureHandle vbufferDensity; + } + + public FogVolumesPass() + { + GraphicsSettings.TryGetRenderPipelineSettings(out var resources); + m_Material = CoreUtils.CreateEngineMaterial(resources?.fogVolumePS); + } + + public void Dispose() + { + CoreUtils.Destroy(m_Material); + m_Material = null; + } + + public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) + { + if (m_Material == null || !SystemInfo.supportsRenderTargetArrayIndexFromVertexShader) + return; + + var fogData = frameData.GetOrCreate(); + if (!fogData.vbufferDensity.IsValid()) + return; + + var fogVolumeManager = ((UniversalRenderer)frameData.Get().renderer).fogVolumeManager; + + // Culling completes at execution, so only the total count is known here. + int maxFogVolumeCount = fogVolumeManager.fogVolumeCount; + if (maxFogVolumeCount == 0) + return; + + using (var builder = renderGraph.AddUnsafePass("Fog Volumes", out var passData)) + { + passData.material = m_Material; + passData.propertyBlock = m_PropertyBlock; + passData.fogVolumeManager = fogVolumeManager; + passData.coordToViewDirWS = fogData.vBufferParams.coordToViewDirWS; + + var fogVolumeBufferDesc = new BufferDesc( + maxFogVolumeCount, + UnsafeUtility.SizeOf(), + GraphicsBuffer.Target.Structured) + { + name = "Fog Volume Data" + }; + passData.fogVolumeBuffer = renderGraph.CreateBuffer(fogVolumeBufferDesc); + builder.UseBuffer(passData.fogVolumeBuffer, AccessFlags.Write); + + passData.vbufferDensity = fogData.vbufferDensity; + builder.UseTexture(passData.vbufferDensity, AccessFlags.ReadWrite); + + builder.SetRenderFunc(static (PassData data, UnsafeGraphContext context) => + { + var fogVolumeManager = data.fogVolumeManager; + int fogVolumeCount = fogVolumeManager.CompleteCulling(); + if (fogVolumeCount == 0) + return; + + var fogVolumeData = fogVolumeManager.visibleFogVolumeData; + var blendModes = fogVolumeManager.visibleBlendModes; + + var cmd = context.cmd; + GraphicsBuffer fogVolumeBuffer = data.fogVolumeBuffer; + + cmd.SetBufferData(fogVolumeBuffer, fogVolumeData, 0, 0, fogVolumeCount); + cmd.SetRenderTarget(data.vbufferDensity, 0, CubemapFace.Unknown, -1); + + var properties = data.propertyBlock; + properties.SetBuffer(ShaderIDs._FogVolumes, fogVolumeBuffer); + properties.SetMatrix(SharedIDs._VBufferCoordToViewDirWS, data.coordToViewDirWS); + + // Instances blend in order, so consecutive volumes sharing a blend mode and density texture share a draw. + int runStart = 0; + while (runStart < fogVolumeCount) + { + var blendMode = blendModes[runStart]; + Texture densityTexture = null; + bool hasTexturedVolume = false; + uint maxSliceCount = 0; + + int runEnd = runStart; + for (; runEnd < fogVolumeCount; ++runEnd) + { + if (blendModes[runEnd] != blendMode) + break; + + if (fogVolumeData[runEnd].densityMode == (uint)FogVolumeDensityMode.Texture) + { + var fogVolumeTexture = fogVolumeManager.GetVisibleFogVolume(runEnd).densityTexture; + if (!hasTexturedVolume) + { + densityTexture = fogVolumeTexture; + hasTexturedVolume = true; + } + else if (fogVolumeTexture != densityTexture) + break; + } + + maxSliceCount = Math.Max(maxSliceCount, fogVolumeData[runEnd].sliceCount); + } + + var densityTextureMode = DensityTextureMode.None; + + // Ignore density textures that aren't 3D. + if (densityTexture != null && densityTexture.dimension == TextureDimension.Tex3D) + { + var format = densityTexture.graphicsFormat; + if (GraphicsFormatUtility.IsAlphaOnlyFormat(format)) + densityTextureMode = DensityTextureMode.Alpha; + else if (GraphicsFormatUtility.GetColorComponentCount(format) == 1) + densityTextureMode = DensityTextureMode.Red; + else + densityTextureMode = DensityTextureMode.Color; + + properties.SetTexture(ShaderIDs._FogVolumeDensityTexture, densityTexture); + } + + properties.SetInteger(ShaderIDs._FogVolumeDensityTextureMode, (int)densityTextureMode); + properties.SetInteger(ShaderIDs._FogVolumeRunStart, runStart); + + cmd.DrawProcedural( + Matrix4x4.identity, + data.material, + (int)blendMode, + MeshTopology.Triangles, + k_QuadVertexCount * (int)maxSliceCount, + runEnd - runStart, + properties); + + runStart = runEnd; + } + }); + } + } + } +} + +#endif diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Passes/FogVolumesPass.cs.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Passes/FogVolumesPass.cs.meta new file mode 100644 index 00000000000..0404f0d7da7 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Passes/FogVolumesPass.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 9bec169a92ff51b419176cce7b34550d \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Passes/GenerateMaxZMaskPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Passes/GenerateMaxZMaskPass.cs index 48b6c5e92dd..0ccaae8d0e5 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Passes/GenerateMaxZMaskPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Passes/GenerateMaxZMaskPass.cs @@ -94,22 +94,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer passData.finalMaskH = finalMaskH; passData.viewCount = slices; - var camera = cameraData.camera; - float near = camera.nearClipPlane; - float far = camera.farClipPlane; - float invNear = Mathf.Approximately(near, 0.0f) ? 0.0f : 1.0f / near; - float invFar = Mathf.Approximately(far, 0.0f) ? 0.0f : 1.0f / far; - float zc0 = 1.0f - far * invNear; - float zc1 = far * invNear; - var zBufferParams = new Vector4(zc0, zc1, zc0 * invFar, zc1 * invFar); - if (SystemInfo.usesReversedZBuffer) - { - zBufferParams.y += zBufferParams.x; - zBufferParams.x = -zBufferParams.x; - zBufferParams.w += zBufferParams.z; - zBufferParams.z = -zBufferParams.z; - } - passData.zBufferParams = zBufferParams; + passData.zBufferParams = RenderingUtils.ComputeZBufferParams(cameraData.camera); // Input texture passData.depthTexture = resourceData.cameraDepthTexture; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Passes/VolumetricFogGlobalsPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Passes/VolumetricFogGlobalsPass.cs index 9c735cfb937..816c35b7c86 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Passes/VolumetricFogGlobalsPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Passes/VolumetricFogGlobalsPass.cs @@ -125,10 +125,13 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer if (fogData.volumetricFogEnabled) { var cameraData = frameData.Get(); - fogData.vBufferParams = new VBufferParams(cameraData.camera, cameraData.cameraTargetDescriptor, fogData.screenFraction, fogData.sliceCount, fogData.cutoffDistance, fogData.sliceDistributionUniformity); + fogData.vBufferParams = new VBufferParams(cameraData, fogData.screenFraction, fogData.sliceCount, fogData.cutoffDistance, fogData.sliceDistributionUniformity); fogData.encodingParams = fogData.vBufferParams.encodingParams; fogData.decodingParams = fogData.vBufferParams.decodingParams; fogData.viewportSize = fogData.vBufferParams.viewportSize; + + var fogVolumeManager = ((UniversalRenderer)cameraData.renderer).fogVolumeManager; + fogVolumeManager.ScheduleCulling(cameraData, fogData.vBufferParams, fogData.cutoffDistance); } } else diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Passes/VolumetricLightingPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Passes/VolumetricLightingPass.cs index 3768e346eb6..1842fe1e92d 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Passes/VolumetricLightingPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Passes/VolumetricLightingPass.cs @@ -38,24 +38,17 @@ static class ShaderIDs public static readonly int _PrevCamPosWS = Shader.PropertyToID("_PrevCamPosWS"); public static readonly int _VBufferPrevViewProjMatrix = Shader.PropertyToID("_VBufferPrevViewProjMatrix"); - public static readonly int _AdditionalLightsCount = Shader.PropertyToID("_AdditionalLightsCount"); public static readonly int AdditionalLights = Shader.PropertyToID("AdditionalLights"); public static readonly int urp_ZBinBuffer = Shader.PropertyToID("urp_ZBinBuffer"); public static readonly int urp_TileBuffer = Shader.PropertyToID("urp_TileBuffer"); public static readonly int urp_ZBins = Shader.PropertyToID("urp_ZBins"); public static readonly int urp_Tiles = Shader.PropertyToID("urp_Tiles"); - public static readonly int _FPParams0 = Shader.PropertyToID("_FPParams0"); - public static readonly int _FPParams1 = Shader.PropertyToID("_FPParams1"); - public static readonly int _FPParams2 = Shader.PropertyToID("_FPParams2"); public static readonly int _WorldSpaceCameraPos = Shader.PropertyToID("_WorldSpaceCameraPos"); public static readonly int unity_MatrixV = Shader.PropertyToID("unity_MatrixV"); // Light cookies public static readonly int _MainLightCookieTexture = Shader.PropertyToID("_MainLightCookieTexture"); public static readonly int _AdditionalLightsCookieAtlasTexture = Shader.PropertyToID("_AdditionalLightsCookieAtlasTexture"); - public static readonly int _MainLightWorldToLight = Shader.PropertyToID("_MainLightWorldToLight"); - public static readonly int _MainLightCookieTextureFormat = Shader.PropertyToID("_MainLightCookieTextureFormat"); - public static readonly int _AdditionalLightsCookieAtlasTextureFormat = Shader.PropertyToID("_AdditionalLightsCookieAtlasTextureFormat"); public static readonly int LightCookies = Shader.PropertyToID("LightCookies"); } @@ -99,6 +92,7 @@ class VolumetricLightingPassData public bool depthIsArray; public bool applyLocalLights; public UniversalShadowData shadowData; + public UniversalGlobalShaderData globalShaderData; // Textures public TextureHandle depthTexture; @@ -261,6 +255,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer passData.depthIsArray = depthIsArray; passData.applyLocalLights = applyLocalLights; passData.shadowData = frameData.Get(); + passData.globalShaderData = frameData.Get(); passData.vbufferW = vBufferParams.vbufferW; passData.vbufferH = vBufferParams.vbufferH; @@ -478,7 +473,8 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer // Pull previous view-projection / camera position from the per-camera motion tracker. Matrix4x4 prevVP = Matrix4x4.identity; Vector3 prevCamPos = camera.transform.position; - if (camera.TryGetComponent(out var additional)) + var additional = cameraData.additionalCameraData; + if (additional != null) { var motionData = additional.motionVectorsPersistentData; prevVP = motionData.previousViewProjection; @@ -573,14 +569,16 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer cmd.SetComputeTextureParam(cs, kernel, SharedIDs._VBufferDensity, data.vbufferDensity); cmd.SetComputeTextureParam(cs, kernel, SharedIDs._VBuffer, data.vbuffer); + // The light list and cookie variables are read-only in the public interfaces, URP writes them here. + using var globals = data.globalShaderData.GetUploader().Get(); + // Bind URP's persistent AdditionalLights constant buffer, or the zero stand-in if ForwardLights // didn't provide one. { GraphicsBuffer additionalLightsCB = data.additionalLightsCB ?? data.zeroLightCB; int additionalLightsCBSizeBytes = data.additionalLightsCB != null ? data.additionalLightsCBSizeBytes : data.zeroLightCBSizeBytes; cmd.SetComputeConstantBufferParam(cs, ShaderIDs.AdditionalLights, additionalLightsCB, 0, additionalLightsCBSizeBytes); - cmd.SetComputeVectorParam(cs, ShaderIDs._AdditionalLightsCount, - new Vector4(data.additionalLightsCount, 0f, 0f, 0f)); + globals._AdditionalLightsCount = new Vector4(data.additionalLightsCount, 0f, 0f, 0f); } if (data.zBinsBuffer != null && data.tileMasksBuffer != null) @@ -598,9 +596,9 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer data.tileMasksBuffer, 0, UniversalRenderPipeline.maxTileWords * 4); } - cmd.SetComputeVectorParam(cs, ShaderIDs._FPParams0, data.fpParams0); - cmd.SetComputeVectorParam(cs, ShaderIDs._FPParams1, data.fpParams1); - cmd.SetComputeVectorParam(cs, ShaderIDs._FPParams2, data.fpParams2); + globals._FPParams0 = data.fpParams0; + globals._FPParams1 = data.fpParams1; + globals._FPParams2 = data.fpParams2; cmd.SetComputeVectorParam(cs, ShaderIDs._WorldSpaceCameraPos, data.cameraPositionWS); cmd.SetComputeMatrixParam(cs, ShaderIDs.unity_MatrixV, data.viewMatrix); } @@ -611,9 +609,9 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer cmd.SetComputeTextureParam(cs, kernel, ShaderIDs._MainLightCookieTexture, data.mainCookieTexture); cmd.SetComputeTextureParam(cs, kernel, ShaderIDs._AdditionalLightsCookieAtlasTexture, data.additionalCookieAtlas); - cmd.SetComputeMatrixParam(cs, ShaderIDs._MainLightWorldToLight, sampleCookies ? data.mainCookieWorldToLight : Matrix4x4.identity); - cmd.SetComputeFloatParam(cs, ShaderIDs._MainLightCookieTextureFormat, sampleCookies ? data.mainCookieFormat : kLightCookieFormatNone); - cmd.SetComputeFloatParam(cs, ShaderIDs._AdditionalLightsCookieAtlasTextureFormat, sampleCookies ? data.additionalCookieFormat : kLightCookieFormatNone); + globals._MainLightWorldToLight = sampleCookies ? data.mainCookieWorldToLight : Matrix4x4.identity; + globals._MainLightCookieTextureFormat = sampleCookies ? data.mainCookieFormat : kLightCookieFormatNone; + globals._AdditionalLightsCookieAtlasTextureFormat = sampleCookies ? data.additionalCookieFormat : kLightCookieFormatNone; { GraphicsBuffer lightCookieCB = data.zeroLightCB; int lightCookieCBSizeBytes = data.zeroCookieCBSizeBytes; @@ -641,6 +639,8 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer cmd.SetComputeTextureParam(cs, kernel, ShaderIDs._VBufferFeedback, data.feedbackBuffer); } + globals.Push(cmd); + int dispatchX = CoreUtils.DivRoundUp(data.vbufferW, 8); int dispatchY = CoreUtils.DivRoundUp(data.vbufferH, 8); cmd.DispatchCompute(cs, kernel, dispatchX, dispatchY, 1); diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Shaders/FogVolume.shader b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Shaders/FogVolume.shader new file mode 100644 index 00000000000..22d31ef7ac1 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Shaders/FogVolume.shader @@ -0,0 +1,197 @@ +Shader "Hidden/Universal Render Pipeline/FogVolume" +{ + HLSLINCLUDE + #pragma target 4.5 + #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2 + + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" + + // Must match FogVolumeData in FogVolumeCullingJob.cs. + struct FogVolumeData + { + float4 axisX; + float4 axisY; + float4 axisZ; + float4 center; + float4 scattering; + float4 clipBounds; + float3 densityTextureTiling; + uint startSlice; // 16-byte boundary + float3 densityTextureScrollSpeed; + uint sliceCount; // 16-byte boundary + uint densityMode; + uint3 padding; // 16-byte boundary + }; + + StructuredBuffer _FogVolumes; + float4x4 _VBufferCoordToViewDirWS; + int _FogVolumeRunStart; + int _FogVolumeDensityTextureMode; + + TEXTURE3D(_FogVolumeDensityTexture); + SAMPLER(sampler_FogVolumeDensityTexture); + + // Set globally by VolumetricFogGlobalsPass. + float4 _DepthDecodingParams; + float _VBufferRcpSliceCount; + + // Must match FogVolumeDensityMode in FogVolume.cs. + static const uint k_FogVolumeDensityModeConstant = 0; + static const uint k_FogVolumeDensityModeTexture = 1; + + // Must match DensityTextureMode in FogVolumesPass.cs. + static const int k_DensityTextureModeNone = 0; + static const int k_DensityTextureModeColor = 1; + static const int k_DensityTextureModeAlpha = 2; + static const int k_DensityTextureModeRed = 3; + + // Must match k_QuadVertexCount in FogVolumesPass.cs. + static const uint k_QuadVertexCount = 6; + + static const float2 k_QuadCorners[k_QuadVertexCount] = + { + float2(0.0, 0.0), float2(1.0, 0.0), float2(0.0, 1.0), + float2(0.0, 1.0), float2(1.0, 0.0), float2(1.0, 1.0) + }; + + struct Varyings + { + float4 positionCS : SV_POSITION; + nointerpolation uint slice : TEXCOORD0; + nointerpolation uint fogVolumeIndex : TEXCOORD1; + nointerpolation uint renderTargetIndex : SV_RenderTargetArrayIndex; + }; + + Varyings Vert(uint vertexID : SV_VertexID, uint instanceID : SV_InstanceID) + { + uint fogVolumeIndex = _FogVolumeRunStart + instanceID; + FogVolumeData fogVolume = _FogVolumes[fogVolumeIndex]; + float4 clipBounds = fogVolume.clipBounds; + + uint quadIndex = vertexID / k_QuadVertexCount; + uint cornerIndex = vertexID % k_QuadVertexCount; + + Varyings output; + output.positionCS = float4(clipBounds.xy + k_QuadCorners[cornerIndex] * clipBounds.zw, 0.5, 1.0); + output.slice = fogVolume.startSlice + quadIndex; + output.fogVolumeIndex = fogVolumeIndex; + output.renderTargetIndex = output.slice; + + if (quadIndex >= fogVolume.sliceCount) + { + output.positionCS = float4(0.0, 0.0, 0.5, 1.0); + output.renderTargetIndex = 0; + } + + return output; + } + + float4 Frag(Varyings input) : SV_Target + { + FogVolumeData fogVolume = _FogVolumes[input.fogVolumeIndex]; + + // Matches the voxel centers written by VolumeVoxelization.compute. + float3 rayDirWS = mul(-float4(input.positionCS.xy, 1, 1), _VBufferCoordToViewDirWS).xyz; + float rayLength = length(rayDirWS); + float3 dirWS = rayDirWS / rayLength; + float tStart = _ProjectionParams.y * rayLength; + + float e0 = input.slice * _VBufferRcpSliceCount; + float t0 = max(tStart, DecodeLogarithmicDepthGeneralized(e0, _DepthDecodingParams)); + float t1 = max(tStart, DecodeLogarithmicDepthGeneralized(e0 + _VBufferRcpSliceCount, _DepthDecodingParams)); + float3 voxelCenterWS = _WorldSpaceCameraPos + 0.5 * (t0 + t1) * dirWS; + + float3 offset = voxelCenterWS - fogVolume.center.xyz; + float3 positionLS = float3(dot(offset, fogVolume.axisX.xyz), dot(offset, fogVolume.axisY.xyz), dot(offset, fogVolume.axisZ.xyz)); + if (any(abs(positionLS) > 1.0)) + discard; + + // RGB tints the albedo and alpha scales the density. + float4 densityTexel = 1.0; + [branch] + if (fogVolume.densityMode == k_FogVolumeDensityModeTexture) + { + // Fog volumes without a 3D texture have no fog. + densityTexel = 0.0; + if (_FogVolumeDensityTextureMode != k_DensityTextureModeNone) + { + float3 uvw = (positionLS * 0.5 + 0.5) * fogVolume.densityTextureTiling - fogVolume.densityTextureScrollSpeed * _Time.y; + densityTexel = SAMPLE_TEXTURE3D_LOD(_FogVolumeDensityTexture, sampler_FogVolumeDensityTexture, uvw, 0); + if (_FogVolumeDensityTextureMode == k_DensityTextureModeAlpha) + densityTexel.rgb = 1.0; + else if (_FogVolumeDensityTextureMode == k_DensityTextureModeRed) + densityTexel = float4(1.0, 1.0, 1.0, densityTexel.r); + } + } + + return fogVolume.scattering * float4(densityTexel.rgb * densityTexel.a, densityTexel.a); + } + ENDHLSL + + SubShader + { + Tags { "RenderPipeline" = "UniversalPipeline" } + + ZWrite Off + ZTest Always + Cull Off + + // Pass order must match FogVolumeBlendMode. + Pass + { + Name "Overwrite" + Blend One Zero + + HLSLPROGRAM + #pragma vertex Vert + #pragma fragment Frag + ENDHLSL + } + + Pass + { + Name "Add" + Blend One One + + HLSLPROGRAM + #pragma vertex Vert + #pragma fragment Frag + ENDHLSL + } + + Pass + { + Name "Multiply" + Blend DstColor Zero + + HLSLPROGRAM + #pragma vertex Vert + #pragma fragment Frag + ENDHLSL + } + + Pass + { + Name "Min" + Blend One One + BlendOp Min + + HLSLPROGRAM + #pragma vertex Vert + #pragma fragment Frag + ENDHLSL + } + + Pass + { + Name "Max" + Blend One One + BlendOp Max + + HLSLPROGRAM + #pragma vertex Vert + #pragma fragment Frag + ENDHLSL + } + } +} diff --git a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Shaders/PassthroughSkybox.shader.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Shaders/FogVolume.shader.meta similarity index 80% rename from Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Shaders/PassthroughSkybox.shader.meta rename to Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Shaders/FogVolume.shader.meta index e4fbd818a35..fa032beb8e7 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Shaders/PassthroughSkybox.shader.meta +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Shaders/FogVolume.shader.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 5e4da360906ed014eb18ce666f57cc46 +guid: 6a5eb07a8ed637e4f8c8316c9f6f5770 ShaderImporter: externalObjects: {} defaultTextures: [] diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Shaders/VolumeVoxelization.compute b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Shaders/VolumeVoxelization.compute index ebb1cdc2817..1ec91d61d01 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Shaders/VolumeVoxelization.compute +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Shaders/VolumeVoxelization.compute @@ -44,12 +44,12 @@ void VolumeVoxelization(uint3 dispatchThreadId : SV_DispatchThreadID) if (voxelCoord.x >= (uint)_VBufferSize.x || voxelCoord.y >= (uint)_VBufferSize.y) return; - // World-space view ray through the column center, starting at the near plane. - float3 F = normalize(mul(-float4(0.5 * _VBufferSize.x, 0.5 * _VBufferSize.y, 1, 1), _VBufferCoordToViewDirWS).xyz); + // View ray through the column center. Its view-space depth is 1, so it meets the near plane at near * length. float2 centerCoord = voxelCoord + float2(0.5, 0.5); float3 rayDirWS = mul(-float4(centerCoord, 1, 1), _VBufferCoordToViewDirWS).xyz; - float3 dirWS = rayDirWS * rsqrt(dot(rayDirWS, rayDirWS)); - float tStart = _CameraNearPlane / dot(F, dirWS); + float rayLength = length(rayDirWS); + float3 dirWS = rayDirWS / rayLength; + float tStart = _CameraNearPlane * rayLength; for (uint slice = 0; slice < _VBufferSliceCount; slice++) { diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Shaders/VolumetricLighting.compute b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Shaders/VolumetricLighting.compute index 2a9fde2a0e8..8becef96e76 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Shaders/VolumetricLighting.compute +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/Shaders/VolumetricLighting.compute @@ -173,8 +173,8 @@ void VolumetricLighting(uint3 dispatchThreadId : SV_DispatchThreadID) if (voxelCoord.x >= (uint)_VBufferSize.x || voxelCoord.y >= (uint)_VBufferSize.y) return; - // View forward direction: the center voxel maps approximately to the camera forward axis. - float3 F = normalize(mul(-float4(0.5 * _VBufferSize.x, 0.5 * _VBufferSize.y, 1, 1), _VBufferCoordToViewDirWS).xyz); + // Rows 0 and 1 are the camera right and up axes, so their cross product is the forward axis, even with lens shift. + float3 F = normalize(cross(_VBufferCoordToViewDirWS[0].xyz, _VBufferCoordToViewDirWS[1].xyz)); // No camera up matrix is exposed, so pick a world axis to derive a perpendicular basis from F. float3 U = abs(F.y) < 0.999 ? float3(0, 1, 0) : float3(1, 0, 0); diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/VBufferParams.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/VBufferParams.cs index ceb57f7f02f..f38d37a16f3 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/VBufferParams.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/VBufferParams.cs @@ -17,10 +17,10 @@ internal struct VBufferParams public Vector4 decodingParams; // logarithmic-depth decoding public Matrix4x4 coordToViewDirWS; // pixel coord → world-space view direction - internal VBufferParams(Camera camera, RenderTextureDescriptor descriptor, float screenFraction, int sliceCount, float cutoffDistance, float sliceDistributionUniformity) + internal VBufferParams(UniversalCameraData cameraData, float screenFraction, int sliceCount, float cutoffDistance, float sliceDistributionUniformity) { - int screenWidth = descriptor.width; - int screenHeight = descriptor.height; + int screenWidth = cameraData.cameraTargetDescriptor.width; + int screenHeight = cameraData.cameraTargetDescriptor.height; // At the default 12.5% this gives the same results as a fixed 8-pixel // voxel for screen sizes that are multiples of 8. @@ -29,9 +29,12 @@ internal VBufferParams(Camera camera, RenderTextureDescriptor descriptor, float voxelSize = 1.0f / screenFraction; this.sliceCount = sliceCount; - float nearPlane = camera.nearClipPlane; - float vFoV = camera.fieldOfView * Mathf.Deg2Rad; - float tanHalfVertFoV = Mathf.Tan(0.5f * vFoV); + // Uses the projection rather than fieldOfView so gate fit and lens shift match the rendered image. + Matrix4x4 projection = cameraData.GetProjectionMatrixNoJitter(); + float nearPlane = cameraData.camera.nearClipPlane; + float tanHalfVertFoV = 1.0f / projection.m11; + float tanHalfHorzFoV = 1.0f / projection.m00; + float vFoV = 2.0f * Mathf.Atan(tanHalfVertFoV); viewportSize = new Vector4(vbufferW, vbufferH, 1.0f / vbufferW, 1.0f / vbufferH); unitDepthTexelSpacing = tanHalfVertFoV * (2.0f / vbufferH); halfVoxelArcLength = vFoV * 0.5f / vbufferH; @@ -54,11 +57,10 @@ internal VBufferParams(Camera camera, RenderTextureDescriptor descriptor, float // Pixel-coord to world-space view-direction matrix { - float aspectRatio = viewportSize.x * viewportSize.w; - float m00 = -2.0f * viewportSize.z * tanHalfVertFoV * aspectRatio; + float m00 = -2.0f * viewportSize.z * tanHalfHorzFoV; float m11 = -2.0f * viewportSize.w * tanHalfVertFoV; - float m20 = tanHalfVertFoV * aspectRatio; - float m21 = tanHalfVertFoV; + float m20 = (1.0f - projection.m02) * tanHalfHorzFoV; + float m21 = (1.0f - projection.m12) * tanHalfVertFoV; var viewSpaceRasterTransform = new Matrix4x4( new Vector4(m00, 0.0f, 0.0f, 0.0f), @@ -66,7 +68,7 @@ internal VBufferParams(Camera camera, RenderTextureDescriptor descriptor, float new Vector4(m20, m21, -1.0f, 0.0f), new Vector4(0.0f, 0.0f, 0.0f, 1.0f)); - Matrix4x4 viewMatrix = camera.worldToCameraMatrix; + Matrix4x4 viewMatrix = cameraData.GetViewMatrix(); viewMatrix.SetColumn(3, new Vector4(0, 0, 0, 1)); viewMatrix.SetRow(2, -viewMatrix.GetRow(2)); coordToViewDirWS = Matrix4x4.Transpose(viewMatrix.transpose * viewSpaceRasterTransform); diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/VolumetricFogRendererFeature.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/VolumetricFogRendererFeature.cs index 105bc3bcfce..a182ed35000 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/VolumetricFogRendererFeature.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/VolumetricFogRendererFeature.cs @@ -7,7 +7,7 @@ namespace UnityEngine.Rendering.Universal /// [SupportedOnRenderer(typeof(UniversalRendererData))] [DisallowMultipleRendererFeature("Volumetric Fog")] - [Tooltip("Renders volumetric fog by voxelizing global and local fog volumes, ray-marching lit volume slices, and compositing the result.")] + [Tooltip("Renders volumetric fog by voxelizing the global fog and Fog Volumes, ray-marching lit volume slices, and compositing the result.")] public sealed class VolumetricFogRendererFeature : ScriptableRendererFeature { // IDs used by more than one pass live here. Single-callsite IDs are declared @@ -31,6 +31,7 @@ internal static class ShaderIDs VolumetricFogGlobalsPass m_GlobalsPass; GenerateMaxZMaskPass m_MaxZPass; VolumeVoxelizationPass m_VoxelizationPass; + FogVolumesPass m_FogVolumesPass; VolumetricLightingPass m_LightingPass; VolumetricFilteringPass m_FilteringPass; ApplyVolumetricFogPass m_ApplyPass; @@ -47,6 +48,7 @@ public override void Create() m_GlobalsPass = new VolumetricFogGlobalsPass { renderPassEvent = RenderPassEvent.BeforeRenderingShadows }; m_MaxZPass = new GenerateMaxZMaskPass { renderPassEvent = RenderPassEvent.AfterRenderingSkybox }; m_VoxelizationPass = new VolumeVoxelizationPass { renderPassEvent = RenderPassEvent.AfterRenderingSkybox }; + m_FogVolumesPass = new FogVolumesPass { renderPassEvent = RenderPassEvent.AfterRenderingSkybox }; m_LightingPass = new VolumetricLightingPass { renderPassEvent = RenderPassEvent.AfterRenderingSkybox }; m_FilteringPass = new VolumetricFilteringPass { renderPassEvent = RenderPassEvent.AfterRenderingSkybox }; m_ApplyPass = new ApplyVolumetricFogPass { renderPassEvent = RenderPassEvent.AfterRenderingSkybox }; @@ -83,6 +85,7 @@ public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingD renderer.EnqueuePass(m_MaxZPass); renderer.EnqueuePass(m_VoxelizationPass); + renderer.EnqueuePass(m_FogVolumesPass); renderer.EnqueuePass(m_LightingPass); renderer.EnqueuePass(m_FilteringPass); renderer.EnqueuePass(m_ApplyPass); @@ -95,6 +98,7 @@ protected override void Dispose(bool disposing) if (m_GlobalsPass == null) return; + m_FogVolumesPass.Dispose(); m_LightingPass.Dispose(); m_ApplyPass.Dispose(); m_SSMSPass.Dispose(); @@ -102,6 +106,7 @@ protected override void Dispose(bool disposing) m_GlobalsPass = null; m_MaxZPass = null; m_VoxelizationPass = null; + m_FogVolumesPass = null; m_LightingPass = null; m_FilteringPass = null; m_ApplyPass = null; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/VolumetricFogResources.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/VolumetricFogResources.cs index 35d7d5dd91a..398c0e63e32 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/VolumetricFogResources.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/Fog/VolumetricFogResources.cs @@ -66,6 +66,15 @@ public Shader screenSpaceMultipleScatteringPS get => m_ScreenSpaceMultipleScatteringPS; set => this.SetValueAndNotify(ref m_ScreenSpaceMultipleScatteringPS, value); } + + [SerializeField, ResourcePath("Runtime/RendererFeatures/Fog/Shaders/FogVolume.shader")] + private Shader m_FogVolumePS; + + public Shader fogVolumePS + { + get => m_FogVolumePS; + set => this.SetValueAndNotify(ref m_FogVolumePS, value); + } } } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/ScreenSpaceReflectionRendererFeature/ScreenSpaceReflectionPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/ScreenSpaceReflectionRendererFeature/ScreenSpaceReflectionPass.cs index 6c5f978ed33..a99613f618f 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/ScreenSpaceReflectionRendererFeature/ScreenSpaceReflectionPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/ScreenSpaceReflectionRendererFeature/ScreenSpaceReflectionPass.cs @@ -30,6 +30,7 @@ private enum ShaderPasses BilinearUpscale = 2, // Single pass bilinear upscale BilateralUpscale = 3, // Single pass normal-weighted bilinear upscale TemporalFiltering = 4, + Debug = 5, } // Constants @@ -72,6 +73,7 @@ internal static class ShaderConstants internal static readonly int _ReflectionHistoryTexture = Shader.PropertyToID("_ReflectionHistoryTexture"); internal static readonly int _BaseBlendFactor = Shader.PropertyToID("_BaseBlendFactor"); internal static readonly int _ResolutionScales = Shader.PropertyToID("_ResolutionScales"); + internal static readonly int _DebugParams = Shader.PropertyToID("_DebugParams"); } // Private Variables @@ -220,6 +222,24 @@ private class TemporalFilteringPassData internal Vector2Int viewportSize; } + private class DebugPassData + { + internal Material material; + internal TextureHandle source; + internal TextureHandle cameraDepth; + internal TextureHandle smoothnessTexture; + internal TextureHandle rayDistanceTexture; + internal TextureHandle sceneColor; + internal TextureHandle sceneColorMotionVectors; + internal TextureHandle blackTexture; + internal ScreenSpaceReflectionDebugViewMode viewMode; + internal float sourceLastMipIndex; + internal float rayDistanceRange; + internal bool showSceneColor; + internal Vector2 currentResolutionScale; + internal Vector2 sceneColorResolutionScale; + } + private class DepthCopyPassData { internal Material blitMaterial; @@ -282,6 +302,9 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer } } + TextureHandle selectedMotionVectorTexture; + TextureHandle selectedSceneColorTexture; + Vector2 selectedSceneColorScale; using (var builder = renderGraph.AddRasterRenderPass("SSR - Main Pass", out var passData)) { // Shader keyword changes are considered as global state modifications @@ -405,6 +428,11 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer } } + // Store references to the textures actually used by the main marching pass, used for debug vis. + selectedMotionVectorTexture = passData.motionVectorColor; + selectedSceneColorTexture = passData.afterOpaque ? passData.cameraColor : passData.lastFrameCameraColor; + selectedSceneColorScale = passData.cameraColorResolutionScale; + builder.SetRenderFunc(static (ssrData, rgContext) => { SetupKeywordsAndParameters(ref ssrData); @@ -592,6 +620,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer textureToBlit = mipGenTexture; m_MipGenerator.RenderColorGaussianPyramid(renderGraph, viewportSizeWithScale, fullResSSRTexture, mipGenTexture); } + RenderDebugView(renderGraph, cameraData, textureToBlit, selectedSceneColorTexture, selectedSceneColorScale, selectedMotionVectorTexture, cameraDepthTexture, smoothnessTexture, rayDistanceTexture); RenderAfterOpaqueBlit(renderGraph, textureToBlit, rayDistanceTexture, finalTexture); } else @@ -602,6 +631,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer { renderGraph.AddCopyPass(fullResSSRTexture, finalTexture, passName: "Final blit"); } + RenderDebugView(renderGraph, cameraData, finalTexture, selectedSceneColorTexture, selectedSceneColorScale, selectedMotionVectorTexture, cameraDepthTexture, smoothnessTexture, rayDistanceTexture); } } } @@ -883,7 +913,7 @@ private static void RenderDepthHistory(RenderGraph renderGraph, UniversalCameraD } } } - + // Copies the potentially dynamically scaled depth into a viewport of a fixed size target. static void AddDepthCopyPass(RenderGraph renderGraph, TextureHandle source, TextureHandle destination, Vector2Int viewportSize, Material blitMaterial, string passName) { @@ -904,5 +934,81 @@ static void AddDepthCopyPass(RenderGraph renderGraph, TextureHandle source, Text }); } } + + private void RenderDebugView( + RenderGraph renderGraph, + UniversalCameraData cameraData, + TextureHandle source, + TextureHandle sceneColor, + Vector2 sceneColorResolutionScale, + TextureHandle sceneColorMotionVectors, + TextureHandle cameraDepth, + TextureHandle smoothnessTexture, + TextureHandle rayDistanceTexture) + { + var debugSettings = UniversalRenderPipelineDebugDisplaySettings.Instance.screenSpaceReflectionSettings; + if (debugSettings.viewMode == ScreenSpaceReflectionDebugViewMode.None) + return; + + DebugHandler debugHandler = GetActiveDebugHandler(cameraData); + if (debugHandler == null) + return; + + TextureDesc sourceDesc = source.GetDescriptor(renderGraph); + TextureDesc debugDesc = sourceDesc; + debugDesc.name = "_SSR_DebugTexture"; + debugDesc.useMipMap = false; + debugDesc.autoGenerateMips = false; + debugDesc.enableRandomWrite = false; + debugDesc.clearBuffer = false; + TextureHandle debugTexture = renderGraph.CreateTexture(debugDesc); + + using (var builder = renderGraph.AddRasterRenderPass("SSR - Debug", out var passData)) + { + TextureHandle blackTexture = (TextureXR.slices > 1 && TextureXR.initialized) + ? renderGraph.defaultResources.blackTextureXR + : renderGraph.defaultResources.blackTexture; + + passData.material = m_Material; + passData.source = source; + passData.cameraDepth = cameraDepth; + passData.smoothnessTexture = smoothnessTexture; + passData.rayDistanceTexture = rayDistanceTexture.IsValid() ? rayDistanceTexture : blackTexture; + passData.sceneColor = sceneColor; + passData.sceneColorMotionVectors = sceneColorMotionVectors; + passData.blackTexture = blackTexture; + passData.viewMode = debugSettings.viewMode; + passData.sourceLastMipIndex = sourceDesc.useMipMap ? Mathf.Floor(Mathf.Log(Mathf.Max(sourceDesc.width, sourceDesc.height), 2)) : 0f; + passData.rayDistanceRange = Mathf.Max(debugSettings.rayDistanceRange, 0.01f); + passData.showSceneColor = debugSettings.showSceneColor; + passData.currentResolutionScale = ColorHistory.GetCurrentDynamicResolutionScale(cameraData); + passData.sceneColorResolutionScale = sceneColorResolutionScale; + + builder.SetRenderAttachment(debugTexture, 0); + builder.UseTexture(passData.source); + builder.UseTexture(passData.cameraDepth); + builder.UseTexture(passData.smoothnessTexture); + builder.UseTexture(passData.rayDistanceTexture); + builder.UseTexture(passData.sceneColor); + builder.UseTexture(passData.sceneColorMotionVectors); + builder.UseTexture(passData.blackTexture); + + builder.SetRenderFunc(static (data, ctx) => + { + data.material.SetTexture(ShaderConstants._CameraDepthTexture, data.cameraDepth); + data.material.SetTexture(ShaderConstants._SmoothnessTexture, data.smoothnessTexture); + data.material.SetTexture(ShaderPropertyId.screenSpaceReflectionRayDistance, data.rayDistanceTexture); + data.material.SetTexture(ShaderConstants._CameraColorTexture, ((RTHandle)data.sceneColor)?.rt == null ? data.blackTexture : data.sceneColor); + data.material.SetTexture(ShaderConstants._MotionVectorColorTexture, data.sceneColorMotionVectors); + data.material.SetVector(ShaderConstants._ResolutionScales, new Vector4( + data.currentResolutionScale.x, data.currentResolutionScale.y, + data.sceneColorResolutionScale.x, data.sceneColorResolutionScale.y)); + data.material.SetVector(ShaderConstants._DebugParams, new Vector4(data.sourceLastMipIndex, data.rayDistanceRange, data.showSceneColor ? 1f : 0f, (float)data.viewMode)); + Blitter.BlitTexture(ctx.cmd, data.source, Vector2.one, data.material, (int)ShaderPasses.Debug); + }); + } + + debugHandler.SetCustomDebugTexture(renderGraph, debugTexture); + } } } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/ScreenSpaceReflectionRendererFeature/ScreenSpaceReflectionRendererFeature.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/ScreenSpaceReflectionRendererFeature/ScreenSpaceReflectionRendererFeature.cs index 1a8b63af0dc..8d1e8532ef3 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/ScreenSpaceReflectionRendererFeature/ScreenSpaceReflectionRendererFeature.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/ScreenSpaceReflectionRendererFeature/ScreenSpaceReflectionRendererFeature.cs @@ -47,6 +47,10 @@ public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingD if (UniversalRenderer.IsOffscreenDepthTexture(universalCameraData)) return; + // Reflection probe captures don't need SSR. + if (universalCameraData.cameraType == CameraType.Reflection) + return; + // Only allow in preview cameras via the RenderRequest API (i.e. 'Cameras' overlay in scene view) // Don't allow regular preview cameras (i.e. thumbnails, material previews) if (universalCameraData.isPreviewCamera && !universalCameraData.camera.isProcessingRenderRequest) diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/ScreenSpaceReflectionRendererFeature/ScreenSpaceReflectionVolumeSettings.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/ScreenSpaceReflectionRendererFeature/ScreenSpaceReflectionVolumeSettings.cs index 86527255c73..bfcda59cb66 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/ScreenSpaceReflectionRendererFeature/ScreenSpaceReflectionVolumeSettings.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/ScreenSpaceReflectionRendererFeature/ScreenSpaceReflectionVolumeSettings.cs @@ -5,7 +5,8 @@ namespace UnityEngine.Rendering.Universal /// /// A volume component that holds settings for the Screen Space Reflections Renderer Feature. /// - [Serializable, VolumeComponentMenu("Lighting/Screen Space Reflection"), SupportedOnRenderPipeline] + [Serializable, VolumeComponentMenu("Lighting/Screen Space Reflection")] + [SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))] [DisplayInfo(name = "Screen Space Reflection")] [VolumeRequiresRendererFeatures(typeof(ScreenSpaceReflectionRendererFeature))] public class ScreenSpaceReflectionVolumeSettings : VolumeComponent diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/ScreenSpaceShadows.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/ScreenSpaceShadows.cs index 5d6df401ef7..ab56de90b2c 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/ScreenSpaceShadows.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/ScreenSpaceShadows.cs @@ -73,6 +73,8 @@ public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingD renderer.EnqueuePass(m_SSShadowsPass); renderer.EnqueuePass(m_SSShadowsPostPass); + // The resolve pass reconstructs the receiver from depth without a normal, so the receiver normal bias never reaches it + renderingData.shadowData.mainLightReceiverNormalBiasSkipped = true; } } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/AGENTS.md b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/AGENTS.md new file mode 100644 index 00000000000..03513c9a926 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/AGENTS.md @@ -0,0 +1,4 @@ +# Surface Cache GI renderer feature + +- The lighting rules in `Packages/com.unity.render-pipelines.core/Runtime/Lighting/AGENTS.md` apply here. +- The Surface Cache rules in `Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/AGENTS.md` apply here too, including where runtime tests live. diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/AGENTS.md.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/AGENTS.md.meta new file mode 100644 index 00000000000..de7cf48c840 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/AGENTS.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 9253e05ad635d42008f94fb982158301 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/CLAUDE.md b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/CLAUDE.md new file mode 100644 index 00000000000..43c994c2d36 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/CLAUDE.md.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/CLAUDE.md.meta new file mode 100644 index 00000000000..a7c236a2f4f --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/CLAUDE.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 472a85a09c047469da8a5db2dc8a894a +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/Debug.compute b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/Debug.compute index ad0eb900845..e280948c4f7 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/Debug.compute +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/Debug.compute @@ -15,12 +15,23 @@ #pragma kernel VisualizeMonoCompute VisualizeMono=VisualizeMonoCompute UNIFIED_RT_BACKEND_COMPUTE DISABLE_TEXTURE2D_X_ARRAY #pragma kernel VisualizeSinglePassStereoInstancingCompute VisualizeSinglePassStereoInstancing=VisualizeSinglePassStereoInstancingCompute UNIFIED_RT_BACKEND_COMPUTE -// This guard silences an unexpected compilation errors on MacOS. -#if !defined(SHADER_API_METAL) #pragma kernel VisualizeMonoHardware VisualizeMono=VisualizeMonoHardware UNIFIED_RT_BACKEND_HARDWARE DISABLE_TEXTURE2D_X_ARRAY #pragma kernel VisualizeSinglePassStereoInstancingHardware VisualizeSinglePassStereoInstancing=VisualizeSinglePassStereoInstancingHardware UNIFIED_RT_BACKEND_HARDWARE -#endif #pragma require inlineraytracing : UNIFIED_RT_BACKEND_HARDWARE +#pragma multi_compile_local SURFACE_CACHE_PATH_TRACING_TRANSPARENCY_MODE_OPAQUES_ONLY SURFACE_CACHE_PATH_TRACING_TRANSPARENCY_MODE_CUTOUTS +#pragma multi_compile _ _GBUFFER_NORMALS_OCT + +// The hardware ray tracing compute-shader variants in this file fails to compile on Metal with inlineraytracing +// enabled due to inlineraytracing requiring DXC over FXC compilation path. +// The DXC path fails to compile the expression 'float3 l1s[3]' in Common.hlsl +// as it generates invalid SPIR-V OpTypeVector due to the extra DXC+MTL flag +// '--convert-relaxed-to-half'. Requiring 'native16bit' on the variant removes +// that extra DXC flag, and enables successful DXC compilation, just like on VK. +// +// Todo(UUM-153535) : Remove once DXC + MTL compilation error is addressed +#if defined(SHADER_API_METAL) +#pragma require native16bit : UNIFIED_RT_BACKEND_HARDWARE +#endif #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/TextureXR.hlsl" @@ -51,21 +62,8 @@ TYPED_TEXTURE2D_X(float, _ScreenDepths); TYPED_TEXTURE2D_X(float3, _ScreenShadedNormals); TYPED_TEXTURE2D_X(float3, _ScreenFlatNormals); -uint _RingConfigOffset; -uint _VolumeSpatialResolution; -uint _VolumeCascadeCount; -uint _ViewMode; // Match the C# debug view-mode enum; 0 (None) is never dispatched. -uint _ShowSamplePosition; -float4x4 _ClipToWorldTransforms[2]; -uint _FrameIdx; -float _VolumeVoxelMinSize; -float3 _VolumeTargetPos; -int _PatchWarping; -float _MaterialAtlasTexelSize; // The size of 1 texel in the albedo atlas -uint _TileOffsetY; -uint _TileHeight; - -uint _DummyBlackbox; // By using a uniform we force the compiler to not make any assumptions. +#include "Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/DebugConstants.cs.hlsl" + float3 IsActuallyNan(float3 val) { return isnan(asfloat(_DummyBlackbox ^ asuint(val))); } @@ -88,7 +86,7 @@ float3 TraceMaterialProperty(uint2 pixelIdx, uint2 screenSize, uint globalThread ray.tMax = FLT_MAX; UnifiedRT::RayTracingAccelStruct accelStruct = UNIFIED_RT_GET_ACCEL_STRUCT(_RayTracingAccelerationStructure); - UnifiedRT::Hit hit = TraceRayClosestHit(globalThreadIndex, groupThreadIdx, accelStruct, ray); + UnifiedRT::Hit hit = TraceRayClosestHit(globalThreadIndex, groupThreadIdx, accelStruct, ray, _MaterialEntries, _AlbedoTextures, sampler_AlbedoTextures, _MaterialAtlasTexelSize); float3 result = 0.0f; if (hit.IsValid()) @@ -104,6 +102,36 @@ float3 TraceMaterialProperty(uint2 pixelIdx, uint2 screenSize, uint globalThread return result; } +float3 VisualizeWorldCulling(uint2 pixelIdx, uint2 screenSize, uint globalThreadIndex, uint groupThreadIdx, float nearClipValue) +{ + float3 result = 0.0f; + const float ndcDepth = LoadNdcDepth(_ScreenDepths, pixelIdx); + if (ndcDepth != invalidNdcDepth) + { + const float2 uv = (float2(pixelIdx) + 0.5f) / float2(screenSize); + const float4x4 clipToWorld = _ClipToWorldTransforms[unity_StereoEyeIndex]; + const float3 nearPos = ComputeWorldSpacePosition(uv, nearClipValue, clipToWorld); + const float3 surfacePos = ComputeWorldSpacePosition(uv, ndcDepth, clipToWorld); + const float surfaceDistance = length(surfacePos - nearPos); + const float tolerance = 0.05f + 0.01f * surfaceDistance; + + UnifiedRT::Ray ray; + ray.origin = nearPos; + ray.direction = (surfacePos - nearPos) / surfaceDistance; + ray.tMin = 0.0f; + ray.tMax = surfaceDistance + tolerance; + + UnifiedRT::RayTracingAccelStruct accelStruct = UNIFIED_RT_GET_ACCEL_STRUCT(_RayTracingAccelerationStructure); + UnifiedRT::Hit hit = TraceRayClosestHit(globalThreadIndex, groupThreadIdx, accelStruct, ray, _MaterialEntries, _AlbedoTextures, sampler_AlbedoTextures, _MaterialAtlasTexelSize); + const bool isInWorld = hit.IsValid() && hit.hitDistance >= surfaceDistance - tolerance; + + const float3 shadedNormal = UnpackNormalWSFromTexture(_ScreenShadedNormals[COORD_TEXTURE2D_X(pixelIdx)]); + const float shading = 0.3f + 0.7f * abs(dot(shadedNormal, ray.direction)); + result = (isInWorld ? float3(0.1f, 0.9f, 0.1f) : float3(0.9f, 0.1f, 0.1f)) * shading; + } + return result; +} + void Visualize(uint2 threadIdx, uint groupThreadIdx) { const float3 green = float3(0, 1, 0); @@ -155,6 +183,11 @@ void Visualize(uint2 threadIdx, uint groupThreadIdx) const uint globalThreadIndex = (unity_StereoEyeIndex * _TileHeight + threadIdx.y) * screenSize.x + threadIdx.x; output = TraceMaterialProperty(pixelIdx, screenSize, globalThreadIndex, groupThreadIdx, UNITY_NEAR_CLIP_VALUE, UNITY_RAW_FAR_CLIP_VALUE); } + else if (_ViewMode == 11) // world presence via primary rays + { + const uint globalThreadIndex = (unity_StereoEyeIndex * _TileHeight + threadIdx.y) * screenSize.x + threadIdx.x; + output = VisualizeWorldCulling(pixelIdx, screenSize, globalThreadIndex, groupThreadIdx, UNITY_NEAR_CLIP_VALUE); + } else { const float ndcDepth = LoadNdcDepth(_ScreenDepths, pixelIdx); @@ -167,7 +200,7 @@ void Visualize(uint2 threadIdx, uint groupThreadIdx) const float3 worldFlatNormal = _ScreenFlatNormals[COORD_TEXTURE2D_X(pixelIdx)]; PatchUtil::VolumeParamSet volumeParams; - volumeParams.targetPos = _VolumeTargetPos; + volumeParams.targetPos = _VolumeTargetPos.xyz; volumeParams.spatialResolution = _VolumeSpatialResolution; volumeParams.voxelMinSize = _VolumeVoxelMinSize; volumeParams.cascadeOffsets = _VolumeCascadeOffsets; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/DebugConstants.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/DebugConstants.cs new file mode 100644 index 00000000000..6e3387e0b27 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/DebugConstants.cs @@ -0,0 +1,26 @@ +namespace UnityEngine.Rendering.Universal +{ + [GenerateHLSL(needAccessors = false, generateCBuffer = true)] + internal unsafe struct SurfaceCacheGIDebugConstants + { + [HLSLArray(2, typeof(Matrix4x4))] + public fixed float _ClipToWorldTransforms[2 * 16]; + + public Vector4 _VolumeTargetPos; // xyz: position, w: unused. + + public uint _RingConfigOffset; + public uint _VolumeSpatialResolution; + public uint _VolumeCascadeCount; + public uint _ViewMode; // Match the C# debug view-mode enum; 0 (None) is never dispatched. + + public uint _ShowSamplePosition; + public uint _FrameIdx; + public int _PatchWarping; + public float _MaterialAtlasTexelSize; // The size of 1 texel in the albedo atlas. + + public uint _TileOffsetY; + public uint _TileHeight; + public uint _DummyBlackbox; // Always zero. Read through a constant so the compiler can't make assumptions about it. + public float _VolumeVoxelMinSize; + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/DebugConstants.cs.hlsl b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/DebugConstants.cs.hlsl new file mode 100644 index 00000000000..e9c4aa485fb --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/DebugConstants.cs.hlsl @@ -0,0 +1,27 @@ +// +// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead +// + +#ifndef SURFACECACHEGIDEBUGCONSTANTS_CS_HLSL +#define SURFACECACHEGIDEBUGCONSTANTS_CS_HLSL +// Generated from UnityEngine.Rendering.Universal.SurfaceCacheGIDebugConstants +// PackingRules = Exact +CBUFFER_START(SurfaceCacheGIDebugConstants) + float4x4 _ClipToWorldTransforms[2]; + float4 _VolumeTargetPos; + uint _RingConfigOffset; + uint _VolumeSpatialResolution; + uint _VolumeCascadeCount; + uint _ViewMode; + uint _ShowSamplePosition; + uint _FrameIdx; + int _PatchWarping; + float _MaterialAtlasTexelSize; + uint _TileOffsetY; + uint _TileHeight; + uint _DummyBlackbox; + float _VolumeVoxelMinSize; +CBUFFER_END + + +#endif diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/DebugConstants.cs.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/DebugConstants.cs.hlsl.meta new file mode 100644 index 00000000000..f459c291c3f --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/DebugConstants.cs.hlsl.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 17effbd4bf41d40e886c563b6339c8e6 +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/DebugConstants.cs.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/DebugConstants.cs.meta new file mode 100644 index 00000000000..eff4217ad48 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/DebugConstants.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 0f7d620b6500e437fbc23d49edcee38d \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/FlatNormalResolution.compute b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/FlatNormalResolution.compute index 89b3bf04601..28b23af8893 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/FlatNormalResolution.compute +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/FlatNormalResolution.compute @@ -10,7 +10,7 @@ TYPED_TEXTURE2D_X(float, _ScreenDepths); RW_TEXTURE2D_X(float3, _ScreenFlatNormals); -float4x4 _ClipToWorldTransforms[2]; +#include "Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/FlatNormalResolutionConstants.cs.hlsl" struct PixelInfo { diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/FlatNormalResolutionConstants.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/FlatNormalResolutionConstants.cs new file mode 100644 index 00000000000..4e5949f260f --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/FlatNormalResolutionConstants.cs @@ -0,0 +1,9 @@ +namespace UnityEngine.Rendering.Universal +{ + [GenerateHLSL(needAccessors = false, generateCBuffer = true)] + internal unsafe struct SurfaceCacheGIFlatNormalResolutionConstants + { + [HLSLArray(2, typeof(Matrix4x4))] + public fixed float _ClipToWorldTransforms[2 * 16]; + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/FlatNormalResolutionConstants.cs.hlsl b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/FlatNormalResolutionConstants.cs.hlsl new file mode 100644 index 00000000000..1f288fd4d8f --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/FlatNormalResolutionConstants.cs.hlsl @@ -0,0 +1,14 @@ +// +// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead +// + +#ifndef SURFACECACHEGIFLATNORMALRESOLUTIONCONSTANTS_CS_HLSL +#define SURFACECACHEGIFLATNORMALRESOLUTIONCONSTANTS_CS_HLSL +// Generated from UnityEngine.Rendering.Universal.SurfaceCacheGIFlatNormalResolutionConstants +// PackingRules = Exact +CBUFFER_START(SurfaceCacheGIFlatNormalResolutionConstants) + float4x4 _ClipToWorldTransforms[2]; +CBUFFER_END + + +#endif diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/FlatNormalResolutionConstants.cs.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/FlatNormalResolutionConstants.cs.hlsl.meta new file mode 100644 index 00000000000..f79ef438e1f --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/FlatNormalResolutionConstants.cs.hlsl.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 652e42834a6d242cbbad4f02ad8b9475 +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/FlatNormalResolutionConstants.cs.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/FlatNormalResolutionConstants.cs.meta new file mode 100644 index 00000000000..29aa06846e4 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/FlatNormalResolutionConstants.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 15c4e062ad42a4f58ac99afee2bfd5ab \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/PatchAllocation.compute b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/PatchAllocation.compute index c7cf2b811b6..0a2bd3e4f6e 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/PatchAllocation.compute +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/PatchAllocation.compute @@ -1,6 +1,7 @@ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal glcore ps5 switch2 #pragma kernel AllocateMono DISABLE_TEXTURE2D_X_ARRAY #pragma kernel AllocateSinglePassStereoInstancing +#pragma multi_compile _ _EXPOSURE #define PATCH_UTIL_USE_RW_PATCH_IRRADIANCE_BUFFER #define PATCH_UTIL_USE_RW_CELL_PATCH_INDEX_BUFFER @@ -12,7 +13,9 @@ #include "Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/VectorLogic.hlsl" #include "Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/IrradianceCompression.hlsl" #include "Packages/com.unity.render-pipelines.core/Runtime/Lighting/SurfaceCache/PatchUtil.hlsl" +#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/ExposureFunctions.hlsl" +Texture2D _ExposureMultiplier; RWStructuredBuffer _RingConfigBuffer; RWStructuredBuffer _PatchGeometries; RWStructuredBuffer _PatchStatistics; @@ -32,18 +35,7 @@ TYPED_TEXTURE2D_X(float3, _PreviousLowResScreenIrradiancesL11); TYPED_TEXTURE2D_X(float3, _PreviousLowResScreenIrradiancesL12); TYPED_TEXTURE2D_X(float, _PreviousLowResScreenNdcDepths); -uint _FrameIdx; -uint _StereoEyeIndex; -uint _VolumeSpatialResolution; -float _VolumeVoxelMinSize; -uint _VolumeCascadeCount; -uint _RingConfigOffset; -float4x4 _CurrentClipToWorldTransforms[2]; -float4x4 _PreviousClipToWorldTransforms[2]; -float3 _VolumeTargetPos; -uint2 _LowResScreenSize; -uint2 _FullResPixelOffset; -int _PatchWarping; +#include "Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/PatchAllocationConstants.cs.hlsl" uint CountLeadingZeroes(uint x) { @@ -118,7 +110,7 @@ void Allocate(uint2 lowResPixelPos) const float3 sourceWorldFlatNormal = _CurrentFullResScreenFlatNormals[COORD_TEXTURE2D_X(fullResPixelPos)]; PatchUtil::VolumeParamSet volumeParams; - volumeParams.targetPos = _VolumeTargetPos; + volumeParams.targetPos = _VolumeTargetPos.xyz; volumeParams.spatialResolution = _VolumeSpatialResolution; volumeParams.voxelMinSize = _VolumeVoxelMinSize; volumeParams.cascadeOffsets = _VolumeCascadeOffsets; @@ -188,7 +180,11 @@ void Allocate(uint2 lowResPixelPos) seedLowResPixelPos); if (PatchUtil::IsValid(irradianceSeed)) + { + // Screen irradiances are pre-exposed, patch irradiances are not. + SphericalHarmonics::MulMut(irradianceSeed, GetInvPreExposureMultiplier(_ExposureMultiplier)); patchUpdateCount = PatchUtil::updateMax / 2; + } } } } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/PatchAllocationConstants.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/PatchAllocationConstants.cs new file mode 100644 index 00000000000..36f5a29d2b4 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/PatchAllocationConstants.cs @@ -0,0 +1,28 @@ +using Unity.Mathematics; + +namespace UnityEngine.Rendering.Universal +{ + [GenerateHLSL(needAccessors = false, generateCBuffer = true)] + internal unsafe struct SurfaceCacheGIPatchAllocationConstants + { + [HLSLArray(2, typeof(Matrix4x4))] + public fixed float _CurrentClipToWorldTransforms[2 * 16]; + [HLSLArray(2, typeof(Matrix4x4))] + public fixed float _PreviousClipToWorldTransforms[2 * 16]; + + public Vector4 _VolumeTargetPos; // xyz: position, w: unused. + + public uint _FrameIdx; + public uint _StereoEyeIndex; + public uint _VolumeSpatialResolution; + public uint _VolumeCascadeCount; + + public uint2 _LowResScreenSize; + public uint2 _FullResPixelOffset; + + public uint _RingConfigOffset; + public int _PatchWarping; + public float _VolumeVoxelMinSize; + public uint _PatchAllocationPad0; + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/PatchAllocationConstants.cs.hlsl b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/PatchAllocationConstants.cs.hlsl new file mode 100644 index 00000000000..b774ac58c54 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/PatchAllocationConstants.cs.hlsl @@ -0,0 +1,26 @@ +// +// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead +// + +#ifndef SURFACECACHEGIPATCHALLOCATIONCONSTANTS_CS_HLSL +#define SURFACECACHEGIPATCHALLOCATIONCONSTANTS_CS_HLSL +// Generated from UnityEngine.Rendering.Universal.SurfaceCacheGIPatchAllocationConstants +// PackingRules = Exact +CBUFFER_START(SurfaceCacheGIPatchAllocationConstants) + float4x4 _CurrentClipToWorldTransforms[2]; + float4x4 _PreviousClipToWorldTransforms[2]; + float4 _VolumeTargetPos; + uint _FrameIdx; + uint _StereoEyeIndex; + uint _VolumeSpatialResolution; + uint _VolumeCascadeCount; + uint2 _LowResScreenSize; + uint2 _FullResPixelOffset; + uint _RingConfigOffset; + int _PatchWarping; + float _VolumeVoxelMinSize; + uint _PatchAllocationPad0; +CBUFFER_END + + +#endif diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/PatchAllocationConstants.cs.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/PatchAllocationConstants.cs.hlsl.meta new file mode 100644 index 00000000000..483dbf8ff6d --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/PatchAllocationConstants.cs.hlsl.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: adf31eca191a1485ebc75b3f84759cf0 +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/PatchAllocationConstants.cs.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/PatchAllocationConstants.cs.meta new file mode 100644 index 00000000000..7d809d4ca9d --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/PatchAllocationConstants.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c0eda5fa7d6294b3182bfef9f2182724 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveDenoising.compute b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveDenoising.compute index eb148d77654..3241c91fdbb 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveDenoising.compute +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveDenoising.compute @@ -22,9 +22,7 @@ RW_TEXTURE2D_X(float3, _ResultL10); RW_TEXTURE2D_X(float3, _ResultL11); RW_TEXTURE2D_X(float3, _ResultL12); -float4x4 _ClipToWorldTransforms[2]; -float3 _CameraWorldPos; -int _PassIndex; +#include "Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveDenoisingConstants.cs.hlsl" static const uint kKernelStrides[4] = { 1, 2, 2, 3 }; @@ -66,7 +64,7 @@ void Denoise(uint2 pixelLowResPos) // At a distance of N from the camera, the falloff rate of the plane distance // weight is such that it has half weight (0.5) at a distance N/100. const float k_PlaneDistanceFalloff = 0.6931472f / (0.01f * 0.01f); - const float3 centerToCamera = _CameraWorldPos - centerWorldPos; + const float3 centerToCamera = _CameraWorldPos.xyz - centerWorldPos; const float planeDistanceFalloff = k_PlaneDistanceFalloff * rcp(dot(centerToCamera, centerToCamera)); irradianceSum = centerIrradiance; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveDenoisingConstants.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveDenoisingConstants.cs new file mode 100644 index 00000000000..8667186836d --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveDenoisingConstants.cs @@ -0,0 +1,16 @@ +namespace UnityEngine.Rendering.Universal +{ + [GenerateHLSL(needAccessors = false, generateCBuffer = true)] + internal unsafe struct SurfaceCacheGIScreenResolveDenoisingConstants + { + [HLSLArray(2, typeof(Matrix4x4))] + public fixed float _ClipToWorldTransforms[2 * 16]; + + public Vector4 _CameraWorldPos; // xyz: position, w: unused. + + public int _PassIndex; + public uint _ScreenResolveDenoisingPad0; + public uint _ScreenResolveDenoisingPad1; + public uint _ScreenResolveDenoisingPad2; + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveDenoisingConstants.cs.hlsl b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveDenoisingConstants.cs.hlsl new file mode 100644 index 00000000000..d143d6e8055 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveDenoisingConstants.cs.hlsl @@ -0,0 +1,19 @@ +// +// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead +// + +#ifndef SURFACECACHEGISCREENRESOLVEDENOISINGCONSTANTS_CS_HLSL +#define SURFACECACHEGISCREENRESOLVEDENOISINGCONSTANTS_CS_HLSL +// Generated from UnityEngine.Rendering.Universal.SurfaceCacheGIScreenResolveDenoisingConstants +// PackingRules = Exact +CBUFFER_START(SurfaceCacheGIScreenResolveDenoisingConstants) + float4x4 _ClipToWorldTransforms[2]; + float4 _CameraWorldPos; + int _PassIndex; + uint _ScreenResolveDenoisingPad0; + uint _ScreenResolveDenoisingPad1; + uint _ScreenResolveDenoisingPad2; +CBUFFER_END + + +#endif diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveDenoisingConstants.cs.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveDenoisingConstants.cs.hlsl.meta new file mode 100644 index 00000000000..e92ffe675e3 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveDenoisingConstants.cs.hlsl.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 9d18fd2543b4043598a315aa0024084d +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveDenoisingConstants.cs.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveDenoisingConstants.cs.meta new file mode 100644 index 00000000000..c1889f788a7 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveDenoisingConstants.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 060ab94b6f76a4503a3a8cc440272e78 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveLookup.compute b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveLookup.compute index 6c39d43dd17..c2bdab8d1bf 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveLookup.compute +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveLookup.compute @@ -29,14 +29,7 @@ StructuredBuffer _CellPatchIndices; StructuredBuffer _VolumeCascadeOffsets; StructuredBuffer _GlobalProbe; -uint _VolumeSpatialResolution; -uint _VolumeCascadeCount; -uint _SampleCount; -float _VolumeVoxelMinSize; -float4x4 _ClipToWorldTransforms[2]; -float3 _VolumeTargetPos; -int _PatchWarping; -uint _DistanceFallback; +#include "Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveLookupConstants.cs.hlsl" #define GROUP_SIZE 8 @@ -102,14 +95,14 @@ void Lookup(uint2 lowResPixelPos) rng.Init(lowResPixelPos, 0); PatchUtil::VolumeParamSet volumeParams; - volumeParams.targetPos = _VolumeTargetPos; + volumeParams.targetPos = _VolumeTargetPos.xyz; volumeParams.spatialResolution = _VolumeSpatialResolution; volumeParams.voxelMinSize = _VolumeVoxelMinSize; volumeParams.cascadeOffsets = _VolumeCascadeOffsets; volumeParams.cascadeCount = _VolumeCascadeCount; volumeParams.patchWarping = _PatchWarping != 0; - const int cascadeResolution = PatchUtil::ResolveCascadeIndex(_VolumeTargetPos, worldPos, _VolumeSpatialResolution, _VolumeCascadeCount, _VolumeVoxelMinSize); + const int cascadeResolution = PatchUtil::ResolveCascadeIndex(_VolumeTargetPos.xyz, worldPos, _VolumeSpatialResolution, _VolumeCascadeCount, _VolumeVoxelMinSize); const uint cascadeIdx = cascadeResolution == -1 ? _VolumeCascadeCount - 1 : cascadeResolution; const float voxelSize = PatchUtil::GetVoxelSize(_VolumeVoxelMinSize, cascadeIdx); diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveLookupConstants.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveLookupConstants.cs new file mode 100644 index 00000000000..19a3817827b --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveLookupConstants.cs @@ -0,0 +1,21 @@ +namespace UnityEngine.Rendering.Universal +{ + [GenerateHLSL(needAccessors = false, generateCBuffer = true)] + internal unsafe struct SurfaceCacheGIScreenResolveLookupConstants + { + [HLSLArray(2, typeof(Matrix4x4))] + public fixed float _ClipToWorldTransforms[2 * 16]; + + public Vector4 _VolumeTargetPos; // xyz: position, w: unused. + + public uint _VolumeSpatialResolution; + public uint _VolumeCascadeCount; + public uint _SampleCount; + public int _PatchWarping; + + public uint _DistanceFallback; + public float _VolumeVoxelMinSize; + public uint _ScreenResolveLookupPad0; + public uint _ScreenResolveLookupPad1; + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveLookupConstants.cs.hlsl b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveLookupConstants.cs.hlsl new file mode 100644 index 00000000000..c959edd27b1 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveLookupConstants.cs.hlsl @@ -0,0 +1,23 @@ +// +// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead +// + +#ifndef SURFACECACHEGISCREENRESOLVELOOKUPCONSTANTS_CS_HLSL +#define SURFACECACHEGISCREENRESOLVELOOKUPCONSTANTS_CS_HLSL +// Generated from UnityEngine.Rendering.Universal.SurfaceCacheGIScreenResolveLookupConstants +// PackingRules = Exact +CBUFFER_START(SurfaceCacheGIScreenResolveLookupConstants) + float4x4 _ClipToWorldTransforms[2]; + float4 _VolumeTargetPos; + uint _VolumeSpatialResolution; + uint _VolumeCascadeCount; + uint _SampleCount; + int _PatchWarping; + uint _DistanceFallback; + float _VolumeVoxelMinSize; + uint _ScreenResolveLookupPad0; + uint _ScreenResolveLookupPad1; +CBUFFER_END + + +#endif diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveLookupConstants.cs.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveLookupConstants.cs.hlsl.meta new file mode 100644 index 00000000000..7d7eca63c1e --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveLookupConstants.cs.hlsl.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: df14ae5c54a6848a88a7a0833d5ad3b5 +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveLookupConstants.cs.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveLookupConstants.cs.meta new file mode 100644 index 00000000000..9a2bb7d52b8 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveLookupConstants.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 15b53546ba78449b981041b1d940c682 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveUpsampling.compute b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveUpsampling.compute index f50cb4f0a05..df2d734bc4e 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveUpsampling.compute +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveUpsampling.compute @@ -2,6 +2,7 @@ #pragma kernel UpsampleMono DISABLE_TEXTURE2D_X_ARRAY #pragma kernel UpsampleSinglePassStereoInstancing +#pragma multi_compile _ _GBUFFER_NORMALS_OCT #define GROUP_SHARED_CACHE @@ -23,9 +24,7 @@ TYPED_TEXTURE2D_X(float3, _LowResIrradiancesL11); TYPED_TEXTURE2D_X(float3, _LowResIrradiancesL12); RW_TEXTURE2D_X(float4, _FullResIrradiances); -float _Intensity; -float4x4 _ClipToWorldTransforms[2]; -float3 _CameraWorldPos; +#include "Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveUpsamplingConstants.cs.hlsl" #define UPSAMPLE_TILE_SIZE 8 @@ -117,7 +116,7 @@ void Upsample(uint2 targetPixelPos, int groupIndex, uint2 groupId) // At a distance of N from the camera, the falloff rate of the plane distance // weight is such that it has half weight (0.5) at a distance N/100. const float k_PlaneDistanceFalloff = 0.6931472f / (0.01f * 0.01f); - const float3 targetToCamera = _CameraWorldPos - fullResWorldPos; + const float3 targetToCamera = _CameraWorldPos.xyz - fullResWorldPos; const float planeDistanceFalloff = k_PlaneDistanceFalloff * rcp(dot(targetToCamera, targetToCamera)); float weightSum = 0.0f; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveUpsamplingConstants.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveUpsamplingConstants.cs new file mode 100644 index 00000000000..19d94faaa58 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveUpsamplingConstants.cs @@ -0,0 +1,16 @@ +namespace UnityEngine.Rendering.Universal +{ + [GenerateHLSL(needAccessors = false, generateCBuffer = true)] + internal unsafe struct SurfaceCacheGIScreenResolveUpsamplingConstants + { + [HLSLArray(2, typeof(Matrix4x4))] + public fixed float _ClipToWorldTransforms[2 * 16]; + + public Vector4 _CameraWorldPos; // xyz: position, w: unused. + + public float _Intensity; + public uint _ScreenResolveUpsamplingPad0; + public uint _ScreenResolveUpsamplingPad1; + public uint _ScreenResolveUpsamplingPad2; + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveUpsamplingConstants.cs.hlsl b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveUpsamplingConstants.cs.hlsl new file mode 100644 index 00000000000..400bf856f99 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveUpsamplingConstants.cs.hlsl @@ -0,0 +1,19 @@ +// +// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead +// + +#ifndef SURFACECACHEGISCREENRESOLVEUPSAMPLINGCONSTANTS_CS_HLSL +#define SURFACECACHEGISCREENRESOLVEUPSAMPLINGCONSTANTS_CS_HLSL +// Generated from UnityEngine.Rendering.Universal.SurfaceCacheGIScreenResolveUpsamplingConstants +// PackingRules = Exact +CBUFFER_START(SurfaceCacheGIScreenResolveUpsamplingConstants) + float4x4 _ClipToWorldTransforms[2]; + float4 _CameraWorldPos; + float _Intensity; + uint _ScreenResolveUpsamplingPad0; + uint _ScreenResolveUpsamplingPad1; + uint _ScreenResolveUpsamplingPad2; +CBUFFER_END + + +#endif diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveUpsamplingConstants.cs.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveUpsamplingConstants.cs.hlsl.meta new file mode 100644 index 00000000000..a438465e412 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveUpsamplingConstants.cs.hlsl.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 648d5b7506d1e44f895b8e0dd5e3b755 +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveUpsamplingConstants.cs.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveUpsamplingConstants.cs.meta new file mode 100644 index 00000000000..531ec742fa9 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/ScreenResolveUpsamplingConstants.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: aa10fc57ab82942f08f88e1617a46b41 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/SurfaceCacheEntityChangeBridge.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/SurfaceCacheEntityChangeBridge.cs index f8f13beb326..abfacc0d5f9 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/SurfaceCacheEntityChangeBridge.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/SurfaceCacheEntityChangeBridge.cs @@ -1,6 +1,7 @@ #if SURFACE_CACHE_SUPPORTED || UNITY_EDITOR using System; +using System.Collections.Generic; using Unity.Burst; using Unity.Collections; using Unity.Jobs; @@ -15,6 +16,7 @@ static class SurfaceCacheEntityChangeBridge static NativeList s_PendingChanged; static NativeHashMap s_PendingChangedIndex; static NativeList s_PendingMaterials; + static NativeList s_PendingOverrides; static NativeList s_PendingDestroyed; static NativeList s_PendingTransforms; @@ -26,12 +28,75 @@ static class SurfaceCacheEntityChangeBridge static bool s_FoldNeeded; static uint s_ConsumerVersion; static JobHandle s_TransformJob; + static SurfaceCacheCullingObserver[] s_CullingObservers = Array.Empty(); + static int s_CullingObserverCount; public static bool IsConsumerPresent => s_ConsumerRegistered; // Producers push their full state again when this changes, so a recreated consumer starts complete. public static uint ConsumerVersion => s_ConsumerVersion; + public static ReadOnlySpan CullingObservers => new(s_CullingObservers, 0, s_CullingObserverCount); + + struct CullingStatistics + { + public int TrackedEntityCount; + public int CulledEntityCount; + public int TrackedChunkCount; + public int CulledChunkCount; + } + + static readonly Dictionary s_CullingStatistics = new(); + + public static int TrackedEntityCount { get; private set; } + public static int CulledEntityCount { get; private set; } + public static int TrackedChunkCount { get; private set; } + public static int CulledChunkCount { get; private set; } + + public static void SetCullingObservers(ReadOnlySpan observers) + { + if (s_CullingObservers.Length < observers.Length) + s_CullingObservers = new SurfaceCacheCullingObserver[observers.Length]; + + observers.CopyTo(s_CullingObservers); + s_CullingObserverCount = observers.Length; + } + + public static void ReportCullingStatistics(ulong producer, int trackedEntityCount, int culledEntityCount, int trackedChunkCount, int culledChunkCount) + { + s_CullingStatistics[producer] = new CullingStatistics + { + TrackedEntityCount = trackedEntityCount, + CulledEntityCount = culledEntityCount, + TrackedChunkCount = trackedChunkCount, + CulledChunkCount = culledChunkCount, + }; + SumCullingStatistics(); + } + + public static void RemoveCullingStatistics(ulong producer) + { + if (s_CullingStatistics.Remove(producer)) + SumCullingStatistics(); + } + + static void SumCullingStatistics() + { + int trackedEntityCount = 0, culledEntityCount = 0, trackedChunkCount = 0, culledChunkCount = 0; + foreach (var statistics in s_CullingStatistics.Values) + { + trackedEntityCount += statistics.TrackedEntityCount; + culledEntityCount += statistics.CulledEntityCount; + trackedChunkCount += statistics.TrackedChunkCount; + culledChunkCount += statistics.CulledChunkCount; + } + + TrackedEntityCount = trackedEntityCount; + CulledEntityCount = culledEntityCount; + TrackedChunkCount = trackedChunkCount; + CulledChunkCount = culledChunkCount; + } + public static bool TryRegisterConsumer() { if (s_ConsumerRegistered) @@ -42,6 +107,7 @@ public static bool TryRegisterConsumer() s_PendingChanged = new NativeList(Allocator.Persistent); s_PendingChangedIndex = new NativeHashMap(64, Allocator.Persistent); s_PendingMaterials = new NativeList(Allocator.Persistent); + s_PendingOverrides = new NativeList(Allocator.Persistent); s_PendingDestroyed = new NativeList(Allocator.Persistent); s_PendingTransforms = new NativeList(Allocator.Persistent); ClearPending(); @@ -55,12 +121,16 @@ public static void UnregisterConsumer() CompleteTransformJob(); s_ConsumerRegistered = false; s_DrainInProgress = false; + s_CullingObserverCount = 0; + s_CullingStatistics.Clear(); + SumCullingStatistics(); if (s_PendingTransforms.IsCreated) { s_PendingChanged.Dispose(); s_PendingChangedIndex.Dispose(); s_PendingMaterials.Dispose(); + s_PendingOverrides.Dispose(); s_PendingDestroyed.Dispose(); s_PendingTransforms.Dispose(); } @@ -108,12 +178,17 @@ static void MarkPushOutsideProducerPass() } public static void PushChanged(in SurfaceCacheEntityInstanceRecord record, ReadOnlySpan materials) + { + PushChanged(record, materials, ReadOnlySpan.Empty); + } + + public static void PushChanged(in SurfaceCacheEntityInstanceRecord record, ReadOnlySpan materials, ReadOnlySpan overrides) { if (!IsConsumerPresent) return; MarkPushOutsideProducerPass(); - Writer.PushChanged(record, materials); + Writer.PushChanged(record, materials, overrides); } // For jobs that push records. Unavailable without a consumer or during a drain, whose views a push would invalidate. @@ -129,6 +204,7 @@ public static bool TryAcquireChangeWriter(out SurfaceCacheEntityChangeWriter wri Changed = s_PendingChanged, Index = s_PendingChangedIndex, Materials = s_PendingMaterials, + Overrides = s_PendingOverrides, Transforms = s_PendingTransforms, }; @@ -155,6 +231,7 @@ public static void PushDestroyed(in EntityId key) public static void BeginDrain( out NativeArray changed, out NativeArray changedMaterials, + out NativeArray changedOverrides, out NativeArray destroyed, out NativeArray transformChanged) { @@ -167,6 +244,7 @@ public static void BeginDrain( changed = s_PendingChanged.AsArray(); changedMaterials = s_PendingMaterials.AsArray(); + changedOverrides = s_PendingOverrides.AsArray(); destroyed = s_PendingDestroyed.AsArray(); transformChanged = s_PendingTransforms.AsArray(); } @@ -257,6 +335,7 @@ static void ClearPending() s_PendingChanged.Clear(); s_PendingMaterials.Clear(); + s_PendingOverrides.Clear(); s_PendingDestroyed.Clear(); s_FoldNeeded = false; @@ -270,43 +349,50 @@ struct SurfaceCacheEntityChangeWriter public NativeList Changed; public NativeHashMap Index; public NativeList Materials; + public NativeList Overrides; public NativeList Transforms; - public void PushChanged(in SurfaceCacheEntityInstanceRecord record, ReadOnlySpan materials) + public void PushChanged(in SurfaceCacheEntityInstanceRecord record, ReadOnlySpan materials, ReadOnlySpan overrides) { var stored = record; stored.MaterialsCount = materials.Length; + stored.OverridesCount = overrides.Length; stored.TransformsBefore = Transforms.Length; - // Avoids re-appending when a key's assignment count does not grow. if (Index.TryGetValue(record.Key, out int at)) { var previous = Changed[at]; - if (previous.MaterialsCount >= materials.Length) - { - for (int i = 0; i < materials.Length; i++) - Materials[previous.MaterialsStart + i] = materials[i]; - - stored.MaterialsStart = previous.MaterialsStart; - } - else - { - stored.MaterialsStart = Materials.Length; - for (int i = 0; i < materials.Length; i++) - Materials.Add(materials[i]); - } - + stored.MaterialsStart = Store(Materials, materials, previous.MaterialsStart, previous.MaterialsCount); + stored.OverridesStart = Store(Overrides, overrides, previous.OverridesStart, previous.OverridesCount); Changed[at] = stored; return; } - stored.MaterialsStart = Materials.Length; - for (int i = 0; i < materials.Length; i++) - Materials.Add(materials[i]); + stored.MaterialsStart = Store(Materials, materials, 0, 0); + stored.OverridesStart = Store(Overrides, overrides, 0, 0); Index.Add(record.Key, Changed.Length); Changed.Add(stored); } + + // Avoids re-appending when a key's previous range is large enough. + static int Store(NativeList list, ReadOnlySpan values, int previousStart, int previousCount) + where T : unmanaged + { + if (previousCount >= values.Length) + { + for (int i = 0; i < values.Length; i++) + list[previousStart + i] = values[i]; + + return previousStart; + } + + int start = list.Length; + for (int i = 0; i < values.Length; i++) + list.Add(values[i]); + + return start; + } } sealed class EntityChangeSource : IDisposable @@ -322,7 +408,7 @@ sealed class EntityChangeSource : IDisposable bool m_DrainBegun; bool m_ContentionLogged; - bool TryAcquireBridge() + public bool TryAcquireBridge() { if (!m_BridgeAcquired) m_BridgeAcquired = SurfaceCacheEntityChangeBridge.TryRegisterConsumer(); @@ -345,11 +431,12 @@ public void CollectChanges(SurfaceCacheWorldChangeSet changeSet) return; } - SurfaceCacheEntityChangeBridge.BeginDrain(out var changed, out var materials, out var destroyed, out var transformChanged); + SurfaceCacheEntityChangeBridge.BeginDrain(out var changed, out var materials, out var overrides, out var destroyed, out var transformChanged); m_DrainBegun = true; changeSet.EntityInstanceChangedList = changed; changeSet.EntityInstanceMaterialList = materials; + changeSet.EntityInstanceMaterialOverrideList = overrides; changeSet.EntityInstanceDestroyedList = destroyed; changeSet.EntityInstanceTransformChangedList = transformChanged; } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/SurfaceCacheEntityRecords.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/SurfaceCacheEntityRecords.cs index 0f1237f7c57..0cfaf6c9baf 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/SurfaceCacheEntityRecords.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/SurfaceCacheEntityRecords.cs @@ -1,5 +1,7 @@ #if SURFACE_CACHE_SUPPORTED || UNITY_EDITOR +using Unity.Mathematics; + namespace UnityEngine.Rendering.Universal { struct SurfaceCacheSubMeshMaterial @@ -8,13 +10,24 @@ struct SurfaceCacheSubMeshMaterial public EntityId Material; } + // Value as the shader receives it, so colors are in the active color space. + struct SurfaceCacheMaterialOverride + { + public int NameId; + public Vector4 Value; + } + struct SurfaceCacheEntityInstanceRecord { public EntityId Key; public EntityId Mesh; + public int MeshLod; // Into the buffer this record was drained with, so valid only until that buffer is reused. public int MaterialsStart; public int MaterialsCount; + // Into the buffer this record was drained with, like the materials. Applies to every submesh. + public int OverridesStart; + public int OverridesCount; // Pending transforms below this index were pushed before this record. public int TransformsBefore; public Matrix4x4 LocalToWorld; @@ -27,6 +40,13 @@ struct SurfaceCacheEntityTransformRecord public EntityId Key; public Matrix4x4 LocalToWorld; } + + struct SurfaceCacheCullingObserver + { + public float3 Position; + public float MaxDistance; + public float MinAngle; + } } #endif diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/SurfaceCacheGIRendererFeature.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/SurfaceCacheGIRendererFeature.cs index 6433085f0a4..8acc7e89f31 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/SurfaceCacheGIRendererFeature.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/SurfaceCacheGIRendererFeature.cs @@ -97,8 +97,26 @@ public ComputeShader screenResolveDenoisingShader /// Use the volume component to control the effect. /// [DisallowMultipleRendererFeature("Surface Cache Global Illumination")] - public class SurfaceCacheGIRendererFeature : ScriptableRendererFeature + public partial class SurfaceCacheGIRendererFeature : ScriptableRendererFeature { + internal enum MaterialResolution + { + VeryLow = 16, + Low = 32, + Medium = 64, + High = 128, + VeryHigh = 256, + } + + [SerializeField] + MaterialResolution m_MaterialResolution = MaterialResolution.Medium; + + internal MaterialResolution materialResolution + { + get => m_MaterialResolution; + set => m_MaterialResolution = value; + } + internal static readonly string k_StaticBatchingErrorMesssage = "Surface Cache GI cannot run because it is incompatible with Static Batching. You can disable the option in the Player Settings."; internal static readonly string k_MeshBufferTargetErrorMessage = "Surface Cache GI requires access to raw mesh buffers. Set Default Mesh Buffer Target to Raw in the Graphics Settings."; @@ -146,6 +164,41 @@ internal static bool IsEligibleCamera(Camera camera) return false; } + internal static float GetEntityCullingMaxDistance(in VolumeParameterSet volumeParams) + { + switch (volumeParams.EntityCullingSphereMode) + { + case SurfaceCacheGIVolumeOverride.EntityCullingSphereMode.Fixed: + return volumeParams.EntityCullingDistance; + case SurfaceCacheGIVolumeOverride.EntityCullingSphereMode.VolumePlusMargin: + return 0.5f * volumeParams.VolumeSize + volumeParams.EntityCullingDistanceMargin; + default: + return float.PositiveInfinity; + } + } + + internal static float GetEntityCullingMinAngle(Camera camera, in VolumeParameterSet volumeParams) + { + switch (volumeParams.EntityCullingSmallObjectUnit) + { + case SurfaceCacheGIVolumeOverride.EntityCullingSmallObjectUnit.Degrees: + return volumeParams.EntityCullingMinAngle; + case SurfaceCacheGIVolumeOverride.EntityCullingSmallObjectUnit.Pixels: + return camera.orthographic ? 0.0f : ScreenSizeToAngle(volumeParams.EntityCullingMinScreenSize, camera.fieldOfView, camera.pixelHeight); + default: + return 0.0f; + } + } + + internal static float ScreenSizeToAngle(float pixels, float verticalFieldOfViewDegrees, int pixelHeight) + { + if (pixelHeight <= 0) + return 0.0f; + + float halfHeightTangent = math.tan(math.radians(verticalFieldOfViewDegrees) * 0.5f); + return 2.0f * math.atan(pixels * halfHeightTangent / pixelHeight); + } + static Vector3 ResolveFocusPos(Camera camera) { GameObject focusTarget = VolumeManager.instance.stack?.GetSceneObjectReference(); @@ -165,7 +218,9 @@ private static VolumeParameterSet GetVolumeParameters(SurfaceCacheGIVolumeOverri SampleCount = (uint)volumeOverride.lightTransportSampleCount.value, WarmUpSampleMultiplier = (uint)volumeOverride.lightTransportWarmupSampleMultiplier.value, PunctualLightCandidateCount = (uint)volumeOverride.lightTransportPunctualLightCandidateCount.value, - DistanceFallback = volumeOverride.volumeDistanceFallback.value + DistanceFallback = volumeOverride.volumeDistanceFallback.value, + AlphaCutouts = volumeOverride.transparencyMode.value == SurfaceCacheGIVolumeOverride.TransparencyMode.OpaquesAndCutouts, + RayTracingNormalBias = volumeOverride.lightTransportRayTracingNormalBias.value }, PatchFilteringParams = new SurfaceCachePatchFilteringParameterSet { @@ -186,7 +241,13 @@ private static VolumeParameterSet GetVolumeParameters(SurfaceCacheGIVolumeOverri VolumeCascadeCount = (uint)volumeOverride.volumeCascadeCount.value, DefragCount = (uint)volumeOverride.lightTransportDefragCount.value, RenderingLayerMask = volumeOverride.lightTransportRenderingLayerMask.value, - PatchWarpingEnabled = volumeOverride.volumePatchWarpingEnabled.value + PatchWarpingEnabled = volumeOverride.volumePatchWarpingEnabled.value, + EntityCullingSphereMode = volumeOverride.entityCullingSphereMode.value, + EntityCullingDistanceMargin = volumeOverride.entityCullingDistanceMargin.value, + EntityCullingDistance = volumeOverride.entityCullingDistance.value, + EntityCullingSmallObjectUnit = volumeOverride.entityCullingSmallObjectUnit.value, + EntityCullingMinScreenSize = volumeOverride.entityCullingMinScreenSize.value, + EntityCullingMinAngle = math.radians(volumeOverride.entityCullingMinSolidAngle.value) }; } @@ -232,48 +293,29 @@ internal static class ShaderIDs public static readonly int _PreviousLowResScreenIrradiancesL11 = Shader.PropertyToID("_PreviousLowResScreenIrradiancesL11"); public static readonly int _PreviousLowResScreenIrradiancesL12 = Shader.PropertyToID("_PreviousLowResScreenIrradiancesL12"); public static readonly int _PreviousLowResScreenNdcDepths = Shader.PropertyToID("_PreviousLowResScreenNdcDepths"); - public static readonly int _PassIndex = Shader.PropertyToID("_PassIndex"); - public static readonly int _Intensity = Shader.PropertyToID("_Intensity"); - public static readonly int _ViewMode = Shader.PropertyToID("_ViewMode"); - public static readonly int _ShowSamplePosition = Shader.PropertyToID("_ShowSamplePosition"); - public static readonly int _SampleCount = Shader.PropertyToID("_SampleCount"); - public static readonly int _ClipToWorldTransforms = Shader.PropertyToID("_ClipToWorldTransforms"); - public static readonly int _NoiseWorldToClipTransform = Shader.PropertyToID("_NoiseWorldToClipTransform"); - public static readonly int _CameraWorldPos = Shader.PropertyToID("_CameraWorldPos"); - public static readonly int _CurrentClipToWorldTransforms = Shader.PropertyToID("_CurrentClipToWorldTransforms"); - public static readonly int _PreviousClipToWorldTransforms = Shader.PropertyToID("_PreviousClipToWorldTransforms"); - public static readonly int _FrameIdx = Shader.PropertyToID("_FrameIdx"); - public static readonly int _StereoEyeIndex = Shader.PropertyToID("_StereoEyeIndex"); - public static readonly int _VolumeSpatialResolution = Shader.PropertyToID("_VolumeSpatialResolution"); - public static readonly int _RingConfigOffset = Shader.PropertyToID("_RingConfigOffset"); - public static readonly int _VolumeTargetPos = Shader.PropertyToID("_VolumeTargetPos"); - public static readonly int _FullResPixelOffset = Shader.PropertyToID("_FullResPixelOffset"); - public static readonly int _LowResScreenSize = Shader.PropertyToID("_LowResScreenSize"); - public static readonly int _VolumeCascadeCount = Shader.PropertyToID("_VolumeCascadeCount"); - public static readonly int _VolumeVoxelMinSize = Shader.PropertyToID("_VolumeVoxelMinSize"); - public static readonly int _PatchWarping = Shader.PropertyToID("_PatchWarping"); public static readonly int _VolumeCascadeOffsets = Shader.PropertyToID("_VolumeCascadeOffsets"); public static readonly int _PatchCellIndices = Shader.PropertyToID("_PatchCellIndices"); public static readonly int _MaterialEntries = Shader.PropertyToID("_MaterialEntries"); public static readonly int _AlbedoTextures = Shader.PropertyToID("_AlbedoTextures"); public static readonly int _EmissionTextures = Shader.PropertyToID("_EmissionTextures"); - public static readonly int _MaterialAtlasTexelSize = Shader.PropertyToID("_MaterialAtlasTexelSize"); - public static readonly int _TileOffsetY = Shader.PropertyToID("_TileOffsetY"); - public static readonly int _TileHeight = Shader.PropertyToID("_TileHeight"); public static readonly int _GlobalProbe = Shader.PropertyToID("_GlobalProbe"); - public static readonly int _DistanceFallback = Shader.PropertyToID("_DistanceFallback"); public static readonly int _InputL0 = Shader.PropertyToID("_InputL0"); public static readonly int _InputL10 = Shader.PropertyToID("_InputL10"); public static readonly int _InputL11 = Shader.PropertyToID("_InputL11"); public static readonly int _InputL12 = Shader.PropertyToID("_InputL12"); public static readonly int _LowResNdcDepths = Shader.PropertyToID("_LowResNdcDepths"); + public static readonly int SurfaceCacheGIFlatNormalResolutionConstants = Shader.PropertyToID("SurfaceCacheGIFlatNormalResolutionConstants"); + public static readonly int SurfaceCacheGIPatchAllocationConstants = Shader.PropertyToID("SurfaceCacheGIPatchAllocationConstants"); + public static readonly int SurfaceCacheGIScreenResolveLookupConstants = Shader.PropertyToID("SurfaceCacheGIScreenResolveLookupConstants"); + public static readonly int SurfaceCacheGIScreenResolveDenoisingConstants = Shader.PropertyToID("SurfaceCacheGIScreenResolveDenoisingConstants"); + public static readonly int SurfaceCacheGIScreenResolveUpsamplingConstants = Shader.PropertyToID("SurfaceCacheGIScreenResolveUpsamplingConstants"); + public static readonly int SurfaceCacheGIDebugConstants = Shader.PropertyToID("SurfaceCacheGIDebugConstants"); } internal readonly struct CameraInfo { public readonly Matrix4x4 ClipToWorld0; public readonly Matrix4x4 ClipToWorld1; - public readonly Matrix4x4 WorldToClip; public readonly Vector3 WorldPos; public readonly int2 ScreenResolution; // How many XR views/eyes? 1 if we are not using XR. @@ -281,11 +323,10 @@ internal readonly struct CameraInfo // Whether we use Texture2D or Texture2DArray for screen textures when doing XR rendering. public readonly bool ScreenTexturesAreArrays; - public CameraInfo(Matrix4x4 clipToWorld0, Matrix4x4 clipToWorld1, Matrix4x4 worldToClip, Vector3 worldPos, int2 screenResolution, int viewCount, bool screenTexturesAreArrays) + public CameraInfo(Matrix4x4 clipToWorld0, Matrix4x4 clipToWorld1, Vector3 worldPos, int2 screenResolution, int viewCount, bool screenTexturesAreArrays) { ClipToWorld0 = clipToWorld0; ClipToWorld1 = clipToWorld1; - WorldToClip = worldToClip; WorldPos = worldPos; ViewCount = viewCount; ScreenTexturesAreArrays = screenTexturesAreArrays; @@ -293,11 +334,11 @@ public CameraInfo(Matrix4x4 clipToWorld0, Matrix4x4 clipToWorld1, Matrix4x4 worl } } - static void ComputeViewInfo(UniversalCameraData cameraData, int viewIndex, out Matrix4x4 worldToClip, out Matrix4x4 clipToWorld, out Vector3 worldPos) + static void ComputeViewInfo(UniversalCameraData cameraData, int viewIndex, out Matrix4x4 clipToWorld, out Vector3 worldPos) { var worldToView = cameraData.GetViewMatrix(viewIndex); var viewToClip = cameraData.GetGPUProjectionMatrix(true, viewIndex); - worldToClip = viewToClip * worldToView; + var worldToClip = viewToClip * worldToView; clipToWorld = worldToClip.inverse; worldPos = cameraData.xr.enabled ? (Vector3)worldToView.inverse.GetColumn(3) : cameraData.worldSpaceCameraPos; } @@ -309,25 +350,13 @@ internal static CameraInfo ComputeCameraInfo(UniversalCameraData cameraData) Debug.Assert(viewCount == 1 || viewCount == 2); Debug.Assert(viewCount == 1 || screenTexturesAreArrays); - ComputeViewInfo(cameraData, 0, out var worldToClip, out var clipToWorld0, out var worldPos); + ComputeViewInfo(cameraData, 0, out var clipToWorld0, out var worldPos); var clipToWorld1 = clipToWorld0; if (viewCount > 1) - ComputeViewInfo(cameraData, 1, out _, out clipToWorld1, out _); + ComputeViewInfo(cameraData, 1, out clipToWorld1, out _); var screenResolution = new int2(cameraData.cameraTargetDescriptor.width, cameraData.cameraTargetDescriptor.height); - return new CameraInfo(clipToWorld0, clipToWorld1, worldToClip, worldPos, screenResolution, viewCount, screenTexturesAreArrays); - } - - // Keeps DrawObjectsPass/GBufferPass on the screen-space-GI path instead of falling back to lightmap/APV/SH. - class SurfaceCacheZeroGIPass : ScriptableRenderPass - { - public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) - { - UniversalResourceData resourceData = frameData.Get(); - resourceData.irradianceTexture = (TextureXR.slices > 1 && TextureXR.initialized) - ? renderGraph.defaultResources.blackTextureXR - : renderGraph.defaultResources.blackTexture; - } + return new CameraInfo(clipToWorld0, clipToWorld1, worldPos, screenResolution, viewCount, screenTexturesAreArrays); } class SurfaceCacheWorldPass : ScriptableRenderPass, IDisposable @@ -350,7 +379,9 @@ private class WorldUpdatePassData private readonly bool _conformToUnityGIFormat; internal SurfaceCacheWorld World => _world; + internal bool TryAcquireEntityChanges() => _entityChangeSource.TryAcquireBridge(); internal uint RenderingLayerMask { get; set; } + internal int MaterialResolution { get; set; } public SurfaceCacheWorldPass( RayTracingContext rtContext, @@ -392,7 +423,8 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer RenderSettings.ambientIntensity, _conformToUnityGIFormat, RenderingLayerMask, - _world); + _world, + MaterialResolution); } catch { @@ -448,6 +480,8 @@ class PerCameraState : IDisposable internal uint FrameIndex; internal uint RenderingLayerMask; internal int LastUsedFrame; + internal bool EntityCullingEnabled; + internal SurfaceCacheCullingObserver EntityCullingObserver; public PerCameraState(SurfaceCache cache) { @@ -496,6 +530,7 @@ class SurfaceCacheCameraPass : ScriptableRenderPass, IDisposable private class FlatNormalResolutionPassData { internal ComputeShader Shader; + internal ConstantBuffer Constants; internal int KernelIndex; internal uint3 ThreadGroupSize; internal uint3 ThreadCount; @@ -507,6 +542,7 @@ private class FlatNormalResolutionPassData private class PatchAllocationPassData { internal ComputeShader Shader; + internal ConstantBuffer Constants; internal int KernelIndex; internal uint3 ThreadGroupSize; internal uint3 ThreadCount; @@ -518,6 +554,7 @@ private class PatchAllocationPassData internal TextureHandle LowResScreenIrradiancesL11; internal TextureHandle LowResScreenIrradiancesL12; internal TextureHandle LowResScreenNdcDepths; + internal TextureHandle ExposureMultiplier; internal GraphicsBuffer CellAllocationMarks; internal GraphicsBuffer CellPatchIndices; internal GraphicsBuffer RingConfigBuffer; @@ -544,6 +581,7 @@ private class PatchAllocationPassData private class DebugPassData { internal ComputeShader Shader; + internal ConstantBuffer Constants; internal int KernelIndex; internal uint3 ThreadGroupSize; internal uint3 ThreadCount; @@ -558,6 +596,7 @@ private class DebugPassData internal GraphicsBuffer PatchCellIndices; internal GraphicsBuffer PatchStatistics; internal SurfaceCacheDebugViewMode ViewMode; + internal LocalKeyword TransparencyModeKeyword; internal uint FrameIndex; internal bool ShowSamplePosition; internal uint VolumeSpatialResolution; @@ -576,6 +615,7 @@ private class DebugPassData private class ScreenIrradianceLookupPassData { internal ComputeShader Shader; + internal ConstantBuffer Constants; internal int KernelIndex; internal uint3 ThreadGroupSize; internal uint3 ThreadCount; @@ -605,6 +645,7 @@ private class ScreenIrradianceLookupPassData private class ScreenIrradianceUpsamplingPassData { internal ComputeShader Shader; + internal ConstantBuffer Constants; internal int KernelIndex; internal uint3 ThreadGroupSize; internal uint3 FullResThreadCount; @@ -625,6 +666,7 @@ private class ScreenIrradianceUpsamplingPassData private class ScreenResolveDenoisingPassData { internal ComputeShader Shader; + internal ConstantBuffer Constants; internal int KernelIndex; internal uint3 ThreadGroupSize; internal uint3 ThreadCount; @@ -643,7 +685,6 @@ private class ScreenResolveDenoisingPassData internal TextureHandle InputNdcDepths; internal TextureHandle ScreenFlatNormals; internal Matrix4x4[] ClipToWorldTransforms = new Matrix4x4[2]; - internal Matrix4x4 NoiseWorldToClipTransform; internal Vector3 CameraWorldPos; internal int PassCount; } @@ -673,11 +714,35 @@ private class ScreenResolveDenoisingPassData private readonly int _screenResolveDenoisingSinglePassStereoInstancingKernel; private readonly int _debugMonoKernel; private readonly int _debugSinglePassStereoInstancingKernel; + private readonly LocalKeyword _debugOpaquesOnlyKeyword; + private readonly LocalKeyword _debugCutoutsKeyword; private uint3 _screenResolveLookupKernelGroupSize; private uint3 _screenResolveUpsamplingKernelGroupSize; private uint3 _screenResolveDenoisingKernelGroupSize; private uint3 _debugKernelGroupSize; + private class ConstantBufferSet : IDisposable + { + public readonly ConstantBuffer FlatNormalResolution = new(); + public readonly ConstantBuffer PatchAllocation = new(); + public readonly ConstantBuffer ScreenResolveLookup = new(); + public readonly ConstantBuffer ScreenResolveDenoising = new(); + public readonly ConstantBuffer ScreenResolveUpsampling = new(); + public readonly ConstantBuffer Debug = new(); + + public void Dispose() + { + FlatNormalResolution.Release(); + PatchAllocation.Release(); + ScreenResolveLookup.Release(); + ScreenResolveDenoising.Release(); + ScreenResolveUpsampling.Release(); + Debug.Release(); + } + } + + private readonly ConstantBufferSet _constantBuffers = new(); + internal Vector3 FocusPos { get; set; } internal VolumeParameterSet VolumeParams { get; set; } internal PerCameraState CurrentPerCameraState { get; set; } @@ -719,17 +784,23 @@ public SurfaceCacheCameraPass( rayTracingBackend == RayTracingBackend.Compute ? "VisualizeMonoCompute" : "VisualizeMonoHardware"); _debugSinglePassStereoInstancingKernel = _debugShader.FindKernel( rayTracingBackend == RayTracingBackend.Compute ? "VisualizeSinglePassStereoInstancingCompute" : "VisualizeSinglePassStereoInstancingHardware"); + _debugOpaquesOnlyKeyword = new LocalKeyword(_debugShader, SurfaceCacheResourceSet.OpaquesOnlyKeyword); + _debugCutoutsKeyword = new LocalKeyword(_debugShader, SurfaceCacheResourceSet.CutoutsKeyword); _screenResolveLookupShader.GetKernelThreadGroupSizes(_screenResolveLookupMonoKernel, out _screenResolveLookupKernelGroupSize.x, out _screenResolveLookupKernelGroupSize.y, out _screenResolveLookupKernelGroupSize.z); _screenResolveUpsamplingShader.GetKernelThreadGroupSizes(_screenResolveUpsamplingMonoKernel, out _screenResolveUpsamplingKernelGroupSize.x, out _screenResolveUpsamplingKernelGroupSize.y, out _screenResolveUpsamplingKernelGroupSize.z); _screenResolveDenoisingShader.GetKernelThreadGroupSizes(_screenResolveDenoisingMonoKernel, out _screenResolveDenoisingKernelGroupSize.x, out _screenResolveDenoisingKernelGroupSize.y, out _screenResolveDenoisingKernelGroupSize.z); + _debugShader.EnableKeyword(_debugOpaquesOnlyKeyword); _debugShader.GetKernelThreadGroupSizes(_debugMonoKernel, out _debugKernelGroupSize.x, out _debugKernelGroupSize.y, out _debugKernelGroupSize.z); + _debugShader.DisableKeyword(_debugOpaquesOnlyKeyword); } public void Dispose() { _debugTraceScratch?.Dispose(); _debugTraceScratch = null; + + _constantBuffers.Dispose(); } internal TextureHandle RecordFlatNormalResolution(RenderGraph renderGraph, in CameraInfo cameraInfo, TextureHandle screenDepths) @@ -749,6 +820,7 @@ internal TextureHandle RecordFlatNormalResolution(RenderGraph renderGraph, in Ca { passData.ThreadCount = new uint3((uint)cameraInfo.ScreenResolution.x, (uint)cameraInfo.ScreenResolution.y, (uint)cameraInfo.ViewCount); passData.Shader = _flatNormalResolutionShader; + passData.Constants = _constantBuffers.FlatNormalResolution; passData.KernelIndex = cameraInfo.ScreenTexturesAreArrays ? _flatNormalResolutionSinglePassStereoInstancingKernel : _flatNormalResolutionMonoKernel; passData.ThreadGroupSize = _flatNormalResolutionKernelGroupSize; passData.ScreenDepths = screenDepths; @@ -802,6 +874,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer passData.ThreadCount = new uint3(lowResScreenSize, 1); passData.Shader = _patchAllocationShader; + passData.Constants = _constantBuffers.PatchAllocation; passData.KernelIndex = cameraInfo.ScreenTexturesAreArrays ? _patchAllocationSinglePassStereoInstancingKernel : _patchAllocationMonoKernel; passData.ThreadGroupSize = _patchAllocationKernelGroupSize; passData.ScreenDepths = resourceData.cameraDepthTexture; @@ -812,6 +885,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer passData.LowResScreenIrradiancesL11 = lowResScreenIrradiancesL11Handle; passData.LowResScreenIrradiancesL12 = lowResScreenIrradiancesL12Handle; passData.LowResScreenNdcDepths = lowResScreenNdcDepthsHandle; + passData.ExposureMultiplier = resourceData.exposureMultiplier; passData.CellAllocationMarks = cache.Volume.CellAllocationMarks; passData.CellPatchIndices = cache.Volume.CellPatchIndices; passData.RingConfigBuffer = cache.RingConfig.Buffer; @@ -851,6 +925,10 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer builder.UseTexture(lowResScreenIrradiancesL11Handle, AccessFlags.Read); builder.UseTexture(lowResScreenIrradiancesL12Handle, AccessFlags.Read); builder.UseTexture(lowResScreenNdcDepthsHandle, AccessFlags.Read); + if (passData.ExposureMultiplier.IsValid()) + { + builder.UseTexture(passData.ExposureMultiplier, AccessFlags.Read); + } builder.SetRenderFunc((PatchAllocationPassData data, ComputeGraphContext cgContext) => AllocatePatches(data, cgContext)); } @@ -876,6 +954,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer data.ClipToWorldTransforms[1] = cameraInfo.ClipToWorld1; data.ThreadCount = new uint3((uint)CurrentPerCameraState.LowResIrradiancesL0.rt.width, (uint)CurrentPerCameraState.LowResIrradiancesL0.rt.height, (uint)cameraInfo.ViewCount); data.Shader = _screenResolveLookupShader; + data.Constants = _constantBuffers.ScreenResolveLookup; data.KernelIndex = cameraInfo.ScreenTexturesAreArrays ? _screenResolveLookupSinglePassStereoInstancingKernel : _screenResolveLookupMonoKernel; data.ThreadGroupSize = _screenResolveLookupKernelGroupSize; data.ExposureMultiplier = resourceData.exposureMultiplier; @@ -960,10 +1039,10 @@ TextureHandle CreateDenoisingTargetTexture(GraphicsFormat format, string name) { denoisingData.ClipToWorldTransforms[0] = cameraInfo.ClipToWorld0; denoisingData.ClipToWorldTransforms[1] = cameraInfo.ClipToWorld1; - denoisingData.NoiseWorldToClipTransform = cameraInfo.WorldToClip; denoisingData.CameraWorldPos = cameraInfo.WorldPos; denoisingData.ThreadCount = new uint3((uint)lowResWidth, (uint)lowResHeight, (uint)cameraInfo.ViewCount); denoisingData.Shader = _screenResolveDenoisingShader; + denoisingData.Constants = _constantBuffers.ScreenResolveDenoising; denoisingData.KernelIndex = cameraInfo.ScreenTexturesAreArrays ? _screenResolveDenoisingSinglePassStereoInstancingKernel : _screenResolveDenoisingMonoKernel; denoisingData.ThreadGroupSize = _screenResolveDenoisingKernelGroupSize; denoisingData.InputL0 = lowResScreenIrradiancesL0Handle; @@ -1031,6 +1110,7 @@ TextureHandle CreateDenoisingTargetTexture(GraphicsFormat format, string name) passData.TraceScratchBuffer = _debugTraceScratch; passData.World = _world; passData.Shader = _debugShader; + passData.Constants = _constantBuffers.Debug; passData.KernelIndex = cameraInfo.ScreenTexturesAreArrays ? _debugSinglePassStereoInstancingKernel : _debugMonoKernel; passData.ThreadGroupSize = _debugKernelGroupSize; passData.ScreenDepths = resourceData.cameraDepthTexture; @@ -1051,6 +1131,7 @@ TextureHandle CreateDenoisingTargetTexture(GraphicsFormat format, string name) passData.VolumeCascadeCount = cache.Volume.CascadeCount; passData.CascadeOffsets = cache.Volume.CascadeOffsetBuffer; passData.ViewMode = debugSettings.viewMode; + passData.TransparencyModeKeyword = VolumeParams.EstimationParams.AlphaCutouts ? _debugCutoutsKeyword : _debugOpaquesOnlyKeyword; passData.FrameIndex = CurrentPerCameraState.FrameIndex; passData.ShowSamplePosition = debugSettings.showSamplePosition; passData.ClipToWorldTransforms[0] = cameraInfo.ClipToWorld0; @@ -1074,6 +1155,7 @@ TextureHandle CreateDenoisingTargetTexture(GraphicsFormat format, string name) data.CameraWorldPos = cameraInfo.WorldPos; data.FullResThreadCount = new uint3((uint)cameraInfo.ScreenResolution.x, (uint)cameraInfo.ScreenResolution.y, (uint)cameraInfo.ViewCount); data.Shader = _screenResolveUpsamplingShader; + data.Constants = _constantBuffers.ScreenResolveUpsampling; data.KernelIndex = cameraInfo.ScreenTexturesAreArrays ? _screenResolveUpsamplingSinglePassStereoInstancingKernel : _screenResolveUpsamplingMonoKernel; data.ThreadGroupSize = _screenResolveUpsamplingKernelGroupSize; data.FullResDepths = resourceData.cameraDepthTexture; @@ -1114,7 +1196,10 @@ static void ResolveFlatNormals(FlatNormalResolutionPassData data, ComputeGraphCo var kernelIndex = data.KernelIndex; cmd.SetComputeTextureParam(shader, kernelIndex, ShaderIDs._ScreenDepths, data.ScreenDepths); cmd.SetComputeTextureParam(shader, kernelIndex, ShaderIDs._ScreenFlatNormals, data.ScreenFlatNormals); - cmd.SetComputeMatrixArrayParam(shader, ShaderIDs._ClipToWorldTransforms, data.ClipToWorldTransforms); + var constants = new SurfaceCacheGIFlatNormalResolutionConstants(); + unsafe { CopyMatrices(data.ClipToWorldTransforms, constants._ClipToWorldTransforms); } + data.Constants.UpdateData(cmd, constants); + data.Constants.Set(cmd, shader, ShaderIDs.SurfaceCacheGIFlatNormalResolutionConstants); uint3 groupCount = DivUp(data.ThreadCount, data.ThreadGroupSize); cmd.DispatchCompute(shader, kernelIndex, (int)groupCount.x, (int)groupCount.y, (int)groupCount.z); @@ -1133,6 +1218,10 @@ static void AllocatePatches(PatchAllocationPassData data, ComputeGraphContext cg cmd.SetComputeTextureParam(shader, kernelIndex, ShaderIDs._PreviousLowResScreenIrradiancesL11, data.LowResScreenIrradiancesL11); cmd.SetComputeTextureParam(shader, kernelIndex, ShaderIDs._PreviousLowResScreenIrradiancesL12, data.LowResScreenIrradiancesL12); cmd.SetComputeTextureParam(shader, kernelIndex, ShaderIDs._PreviousLowResScreenNdcDepths, data.LowResScreenNdcDepths); + if (data.ExposureMultiplier.IsValid()) + { + cmd.SetComputeTextureParam(shader, kernelIndex, ShaderIDs._ExposureMultiplier, data.ExposureMultiplier); + } cmd.SetComputeBufferParam(shader, kernelIndex, ShaderIDs._CellAllocationMarks, data.CellAllocationMarks); cmd.SetComputeBufferParam(shader, kernelIndex, ShaderIDs._CellPatchIndices, data.CellPatchIndices); cmd.SetComputeBufferParam(shader, kernelIndex, ShaderIDs._RingConfigBuffer, data.RingConfigBuffer); @@ -1142,18 +1231,26 @@ static void AllocatePatches(PatchAllocationPassData data, ComputeGraphContext cg cmd.SetComputeBufferParam(shader, kernelIndex, ShaderIDs._PatchCellIndices, data.PatchCellIndices); cmd.SetComputeBufferParam(shader, kernelIndex, ShaderIDs._PatchStatistics, data.PatchStatistics); cmd.SetComputeBufferParam(shader, kernelIndex, ShaderIDs._VolumeCascadeOffsets, data.CascadeOffsets); - cmd.SetComputeIntParam(shader, ShaderIDs._FrameIdx, (int)data.FrameIdx); - cmd.SetComputeIntParam(shader, ShaderIDs._StereoEyeIndex, data.StereoEyeIndex); - cmd.SetComputeIntParam(shader, ShaderIDs._VolumeSpatialResolution, (int)data.VolumeSpatialResolution); - cmd.SetComputeIntParam(shader, ShaderIDs._VolumeCascadeCount, (int)data.VolumeCascadeCount); - cmd.SetComputeIntParam(shader, ShaderIDs._RingConfigOffset, (int)data.RingConfigOffset); - cmd.SetComputeIntParams(shader, ShaderIDs._FullResPixelOffset, (int)data.FullResPixelOffset.x, (int)data.FullResPixelOffset.y); - cmd.SetComputeIntParams(shader, ShaderIDs._LowResScreenSize, (int)data.LowResScreenSize.x, (int)data.LowResScreenSize.y); - cmd.SetComputeFloatParam(shader, ShaderIDs._VolumeVoxelMinSize, data.VoxelMinSize); - cmd.SetComputeIntParam(shader, ShaderIDs._PatchWarping, data.PatchWarpingEnabled ? 1 : 0); - cmd.SetComputeMatrixArrayParam(shader, ShaderIDs._CurrentClipToWorldTransforms, data.CurrentClipToWorldTransforms); - cmd.SetComputeMatrixArrayParam(shader, ShaderIDs._PreviousClipToWorldTransforms, data.PreviousClipToWorldTransforms); - cmd.SetComputeVectorParam(shader, ShaderIDs._VolumeTargetPos, data.VolumeTargetPos); + var constants = new SurfaceCacheGIPatchAllocationConstants + { + _VolumeTargetPos = data.VolumeTargetPos, + _VolumeVoxelMinSize = data.VoxelMinSize, + _FrameIdx = data.FrameIdx, + _StereoEyeIndex = (uint)data.StereoEyeIndex, + _VolumeSpatialResolution = data.VolumeSpatialResolution, + _VolumeCascadeCount = data.VolumeCascadeCount, + _LowResScreenSize = data.LowResScreenSize, + _FullResPixelOffset = data.FullResPixelOffset, + _RingConfigOffset = data.RingConfigOffset, + _PatchWarping = data.PatchWarpingEnabled ? 1 : 0, + }; + unsafe + { + CopyMatrices(data.CurrentClipToWorldTransforms, constants._CurrentClipToWorldTransforms); + CopyMatrices(data.PreviousClipToWorldTransforms, constants._PreviousClipToWorldTransforms); + } + data.Constants.UpdateData(cmd, constants); + data.Constants.Set(cmd, shader, ShaderIDs.SurfaceCacheGIPatchAllocationConstants); uint3 groupCount = DivUp(data.ThreadCount, data.ThreadGroupSize); cmd.DispatchCompute(shader, kernelIndex, (int)groupCount.x, (int)groupCount.y, (int)groupCount.z); @@ -1180,14 +1277,19 @@ static void LookupScreenIrradiance(ScreenIrradianceLookupPassData data, ComputeG cmd.SetComputeBufferParam(shader, kernelIndex, ShaderIDs._VolumeCascadeOffsets, data.CascadeOffsets); cmd.SetComputeBufferParam(shader, kernelIndex, ShaderIDs._PatchStatistics, data.PatchStatistics); cmd.SetComputeBufferParam(shader, kernelIndex, ShaderIDs._GlobalProbe, data.GlobalProbeBuffer); - cmd.SetComputeIntParam(shader, ShaderIDs._DistanceFallback, data.DistanceFallback ? 1 : 0); - cmd.SetComputeIntParam(shader, ShaderIDs._VolumeSpatialResolution, (int)data.VolumeSpatialResolution); - cmd.SetComputeIntParam(shader, ShaderIDs._VolumeCascadeCount, (int)data.VolumeCascadeCount); - cmd.SetComputeIntParam(shader, ShaderIDs._SampleCount, (int)data.SampleCount); - cmd.SetComputeFloatParam(shader, ShaderIDs._VolumeVoxelMinSize, data.VolumeVoxelMinSize); - cmd.SetComputeIntParam(shader, ShaderIDs._PatchWarping, data.PatchWarpingEnabled ? 1 : 0); - cmd.SetComputeMatrixArrayParam(shader, ShaderIDs._ClipToWorldTransforms, data.ClipToWorldTransforms); - cmd.SetComputeVectorParam(shader, ShaderIDs._VolumeTargetPos, data.VolumeTargetPos); + var constants = new SurfaceCacheGIScreenResolveLookupConstants + { + _VolumeTargetPos = data.VolumeTargetPos, + _VolumeVoxelMinSize = data.VolumeVoxelMinSize, + _VolumeSpatialResolution = data.VolumeSpatialResolution, + _VolumeCascadeCount = data.VolumeCascadeCount, + _SampleCount = data.SampleCount, + _PatchWarping = data.PatchWarpingEnabled ? 1 : 0, + _DistanceFallback = data.DistanceFallback ? 1u : 0u, + }; + unsafe { CopyMatrices(data.ClipToWorldTransforms, constants._ClipToWorldTransforms); } + data.Constants.UpdateData(cmd, constants); + data.Constants.Set(cmd, shader, ShaderIDs.SurfaceCacheGIScreenResolveLookupConstants); uint3 groupCount = DivUp(data.ThreadCount, data.ThreadGroupSize); cmd.DispatchCompute(shader, kernelIndex, (int)groupCount.x, (int)groupCount.y, (int)groupCount.z); @@ -1200,9 +1302,11 @@ static void DenoiseScreenIrradiance(ScreenResolveDenoisingPassData data, Compute var kernelIndex = data.KernelIndex; cmd.SetComputeTextureParam(shader, kernelIndex, ShaderIDs._LowResNdcDepths, data.InputNdcDepths); cmd.SetComputeTextureParam(shader, kernelIndex, ShaderIDs._ScreenFlatNormals, data.ScreenFlatNormals); - cmd.SetComputeMatrixArrayParam(shader, ShaderIDs._ClipToWorldTransforms, data.ClipToWorldTransforms); - cmd.SetComputeMatrixParam(shader, ShaderIDs._NoiseWorldToClipTransform, data.NoiseWorldToClipTransform); - cmd.SetComputeVectorParam(shader, ShaderIDs._CameraWorldPos, data.CameraWorldPos); + var constants = new SurfaceCacheGIScreenResolveDenoisingConstants + { + _CameraWorldPos = data.CameraWorldPos, + }; + unsafe { CopyMatrices(data.ClipToWorldTransforms, constants._ClipToWorldTransforms); } uint3 groupCount = DivUp(data.ThreadCount, data.ThreadGroupSize); @@ -1227,7 +1331,9 @@ static void DenoiseScreenIrradiance(ScreenResolveDenoisingPassData data, Compute cmd.SetComputeTextureParam(shader, kernelIndex, ShaderIDs._ResultL10, outputL10); cmd.SetComputeTextureParam(shader, kernelIndex, ShaderIDs._ResultL11, outputL11); cmd.SetComputeTextureParam(shader, kernelIndex, ShaderIDs._ResultL12, outputL12); - cmd.SetComputeIntParam(shader, ShaderIDs._PassIndex, passIndex); + constants._PassIndex = passIndex; + data.Constants.UpdateData(cmd, constants); + data.Constants.Set(cmd, shader, ShaderIDs.SurfaceCacheGIScreenResolveDenoisingConstants); cmd.DispatchCompute(shader, kernelIndex, (int)groupCount.x, (int)groupCount.y, (int)groupCount.z); @@ -1253,19 +1359,35 @@ static void UpsampleScreenIrradiance(ScreenIrradianceUpsamplingPassData passData cmd.SetComputeTextureParam(shader, kernelIndex, ShaderIDs._LowResIrradiancesL11, passData.LowResScreenIrradiancesL11); cmd.SetComputeTextureParam(shader, kernelIndex, ShaderIDs._LowResIrradiancesL12, passData.LowResScreenIrradiancesL12); cmd.SetComputeTextureParam(shader, kernelIndex, ShaderIDs._ResultNdcDepths, passData.LowResScreenNdcDepths); - cmd.SetComputeFloatParam(shader, ShaderIDs._Intensity, passData.Intensity); - cmd.SetComputeMatrixArrayParam(shader, ShaderIDs._ClipToWorldTransforms, passData.ClipToWorldTransforms); - cmd.SetComputeVectorParam(shader, ShaderIDs._CameraWorldPos, passData.CameraWorldPos); + var constants = new SurfaceCacheGIScreenResolveUpsamplingConstants + { + _CameraWorldPos = passData.CameraWorldPos, + _Intensity = passData.Intensity, + }; + unsafe { CopyMatrices(passData.ClipToWorldTransforms, constants._ClipToWorldTransforms); } + passData.Constants.UpdateData(cmd, constants); + passData.Constants.Set(cmd, shader, ShaderIDs.SurfaceCacheGIScreenResolveUpsamplingConstants); uint3 groupCount = DivUp(passData.FullResThreadCount, passData.ThreadGroupSize); cmd.DispatchCompute(shader, kernelIndex, (int)groupCount.x, (int)groupCount.y, (int)groupCount.z); } + static unsafe void CopyMatrices(Matrix4x4[] matrices, float* destination) + { + Debug.Assert(matrices.Length == 2, "Every destination holds exactly two matrices."); + for (int matrixIdx = 0; matrixIdx < matrices.Length; ++matrixIdx) + { + for (int elementIdx = 0; elementIdx < 16; ++elementIdx) + destination[matrixIdx * 16 + elementIdx] = matrices[matrixIdx][elementIdx]; + } + } + static void RenderDebug(DebugPassData data, UnsafeGraphContext graphCtx) { var cmd = CommandBufferHelpers.GetNativeCommandBuffer(graphCtx.cmd); var shader = data.Shader; var kernelIndex = data.KernelIndex; + cmd.EnableKeyword(shader, data.TransparencyModeKeyword); cmd.SetComputeTextureParam(shader, kernelIndex, ShaderIDs._Result, data.Output); cmd.SetComputeTextureParam(shader, kernelIndex, ShaderIDs._ScreenDepths, data.ScreenDepths); cmd.SetComputeTextureParam(shader, kernelIndex, ShaderIDs._ScreenShadedNormals, data.ScreenShadedNormals); @@ -1282,28 +1404,35 @@ static void RenderDebug(DebugPassData data, UnsafeGraphContext graphCtx) cmd.SetComputeBufferParam(shader, kernelIndex, ShaderIDs._MaterialEntries, data.World.GetMaterialListBuffer()); cmd.SetComputeTextureParam(shader, kernelIndex, ShaderIDs._AlbedoTextures, albedoTextures); cmd.SetComputeTextureParam(shader, kernelIndex, ShaderIDs._EmissionTextures, data.World.GetMaterialEmissionTextures()); - cmd.SetComputeFloatParam(shader, ShaderIDs._MaterialAtlasTexelSize, 1.0f / albedoTextures.width); InlineRayTracing.SetAccelerationStructure(cmd, shader, kernelIndex, "_RayTracingAccelerationStructure", data.World.GetAccelerationStructure().GetAccelerationStructure()); data.World.GetAccelerationStructure().Instances.Bind(cmd, shader, kernelIndex); InlineRayTracing.SetTraceScratchBuffer(cmd, shader, kernelIndex, data.TraceScratchBuffer); - cmd.SetComputeIntParam(shader, ShaderIDs._VolumeSpatialResolution, (int)data.VolumeSpatialResolution); - cmd.SetComputeIntParam(shader, ShaderIDs._VolumeCascadeCount, (int)data.VolumeCascadeCount); - cmd.SetComputeIntParam(shader, ShaderIDs._ViewMode, (int)data.ViewMode); - cmd.SetComputeIntParam(shader, ShaderIDs._FrameIdx, (int)data.FrameIndex); - cmd.SetComputeIntParam(shader, ShaderIDs._ShowSamplePosition, data.ShowSamplePosition ? 1 : 0); - cmd.SetComputeFloatParam(shader, ShaderIDs._VolumeVoxelMinSize, data.VolumeVoxelMinSize); - cmd.SetComputeIntParam(shader, ShaderIDs._PatchWarping, data.PatchWarpingEnabled ? 1 : 0); - cmd.SetComputeIntParam(shader, ShaderIDs._RingConfigOffset, (int)data.RingConfigOffset); - cmd.SetComputeVectorParam(shader, ShaderIDs._VolumeTargetPos, data.VolumeTargetPos); - cmd.SetComputeMatrixArrayParam(shader, ShaderIDs._ClipToWorldTransforms, data.ClipToWorldTransforms); - cmd.SetComputeIntParam(shader, ShaderIDs._TileHeight, (int)data.TileHeight); - - if (data.ViewMode == SurfaceCacheDebugViewMode.Albedo || data.ViewMode == SurfaceCacheDebugViewMode.Emission) + var constants = new SurfaceCacheGIDebugConstants + { + _VolumeTargetPos = data.VolumeTargetPos, + _VolumeVoxelMinSize = data.VolumeVoxelMinSize, + _RingConfigOffset = data.RingConfigOffset, + _VolumeSpatialResolution = data.VolumeSpatialResolution, + _VolumeCascadeCount = data.VolumeCascadeCount, + _ViewMode = (uint)data.ViewMode, + _ShowSamplePosition = data.ShowSamplePosition ? 1u : 0u, + _FrameIdx = data.FrameIndex, + _PatchWarping = data.PatchWarpingEnabled ? 1 : 0, + _MaterialAtlasTexelSize = 1.0f / albedoTextures.width, + _TileHeight = data.TileHeight, + }; + unsafe { CopyMatrices(data.ClipToWorldTransforms, constants._ClipToWorldTransforms); } + + if (data.ViewMode == SurfaceCacheDebugViewMode.Albedo + || data.ViewMode == SurfaceCacheDebugViewMode.Emission + || data.ViewMode == SurfaceCacheDebugViewMode.WorldCulling) { for (uint tileOffsetY = 0; tileOffsetY < data.ThreadCount.y; tileOffsetY += data.TileHeight) { - cmd.SetComputeIntParam(shader, ShaderIDs._TileOffsetY, (int)tileOffsetY); + constants._TileOffsetY = tileOffsetY; + data.Constants.UpdateData(cmd, constants); + data.Constants.Set(cmd, shader, ShaderIDs.SurfaceCacheGIDebugConstants); var tileThreadCount = new uint3(data.ThreadCount.x, math.min(data.TileHeight, data.ThreadCount.y - tileOffsetY), data.ThreadCount.z); uint3 groupCount = DivUp(tileThreadCount, data.ThreadGroupSize); cmd.DispatchCompute(shader, kernelIndex, (int)groupCount.x, (int)groupCount.y, (int)groupCount.z); @@ -1311,22 +1440,19 @@ static void RenderDebug(DebugPassData data, UnsafeGraphContext graphCtx) } else { - cmd.SetComputeIntParam(shader, ShaderIDs._TileOffsetY, 0); + data.Constants.UpdateData(cmd, constants); + data.Constants.Set(cmd, shader, ShaderIDs.SurfaceCacheGIDebugConstants); uint3 groupCount = DivUp(data.ThreadCount, data.ThreadGroupSize); cmd.DispatchCompute(shader, kernelIndex, (int)groupCount.x, (int)groupCount.y, (int)groupCount.z); } + + cmd.DisableKeyword(shader, data.TransparencyModeKeyword); } } private SurfaceCacheWorldPass _worldPass; private SurfaceCacheCameraPass _cameraPass; - // Unlike the other passes, this one runs when the cache has been released, so it cannot live in Create(). - private readonly SurfaceCacheZeroGIPass _zeroGIPass = new SurfaceCacheZeroGIPass - { - renderPassEvent = RenderPassEvent.AfterRenderingPrePasses + 1 - }; - private RayTracingContext _rtContext; private readonly Dictionary<(Camera camera, int xrMultipassId), PerCameraState> _cameraStates = new Dictionary<(Camera camera, int xrMultipassId), PerCameraState>(); @@ -1336,6 +1462,13 @@ static void RenderDebug(DebugPassData data, UnsafeGraphContext graphCtx) internal int ActiveCacheCount => _cameraStates.Count; internal uint WorldRenderingLayerMask => _worldPass.RenderingLayerMask; + internal void GetMaterialAtlasUsage(out int materialCount, out AtlasUsage albedo, out AtlasUsage emission, out AtlasUsage transmission) + { + Debug.Assert(IsValidForDebugging(), "Material atlas usage is only available once the feature's resources are created."); + materialCount = _worldPass.World.GetMaterialCount(); + _worldPass.World.GetMaterialAtlasUsage(out albedo, out emission, out transmission); + } + // Historically, GI systems in Unity have, for historical reasons, 1) multiplied punctual light intensity // inputs with PI, and 2) divided all GI output with PI. To match this, Surface Cache for now does // something mathematically equivalent: It divides environment light and triangle emission by PI. @@ -1373,6 +1506,12 @@ internal struct VolumeParameterSet public uint DefragCount; public uint RenderingLayerMask; public bool PatchWarpingEnabled; + public SurfaceCacheGIVolumeOverride.EntityCullingSphereMode EntityCullingSphereMode; + public float EntityCullingDistanceMargin; + public float EntityCullingDistance; + public SurfaceCacheGIVolumeOverride.EntityCullingSmallObjectUnit EntityCullingSmallObjectUnit; + public float EntityCullingMinScreenSize; + public float EntityCullingMinAngle; } SurfaceCache CreateCache(in VolumeParameterSet vp) @@ -1405,6 +1544,32 @@ void EvictStaleCameraStates() } } + void PublishEntityCullingObservers() + { + // Other features would overwrite the observers of the feature whose world receives the entities. + if (_worldPass == null || !_worldPass.TryAcquireEntityChanges()) + return; + + bool excludeSceneView = UniversalRenderPipelineDebugDisplaySettings.Instance.surfaceCacheSettings.excludeSceneViewFromEntityCulling; + Span observers = stackalloc SurfaceCacheCullingObserver[_cameraStates.Count]; + int observerCount = 0; + foreach (var kvp in _cameraStates) + { + if (excludeSceneView && kvp.Key.camera != null && kvp.Key.camera.cameraType == CameraType.SceneView) + continue; + + if (!kvp.Value.EntityCullingEnabled) + { + observerCount = 0; + break; + } + + observers[observerCount++] = kvp.Value.EntityCullingObserver; + } + + SurfaceCacheEntityChangeBridge.SetCullingObservers(observers.Slice(0, observerCount)); + } + bool ResourcesCreated() { return _cameraPass != null; @@ -1523,11 +1688,8 @@ public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingD } if (_cameraStates.Count == 0 && ResourcesCreated()) ClearResources(); - - // Where Surface Cache can never run, Enabled and Disabled already fall back identically, - // so only take over here where it can. - if (HasSupportedRayTracingBackend()) - renderer.EnqueuePass(_zeroGIPass); + else + PublishEntityCullingObservers(); return; } @@ -1558,6 +1720,15 @@ public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingD perCameraState.FrameIndex = reconfigured ? 0u : perCameraState.FrameIndex + 1u; perCameraState.LastUsedFrame = Time.frameCount; perCameraState.RenderingLayerMask = volumeParams.RenderingLayerMask; + Vector3 focusPos = ResolveFocusPos(camera); + perCameraState.EntityCullingEnabled = volumeParams.EntityCullingSphereMode != SurfaceCacheGIVolumeOverride.EntityCullingSphereMode.None + || volumeParams.EntityCullingSmallObjectUnit != SurfaceCacheGIVolumeOverride.EntityCullingSmallObjectUnit.None; + perCameraState.EntityCullingObserver = new SurfaceCacheCullingObserver + { + Position = focusPos, + MaxDistance = GetEntityCullingMaxDistance(volumeParams), + MinAngle = GetEntityCullingMinAngle(camera, volumeParams), + }; // Editor repaints only advance the motion vector index, which stalls while no camera uses motion vectors. int motionVectorFrameIndex = @@ -1573,16 +1744,19 @@ public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingD combinedMask |= kvp.Value.RenderingLayerMask; _worldPass.RenderingLayerMask = combinedMask; + _worldPass.MaterialResolution = (int)m_MaterialResolution; renderer.EnqueuePass(_worldPass); } + PublishEntityCullingObservers(); + ScriptableRenderPassInput passInputs = ScriptableRenderPassInput.Depth | ScriptableRenderPassInput.Normal | ScriptableRenderPassInput.Motion; _cameraPass.CurrentPerCameraState = perCameraState; _cameraPass.VolumeParams = volumeParams; - _cameraPass.FocusPos = ResolveFocusPos(camera); + _cameraPass.FocusPos = focusPos; _cameraPass.ConfigureInput(passInputs); renderer.EnqueuePass(_cameraPass); } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/SurfaceCacheGIRendererFeature.migration.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/SurfaceCacheGIRendererFeature.migration.cs new file mode 100644 index 00000000000..39683eb66bf --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/SurfaceCacheGIRendererFeature.migration.cs @@ -0,0 +1,66 @@ +#if SURFACE_CACHE_SUPPORTED || UNITY_EDITOR + +#if UNITY_EDITOR +using UnityEditor; +#endif + +namespace UnityEngine.Rendering.Universal +{ + public partial class SurfaceCacheGIRendererFeature : ISerializationCallbackReceiver + { + private enum Version + { + // Set only on newly created objects, or on objects serialized before m_Version existed. The two cases are + // told apart by whether this value is first seen during serialization or during deserialization. + Uninitialised = -1, + + Initial, + AddMaterialResolution, + + Count, + Latest = Count - 1, + } + + [SerializeField] + [HideInInspector] + private Version m_Version = Version.Uninitialised; + + private void UpgradeIfNeeded() + { +#if UNITY_EDITOR + if (m_Version == Version.Latest) + return; + + if (m_Version == Version.Initial) + { + m_MaterialResolution = MaterialResolution.VeryHigh; + m_Version++; + } + + EditorApplication.delayCall += () => + { + if (this) + EditorUtility.SetDirty(this); + }; +#endif + } + + /// + void ISerializationCallbackReceiver.OnBeforeSerialize() + { + if (m_Version == Version.Uninitialised) + m_Version = Version.Latest; + } + + /// + void ISerializationCallbackReceiver.OnAfterDeserialize() + { + if (m_Version == Version.Uninitialised) + m_Version = Version.Initial; + + UpgradeIfNeeded(); + } + } +} + +#endif diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/SurfaceCacheGIRendererFeature.migration.cs.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/SurfaceCacheGIRendererFeature.migration.cs.meta new file mode 100644 index 00000000000..0b4cdb8350c --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/SurfaceCacheGIRendererFeature.migration.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 0cdb074b03c646c495237784efbaab85 diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/SurfaceCacheWorldAdapter.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/SurfaceCacheWorldAdapter.cs index a55f3e1821d..0fdbb5cb2ba 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/SurfaceCacheWorldAdapter.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/SurfaceCacheWorldAdapter.cs @@ -68,21 +68,33 @@ internal bool TryGetEntityInstanceInputMaterialIds(EntityId key, out EntityId[] { return _entityInstances.TryGetInputMaterialIds(key, out materialIds); } + + internal bool TryGetEntityInstanceAppliedMeshLod(EntityId key, out int meshLod) + { + return _entityInstances.TryGetAppliedMeshLod(key, out meshLod); + } + + internal bool TryGetMeshRendererAppliedMeshLod(EntityId key, out int meshLod) + { + return _meshRenderers.TryGetAppliedMeshLod(key, out meshLod); + } #endif public void Update(SurfaceCacheWorldChangeSet changes, AmbientMode ambientMode, Material skyboxMaterial, Color ambientSkycolor, Color ambientEquatorColor, Color ambientGroundColor, float materialEnvIntensityMultiplier, - bool divideEnvIntensityByPI, uint renderingLayerMaskFilter, SurfaceCacheWorld world) + bool divideEnvIntensityByPI, uint renderingLayerMaskFilter, SurfaceCacheWorld world, int materialResolution) { using var _ = k_WorldAdapterUpdateMarker.Auto(); + bool resolutionChanged = _sharedMaterials.SetResolution(materialResolution, world); + bool filterChanged = renderingLayerMaskFilter != _renderingLayerMaskFilter; _renderingLayerMaskFilter = renderingLayerMaskFilter; RemoveInstancesWithDestroyedMeshes(changes.MeshDestroyedList, world); UpdateMeshRenderers(changes.MeshRendererTransformChangedIds, changes.MeshRendererTransformChangedLocalToWorlds, changes.MeshRendererChangedList, changes.MeshRendererDestroyedList, world); - UpdateEntityInstances(changes.EntityInstanceTransformChangedList, changes.EntityInstanceChangedList, changes.EntityInstanceMaterialList, changes.EntityInstanceDestroyedList, world); + UpdateEntityInstances(changes.EntityInstanceTransformChangedList, changes.EntityInstanceChangedList, changes.EntityInstanceMaterialList, changes.EntityInstanceMaterialOverrideList, changes.EntityInstanceDestroyedList, world); #if ENABLE_TERRAIN_MODULE UpdateTerrains(changes.TerrainTransformChangedList, changes.TerrainChangedList, changes.TerrainDestroyedList, changes.TerrainDataChangedList, world); #endif @@ -90,17 +102,19 @@ public void Update(SurfaceCacheWorldChangeSet changes, AmbientMode ambientMode, // A change to the global rendering layer mask filter is not reported as a per-object change by the // ObjectDispatcher, so re-evaluate every known instance to add the newly-included and remove the - // newly-excluded ones. Filter changes are rare (authoring), so this rescan is acceptable; the common + // newly-excluded ones. A material resolution change can make room for materials that were rejected, which + // re-evaluation retries. Both changes are rare (authoring), so this rescan is acceptable; the common // unchanged path skips it entirely. - if (filterChanged) + if (filterChanged || resolutionChanged) { _meshRenderers.ReevaluateAll(_sharedMaterials, world, _renderingLayerMaskFilter); _entityInstances.ReevaluateAll(_sharedMaterials, world, _renderingLayerMaskFilter); #if ENABLE_TERRAIN_MODULE _terrains.ReevaluateAll(_sharedMaterials, world, _renderingLayerMaskFilter); #endif - _lights.ReevaluateAll(world, _renderingLayerMaskFilter); } + if (filterChanged) + _lights.ReevaluateAll(world, _renderingLayerMaskFilter); UpdateMaterials(changes.MaterialChangedList, world); UpdateEnvironment( @@ -168,7 +182,7 @@ void UpdateMeshRenderers(NativeArray transformChangedIds, NativeArray< _meshRenderers.TryRemove(entityId, _sharedMaterials, world); } - void UpdateEntityInstances(NativeArray transformChanged, NativeArray changed, NativeArray materials, NativeArray destroyed, SurfaceCacheWorld world) + void UpdateEntityInstances(NativeArray transformChanged, NativeArray changed, NativeArray materials, NativeArray overrides, NativeArray destroyed, SurfaceCacheWorld world) { using var _ = k_EntityInstanceUpdateMarker.Auto(); @@ -181,7 +195,7 @@ void UpdateEntityInstances(NativeArray transf _entityInstances.TryRemove(key, _sharedMaterials, world); foreach (var record in changed) - _entityInstances.Refresh(_entityInstances.CreateSource(record, materials), _sharedMaterials, world, _renderingLayerMaskFilter); + _entityInstances.Refresh(_entityInstances.CreateSource(record, materials, overrides), _sharedMaterials, world, _renderingLayerMaskFilter); } #if ENABLE_TERRAIN_MODULE @@ -276,12 +290,7 @@ void UpdateMaterials(IReadOnlyList changed, SurfaceCacheWorld world) for (int i = 0; i < changed.Count; i++) { var material = (Material)changed[i]; - var matEntityId = material.GetEntityId(); - _sharedMaterials.RemoveMaterialMissingMetaPass(matEntityId); - if (_sharedMaterials.IsReferenced(matEntityId)) - { - _sharedMaterials.Update(matEntityId, material, world); - } + _sharedMaterials.Update(material.GetEntityId(), material, world); } // For now we do not explicitly handle material _removal_. This is acceptable for these reasons: @@ -291,20 +300,114 @@ void UpdateMaterials(IReadOnlyList changed, SurfaceCacheWorld world) // and tracking. It is a lot of work and cost for little gain. } + // Preview scene objects (e.g. Prefab Mode) dispatch transform changes but never their destruction. + static bool IsInPreviewScene(Component component) + { +#if UNITY_EDITOR + return UnityEditor.SceneManagement.EditorSceneManager.IsPreviewSceneObject(component); +#else + return false; +#endif + } + interface IInstanceSource { TKey Key { get; } bool Visible { get; } Mesh Mesh { get; } + int MeshLod { get; } uint RenderingLayerMask { get; } Matrix4x4 LocalToWorld { get; } - string OwnerName { get; } // May fill and return the given scratch list. Assignments outside subMeshCount are dropped. IReadOnlyList GetMaterials(List scratch, int subMeshCount); + // Adds the instance's values for the numeric properties of the material at materialIndex. + void GetOverrides(Material material, int materialIndex, List scratch); + } + + // Overrides are sorted by NameId, and null when the instance overrides nothing. + readonly struct SharedMaterialKey : IEquatable + { + public readonly EntityId Material; + public readonly SurfaceCacheMaterialOverride[] Overrides; + + public SharedMaterialKey(EntityId material) + { + Material = material; + Overrides = null; + } + + public SharedMaterialKey(EntityId material, SurfaceCacheMaterialOverride[] overrides) + { + Material = material; + Overrides = overrides; + } + + public bool Equals(SharedMaterialKey other) + { + return Material == other.Material && OverridesEqual(Overrides, other.Overrides); + } + + public override bool Equals(object obj) + { + return obj is SharedMaterialKey other && Equals(other); + } + + public override int GetHashCode() + { + int hash = Material.GetHashCode(); + if (Overrides != null) + { + foreach (var materialOverride in Overrides) + hash = HashCode.Combine(hash, materialOverride.NameId, materialOverride.Value); + } + + return hash; + } + + static bool OverridesEqual(SurfaceCacheMaterialOverride[] first, SurfaceCacheMaterialOverride[] second) + { + int length = first?.Length ?? 0; + if (length != (second?.Length ?? 0)) + return false; + + for (int i = 0; i < length; i++) + { + if (first[i].NameId != second[i].NameId || !first[i].Value.Equals(second[i].Value)) + return false; + } + + return true; + } + } + + static bool TryFindNumericProperty(Shader shader, int nameId, out int propertyIndex) + { + int propertyCount = shader.GetPropertyCount(); + for (int i = 0; i < propertyCount; i++) + { + if (shader.GetPropertyNameId(i) != nameId) + continue; + + propertyIndex = i; + return IsNumeric(shader.GetPropertyType(i)); + } + + propertyIndex = -1; + return false; + } + + static bool IsNumeric(ShaderPropertyType type) + { + return type == ShaderPropertyType.Float + || type == ShaderPropertyType.Range + || type == ShaderPropertyType.Color + || type == ShaderPropertyType.Vector; } readonly struct MeshRendererSource : IInstanceSource { + static MaterialPropertyBlock s_Properties; + readonly MeshRenderer _renderer; public MeshRendererSource(MeshRenderer renderer) @@ -315,7 +418,7 @@ public MeshRendererSource(MeshRenderer renderer) public EntityId Key => _renderer.GetEntityId(); // In an open subscene the live-converted entities are the source of truth, not the authoring renderers. - public bool Visible => _renderer.enabled && _renderer.gameObject.activeInHierarchy && !_renderer.gameObject.scene.isSubScene && IsInGlobalIlluminationLOD(_renderer); + public bool Visible => _renderer.enabled && _renderer.gameObject.activeInHierarchy && !_renderer.gameObject.scene.isSubScene && !IsInPreviewScene(_renderer) && IsInGlobalIlluminationLOD(_renderer); // A renderer outside any LODGroup contributes, matching an entity without a MeshLODComponent. static bool IsInGlobalIlluminationLOD(MeshRenderer renderer) @@ -341,17 +444,61 @@ public Mesh Mesh } } + public int MeshLod => _renderer.globalIlluminationMeshLod; + public uint RenderingLayerMask => _renderer.renderingLayerMask; public Matrix4x4 LocalToWorld => _renderer.transform.localToWorldMatrix; - public string OwnerName => _renderer.gameObject.name; - public IReadOnlyList GetMaterials(List scratch, int subMeshCount) { _renderer.GetSharedMaterials(scratch); return scratch; } + + public void GetOverrides(Material material, int materialIndex, List scratch) + { + if (!_renderer.HasPropertyBlock()) + return; + + // Rendering uses a material's own block in place of the renderer's block, not merged with it. + s_Properties ??= new MaterialPropertyBlock(); + _renderer.GetPropertyBlock(s_Properties, materialIndex); + if (s_Properties.isEmpty) + _renderer.GetPropertyBlock(s_Properties); + + var shader = material.shader; + int propertyCount = shader.GetPropertyCount(); + for (int i = 0; i < propertyCount; i++) + { + var type = shader.GetPropertyType(i); + if (!IsNumeric(type)) + continue; + + int nameId = shader.GetPropertyNameId(i); + if (TryGetOverride(s_Properties, nameId, type, out var value)) + scratch.Add(new SurfaceCacheMaterialOverride { NameId = nameId, Value = value }); + } + } + + static bool TryGetOverride(MaterialPropertyBlock properties, int nameId, ShaderPropertyType type, out Vector4 value) + { + bool isFloat = type == ShaderPropertyType.Float || type == ShaderPropertyType.Range; + if (isFloat && properties.HasFloat(nameId)) + { + value = new Vector4(properties.GetFloat(nameId), 0f, 0f, 0f); + return true; + } + + if (!isFloat && properties.HasVector(nameId)) + { + value = properties.GetVector(nameId); + return true; + } + + value = default; + return false; + } } readonly struct EntityRecordSource : IInstanceSource @@ -359,14 +506,17 @@ public IReadOnlyList GetMaterials(List scratch, int subMeshC readonly SurfaceCacheEntityInstanceRecord _record; // Copied out: a drained record only carries a range into a buffer the bridge reuses every frame. readonly SurfaceCacheSubMeshMaterial[] _materials; + readonly SurfaceCacheMaterialOverride[] _overrides; - public EntityRecordSource(in SurfaceCacheEntityInstanceRecord record, SurfaceCacheSubMeshMaterial[] materials) + public EntityRecordSource(in SurfaceCacheEntityInstanceRecord record, SurfaceCacheSubMeshMaterial[] materials, SurfaceCacheMaterialOverride[] overrides) { _record = record; _materials = materials; + _overrides = overrides; } public SurfaceCacheSubMeshMaterial[] SubMeshMaterials => _materials; + public SurfaceCacheMaterialOverride[] Overrides => _overrides; public EntityId Key => _record.Key; public bool Visible => _record.Visible; @@ -374,9 +524,9 @@ public EntityRecordSource(in SurfaceCacheEntityInstanceRecord record, SurfaceCac // Safe only because the live RenderMeshArrayHost keeps these meshes resident. public Mesh Mesh => _record.Mesh != EntityId.None ? Resources.EntityIdToObject(_record.Mesh) as Mesh : null; + public int MeshLod => _record.MeshLod; public uint RenderingLayerMask => _record.RenderingLayerMask; public Matrix4x4 LocalToWorld => _record.LocalToWorld; - public string OwnerName => _record.Key.ToString(); // Pads the producer's sparse assignments to one entry per submesh; unassigned ones stay null and are // masked out downstream. Out-of-range assignments are dropped rather than padded to, because @@ -400,11 +550,22 @@ public IReadOnlyList GetMaterials(List scratch, int subMeshC return scratch; } + // An entity can carry override components for properties its material's shader does not declare. + public void GetOverrides(Material material, int materialIndex, List scratch) + { + var shader = material.shader; + foreach (var materialOverride in _overrides) + { + if (TryFindNumericProperty(shader, materialOverride.NameId, out _)) + scratch.Add(materialOverride); + } + } + public EntityRecordSource WithLocalToWorld(in Matrix4x4 localToWorld) { var record = _record; record.LocalToWorld = localToWorld; - return new EntityRecordSource(record, _materials); + return new EntityRecordSource(record, _materials, _overrides); } } @@ -419,17 +580,19 @@ class InstanceSet readonly List _inWorld = new(); readonly List _handles = new(); readonly List _meshIds = new(); + readonly List _meshLods = new(); // The transform last applied to the world instance. readonly List _localToWorlds = new(); // Materials provided by the source the last time we checked ("null materials" are EntityId.None). - readonly List _inputMaterialIds = new(); + readonly List _inputMaterialKeys = new(); // Materials currently acquired from the shared set (may include the fallback material). - readonly List _acquiredMaterialIds = new(); + readonly List _acquiredMaterialKeys = new(); readonly List _reevaluateScratch = new(); readonly Material _fallbackMaterial; readonly List _materialScratch = new(); - readonly Dictionary> _freeMaterialIdArrays = new(); + readonly List _overrideScratch = new(); + readonly Dictionary> _freeMaterialKeyArrays = new(); public InstanceSet(Material fallbackMaterial) { @@ -458,11 +621,23 @@ public bool TryGetAppliedLocalToWorld(TKey key, out Matrix4x4 localToWorld) return false; } + public bool TryGetAppliedMeshLod(TKey key, out int meshLod) + { + if (_slots.TryGetValue(key, out int slot) && _inWorld[slot]) + { + meshLod = _meshLods[slot]; + return true; + } + + meshLod = 0; + return false; + } + public bool TryGetInputMaterialIds(TKey key, out EntityId[] materialIds) { if (_slots.TryGetValue(key, out int slot) && _inWorld[slot]) { - materialIds = _inputMaterialIds[slot]; + materialIds = Array.ConvertAll(_inputMaterialKeys[slot], materialKey => materialKey.Material); return true; } @@ -598,9 +773,10 @@ int Register(TKey key, in TSource source) _inWorld.Add(false); _handles.Add(default); _meshIds.Add(EntityId.None); + _meshLods.Add(0); _localToWorlds.Add(default); - _inputMaterialIds.Add(null); - _acquiredMaterialIds.Add(null); + _inputMaterialKeys.Add(null); + _acquiredMaterialKeys.Add(null); return slot; } @@ -617,9 +793,10 @@ void Unregister(int slot) _inWorld[slot] = _inWorld[last]; _handles[slot] = _handles[last]; _meshIds[slot] = _meshIds[last]; + _meshLods[slot] = _meshLods[last]; _localToWorlds[slot] = _localToWorlds[last]; - _inputMaterialIds[slot] = _inputMaterialIds[last]; - _acquiredMaterialIds[slot] = _acquiredMaterialIds[last]; + _inputMaterialKeys[slot] = _inputMaterialKeys[last]; + _acquiredMaterialKeys[slot] = _acquiredMaterialKeys[last]; _slots[_keys[slot]] = slot; } _keys.RemoveAt(last); @@ -627,9 +804,10 @@ void Unregister(int slot) _inWorld.RemoveAt(last); _handles.RemoveAt(last); _meshIds.RemoveAt(last); + _meshLods.RemoveAt(last); _localToWorlds.RemoveAt(last); - _inputMaterialIds.RemoveAt(last); - _acquiredMaterialIds.RemoveAt(last); + _inputMaterialKeys.RemoveAt(last); + _acquiredMaterialKeys.RemoveAt(last); } void AddToWorld(int slot, in TSource source, Mesh mesh, SharedMaterialSet sharedMaterials, SurfaceCacheWorld world) @@ -640,31 +818,35 @@ void AddToWorld(int slot, in TSource source, Mesh mesh, SharedMaterialSet shared Debug.Assert(_materialScratch.Count == 0); var inputMats = source.GetMaterials(_materialScratch, mesh.subMeshCount); - Span inputMatIds = stackalloc EntityId[mesh.subMeshCount]; - ResolveMaterialIds(inputMats, inputMatIds); + var inputMatKeys = ReuseOrCreateMaterialKeyArray(mesh.subMeshCount); + ResolveMaterialKeys(source, inputMats, null, inputMatKeys); Span acquiredMatHandles = stackalloc MaterialHandle[mesh.subMeshCount]; - Span acquiredMatIds = stackalloc EntityId[mesh.subMeshCount]; + var acquiredMatKeys = ReuseOrCreateMaterialKeyArray(mesh.subMeshCount); Span masks = stackalloc uint[mesh.subMeshCount]; - ResolveMaterialHandlesAndMasks(world, sharedMaterials, source, inputMats, acquiredMatHandles, acquiredMatIds, masks); + ResolveMaterialHandlesAndMasks(world, sharedMaterials, inputMats, inputMatKeys, acquiredMatHandles, acquiredMatKeys, masks); var localToWorld = source.LocalToWorld; + int meshLod = ResolveMeshLod(mesh, source.MeshLod); try { - _handles[slot] = world.AddInstance(mesh, acquiredMatHandles, masks, localToWorld); + _handles[slot] = world.AddInstance(mesh, acquiredMatHandles, masks, localToWorld, meshLod); } catch { - foreach (var matEntityId in acquiredMatIds) - sharedMaterials.Release(matEntityId, world); + foreach (var matKey in acquiredMatKeys) + sharedMaterials.Release(matKey, world); + RecycleMaterialKeyArray(inputMatKeys); + RecycleMaterialKeyArray(acquiredMatKeys); _materialScratch.Clear(); throw; } _meshIds[slot] = mesh.GetEntityId(); + _meshLods[slot] = meshLod; _localToWorlds[slot] = localToWorld; - _inputMaterialIds[slot] = CopyToReusedOrNewArray(inputMatIds); - _acquiredMaterialIds[slot] = CopyToReusedOrNewArray(acquiredMatIds); + _inputMaterialKeys[slot] = inputMatKeys; + _acquiredMaterialKeys[slot] = acquiredMatKeys; _inWorld[slot] = true; _materialScratch.Clear(); @@ -672,7 +854,7 @@ void AddToWorld(int slot, in TSource source, Mesh mesh, SharedMaterialSet shared void UpdateInWorld(int slot, in TSource source, Mesh mesh, SharedMaterialSet sharedMaterials, SurfaceCacheWorld world) { - if (_meshIds[slot] != mesh.GetEntityId()) + if (_meshIds[slot] != mesh.GetEntityId() || _meshLods[slot] != ResolveMeshLod(mesh, source.MeshLod)) { RemoveFromWorld(slot, sharedMaterials, world); AddToWorld(slot, source, mesh, sharedMaterials, world); @@ -683,27 +865,63 @@ void UpdateInWorld(int slot, in TSource source, Mesh mesh, SharedMaterialSet sha Debug.Assert(_materialScratch.Count == 0); var inputMats = source.GetMaterials(_materialScratch, mesh.subMeshCount); - Span inputMatIds = stackalloc EntityId[mesh.subMeshCount]; - ResolveMaterialIds(inputMats, inputMatIds); + var inputMatKeys = ReuseOrCreateMaterialKeyArray(mesh.subMeshCount); + ResolveMaterialKeys(source, inputMats, _inputMaterialKeys[slot], inputMatKeys); - bool materialsChanged = !((ReadOnlySpan)inputMatIds).SequenceEqual(_inputMaterialIds[slot]); - if (materialsChanged) + bool materialsChanged = !((ReadOnlySpan)inputMatKeys).SequenceEqual(_inputMaterialKeys[slot]); + if (materialsChanged || HasRejectedMaterials(_inputMaterialKeys[slot], _acquiredMaterialKeys[slot])) { Span acquiredMatHandles = stackalloc MaterialHandle[mesh.subMeshCount]; - Span acquiredMatIds = stackalloc EntityId[mesh.subMeshCount]; + var acquiredMatKeys = ReuseOrCreateMaterialKeyArray(mesh.subMeshCount); Span masks = stackalloc uint[mesh.subMeshCount]; - ResolveMaterialHandlesAndMasks(world, sharedMaterials, source, inputMats, acquiredMatHandles, acquiredMatIds, masks); + ResolveMaterialHandlesAndMasks(world, sharedMaterials, inputMats, inputMatKeys, acquiredMatHandles, acquiredMatKeys, masks); world.UpdateInstanceMaterials(_handles[slot], acquiredMatHandles); world.UpdateInstanceMask(_handles[slot], masks); - foreach (var matEntityId in _acquiredMaterialIds[slot]) - sharedMaterials.Release(matEntityId, world); + foreach (var matKey in _acquiredMaterialKeys[slot]) + sharedMaterials.Release(matKey, world); + + // Releasing the superseded materials can free the atlas space a rejected acquisition needed. + // A material can only be released once no instance uses it, so the rejected ones are detached first. + if (HasRejectedMaterials(inputMatKeys, acquiredMatKeys)) + { + for (int i = 0; i < acquiredMatKeys.Length; i++) + { + if (!IsRejected(inputMatKeys[i], acquiredMatKeys[i])) + continue; + + acquiredMatHandles[i] = MaterialHandle.Invalid; + masks[i] = 0u; + } + + world.UpdateInstanceMaterials(_handles[slot], acquiredMatHandles); + world.UpdateInstanceMask(_handles[slot], masks); - RecycleMaterialIdArray(_inputMaterialIds[slot]); - RecycleMaterialIdArray(_acquiredMaterialIds[slot]); - _inputMaterialIds[slot] = CopyToReusedOrNewArray(inputMatIds); - _acquiredMaterialIds[slot] = CopyToReusedOrNewArray(acquiredMatIds); + for (int i = 0; i < acquiredMatKeys.Length; i++) + { + if (acquiredMatHandles[i] == MaterialHandle.Invalid) + sharedMaterials.Release(acquiredMatKeys[i], world); + } + + for (int i = 0; i < acquiredMatKeys.Length; i++) + { + if (acquiredMatHandles[i] == MaterialHandle.Invalid) + AcquireMaterial(i, world, sharedMaterials, inputMats, inputMatKeys, acquiredMatHandles, acquiredMatKeys, masks); + } + + world.UpdateInstanceMaterials(_handles[slot], acquiredMatHandles); + world.UpdateInstanceMask(_handles[slot], masks); + } + + RecycleMaterialKeyArray(_inputMaterialKeys[slot]); + RecycleMaterialKeyArray(_acquiredMaterialKeys[slot]); + _inputMaterialKeys[slot] = inputMatKeys; + _acquiredMaterialKeys[slot] = acquiredMatKeys; + } + else + { + RecycleMaterialKeyArray(inputMatKeys); } _materialScratch.Clear(); @@ -711,30 +929,119 @@ void UpdateInWorld(int slot, in TSource source, Mesh mesh, SharedMaterialSet sha ApplyTransform(slot, source.LocalToWorld, world); } - void ResolveMaterialHandlesAndMasks(SurfaceCacheWorld world, SharedMaterialSet sharedMaterials, in TSource source, IReadOnlyList inputMats, Span acquiredMaterialHandles, Span acquiredMaterialEntityIds, Span masks) + static bool HasRejectedMaterials(SharedMaterialKey[] inputMatKeys, SharedMaterialKey[] acquiredMatKeys) { - for (int i = 0; i < acquiredMaterialHandles.Length; i++) + for (int i = 0; i < acquiredMatKeys.Length; i++) + { + if (IsRejected(inputMatKeys[i], acquiredMatKeys[i])) + return true; + } + + return false; + } + + // A material acquired without the overrides that did not fit is retried like a rejected one. + static bool IsRejected(in SharedMaterialKey inputMatKey, in SharedMaterialKey acquiredMatKey) + { + return acquiredMatKey.Material == EntityId.None + || (acquiredMatKey.Overrides == null && inputMatKey.Overrides != null && acquiredMatKey.Material == inputMatKey.Material); + } + + void ResolveMaterialKeys(in TSource source, IReadOnlyList inputMats, SharedMaterialKey[] previousKeys, SharedMaterialKey[] keys) + { + for (int i = 0; i < keys.Length; i++) { Material inputMat = i < inputMats.Count ? inputMats[i] : null; + if (inputMat == null) + { + keys[i] = new SharedMaterialKey(EntityId.None); + continue; + } + + Debug.Assert(_overrideScratch.Count == 0); + source.GetOverrides(inputMat, i, _overrideScratch); + SortByNameId(_overrideScratch); + + var matEntityId = inputMat.GetEntityId(); + if (_overrideScratch.Count == 0) + keys[i] = new SharedMaterialKey(matEntityId); + else if (previousKeys != null && i < previousKeys.Length && previousKeys[i].Material == matEntityId && OverridesMatch(previousKeys[i].Overrides, _overrideScratch)) + keys[i] = previousKeys[i]; + else + keys[i] = new SharedMaterialKey(matEntityId, _overrideScratch.ToArray()); + + _overrideScratch.Clear(); + } + } + + static void SortByNameId(List overrides) + { + for (int i = 1; i < overrides.Count; i++) + { + var current = overrides[i]; + int j = i - 1; + while (j >= 0 && overrides[j].NameId > current.NameId) + { + overrides[j + 1] = overrides[j]; + j--; + } + + overrides[j + 1] = current; + } + } + + static bool OverridesMatch(SurfaceCacheMaterialOverride[] overrides, List scratch) + { + if (overrides == null || overrides.Length != scratch.Count) + return false; + + for (int i = 0; i < overrides.Length; i++) + { + if (overrides[i].NameId != scratch[i].NameId || !overrides[i].Value.Equals(scratch[i].Value)) + return false; + } + + return true; + } + + void ResolveMaterialHandlesAndMasks(SurfaceCacheWorld world, SharedMaterialSet sharedMaterials, IReadOnlyList inputMats, SharedMaterialKey[] inputMaterialKeys, Span acquiredMaterialHandles, SharedMaterialKey[] acquiredMaterialKeys, Span masks) + { + for (int i = 0; i < acquiredMaterialHandles.Length; i++) + AcquireMaterial(i, world, sharedMaterials, inputMats, inputMaterialKeys, acquiredMaterialHandles, acquiredMaterialKeys, masks); + } + + void AcquireMaterial(int subMeshIndex, SurfaceCacheWorld world, SharedMaterialSet sharedMaterials, IReadOnlyList inputMats, SharedMaterialKey[] inputMaterialKeys, Span acquiredMaterialHandles, SharedMaterialKey[] acquiredMaterialKeys, Span masks) + { + Material inputMat = subMeshIndex < inputMats.Count ? inputMats[subMeshIndex] : null; + + bool matIsUnsetOrNoMetaPass = inputMat == null || inputMat.FindPass("Meta") == -1; - masks[i] = inputMat == null ? 0u : 1u; + masks[subMeshIndex] = matIsUnsetOrNoMetaPass ? 0u : 1u; - bool matIsSet = inputMat != null; - bool matIsSetAndHasMetaPass = matIsSet && inputMat.FindPass("Meta") != -1; - bool matIsUnsetOrNoMetaPass = !matIsSetAndHasMetaPass; - bool matIsSetAndNoMetaPass = matIsSet && matIsUnsetOrNoMetaPass; + // Acquiring the fallback even for unset materials buys the assumption that a handle always exists. + var acquiredMat = inputMat; + var acquiredMatKey = inputMaterialKeys[subMeshIndex]; + if (matIsUnsetOrNoMetaPass) + { + acquiredMat = _fallbackMaterial; + acquiredMatKey = new SharedMaterialKey(_fallbackMaterial.GetEntityId()); + } + + acquiredMaterialHandles[subMeshIndex] = sharedMaterials.Acquire(acquiredMatKey, acquiredMat, world); - if (matIsSetAndNoMetaPass && sharedMaterials.AddMaterialMissingMetaPass(inputMat.GetEntityId())) - Debug.LogError($"The material '{inputMat.name}' used by '{source.OwnerName}' does not have a 'Meta' shader pass and cannot be used by Surface Cache Global Illumination. A fallback material will be used for this material instead.", inputMat); + // Per-instance values can outgrow the atlas, so such an instance keeps contributing with the shared material. + if (acquiredMaterialHandles[subMeshIndex] == MaterialHandle.Invalid && acquiredMatKey.Overrides != null) + { + acquiredMatKey = new SharedMaterialKey(acquiredMatKey.Material); + acquiredMaterialHandles[subMeshIndex] = sharedMaterials.Acquire(acquiredMatKey, acquiredMat, world); + } - // Acquiring the fallback even for unset materials buys the assumption that a handle always exists. - var acquiredMat = inputMat; - if (matIsUnsetOrNoMetaPass) - acquiredMat = _fallbackMaterial; + acquiredMaterialKeys[subMeshIndex] = acquiredMatKey; - var acquiredMatEntityId = acquiredMat.GetEntityId(); - acquiredMaterialHandles[i] = sharedMaterials.Acquire(acquiredMatEntityId, acquiredMat, world); - acquiredMaterialEntityIds[i] = acquiredMatEntityId; + if (acquiredMaterialHandles[subMeshIndex] == MaterialHandle.Invalid) + { + masks[subMeshIndex] = 0u; + acquiredMaterialKeys[subMeshIndex] = new SharedMaterialKey(EntityId.None); } } @@ -742,33 +1049,34 @@ void RemoveFromWorld(int slot, SharedMaterialSet sharedMaterials, SurfaceCacheWo { Debug.Assert(_inWorld[slot]); world.RemoveInstance(_handles[slot]); - foreach (var matEntityId in _acquiredMaterialIds[slot]) - sharedMaterials.Release(matEntityId, world); - RecycleMaterialIdArray(_inputMaterialIds[slot]); - RecycleMaterialIdArray(_acquiredMaterialIds[slot]); + foreach (var matKey in _acquiredMaterialKeys[slot]) + sharedMaterials.Release(matKey, world); + RecycleMaterialKeyArray(_inputMaterialKeys[slot]); + RecycleMaterialKeyArray(_acquiredMaterialKeys[slot]); _handles[slot] = default; _meshIds[slot] = EntityId.None; + _meshLods[slot] = 0; _localToWorlds[slot] = default; - _inputMaterialIds[slot] = null; - _acquiredMaterialIds[slot] = null; + _inputMaterialKeys[slot] = null; + _acquiredMaterialKeys[slot] = null; _inWorld[slot] = false; } - EntityId[] CopyToReusedOrNewArray(ReadOnlySpan materialIds) + SharedMaterialKey[] ReuseOrCreateMaterialKeyArray(int length) { - var array = _freeMaterialIdArrays.TryGetValue(materialIds.Length, out var freeArrays) && freeArrays.Count != 0 + return _freeMaterialKeyArrays.TryGetValue(length, out var freeArrays) && freeArrays.Count != 0 ? freeArrays.Pop() - : new EntityId[materialIds.Length]; - materialIds.CopyTo(array); - return array; + : new SharedMaterialKey[length]; } - void RecycleMaterialIdArray(EntityId[] array) + void RecycleMaterialKeyArray(SharedMaterialKey[] array) { - if (!_freeMaterialIdArrays.TryGetValue(array.Length, out var freeArrays)) + // Pooled arrays would otherwise keep the override arrays alive. + Array.Clear(array, 0, array.Length); + if (!_freeMaterialKeyArrays.TryGetValue(array.Length, out var freeArrays)) { - freeArrays = new Stack(); - _freeMaterialIdArrays.Add(array.Length, freeArrays); + freeArrays = new Stack(); + _freeMaterialKeyArrays.Add(array.Length, freeArrays); } freeArrays.Push(array); @@ -779,6 +1087,7 @@ void RecycleMaterialIdArray(EntityId[] array) sealed class EntityInstanceSet : InstanceSet { readonly Dictionary> _freeSubMeshMaterialArrays = new(); + readonly Dictionary> _freeOverrideArrays = new(); public EntityInstanceSet(Material fallbackMaterial) : base(fallbackMaterial) @@ -795,65 +1104,77 @@ public void UpdateTransform(EntityId key, in Matrix4x4 localToWorld, SurfaceCach ApplyTransform(slot, localToWorld, world); } - public EntityRecordSource CreateSource(in SurfaceCacheEntityInstanceRecord record, NativeArray materials) + public EntityRecordSource CreateSource(in SurfaceCacheEntityInstanceRecord record, NativeArray materials, NativeArray overrides) { int count = record.MaterialsCount; // Such a record is never registered, so nothing reads its materials. if (count == 0 || !record.Visible || record.Mesh == EntityId.None) - return new EntityRecordSource(record, Array.Empty()); + return new EntityRecordSource(record, Array.Empty(), Array.Empty()); - // A registered key usually re-reports the same count, so its buffer is reused rather than reallocated. - var buffer = TryGetSlot(record.Key, out int slot) ? GetSource(slot).SubMeshMaterials : null; + // A registered key usually re-reports the same counts, so its buffers are reused rather than reallocated. + bool registered = TryGetSlot(record.Key, out int slot); + var buffer = registered ? GetSource(slot).SubMeshMaterials : null; if (buffer == null || buffer.Length != count) - buffer = ReuseOrCreateSubMeshMaterialArray(count); + buffer = ReuseOrCreateArray(_freeSubMeshMaterialArrays, count); NativeArray.Copy(materials, record.MaterialsStart, buffer, 0, count); - return new EntityRecordSource(record, buffer); + + int overrideCount = record.OverridesCount; + var overrideBuffer = registered ? GetSource(slot).Overrides : null; + if (overrideBuffer == null || overrideBuffer.Length != overrideCount) + overrideBuffer = ReuseOrCreateArray(_freeOverrideArrays, overrideCount); + + if (overrideCount != 0) + NativeArray.Copy(overrides, record.OverridesStart, overrideBuffer, 0, overrideCount); + + return new EntityRecordSource(record, buffer, overrideBuffer); } protected override void OnSourceReplaced(in EntityRecordSource previous, in EntityRecordSource replacement) { if (previous.SubMeshMaterials != replacement.SubMeshMaterials) - RecycleSubMeshMaterialArray(previous.SubMeshMaterials); + RecycleArray(_freeSubMeshMaterialArrays, previous.SubMeshMaterials); + if (previous.Overrides != replacement.Overrides) + RecycleArray(_freeOverrideArrays, previous.Overrides); } protected override void OnSourceUnregistered(in EntityRecordSource source) { - RecycleSubMeshMaterialArray(source.SubMeshMaterials); + RecycleArray(_freeSubMeshMaterialArrays, source.SubMeshMaterials); + RecycleArray(_freeOverrideArrays, source.Overrides); } - SurfaceCacheSubMeshMaterial[] ReuseOrCreateSubMeshMaterialArray(int length) + static T[] ReuseOrCreateArray(Dictionary> freeArraysByLength, int length) { - if (_freeSubMeshMaterialArrays.TryGetValue(length, out var freeArrays) && freeArrays.Count != 0) + if (length == 0) + return Array.Empty(); + + if (freeArraysByLength.TryGetValue(length, out var freeArrays) && freeArrays.Count != 0) return freeArrays.Pop(); - return new SurfaceCacheSubMeshMaterial[length]; + return new T[length]; } - void RecycleSubMeshMaterialArray(SurfaceCacheSubMeshMaterial[] array) + static void RecycleArray(Dictionary> freeArraysByLength, T[] array) { bool isSharedEmptyArray = array.Length == 0; if (isSharedEmptyArray) return; - if (!_freeSubMeshMaterialArrays.TryGetValue(array.Length, out var freeArrays)) + if (!freeArraysByLength.TryGetValue(array.Length, out var freeArrays)) { - freeArrays = new Stack(); - _freeSubMeshMaterialArrays.Add(array.Length, freeArrays); + freeArrays = new Stack(); + freeArraysByLength.Add(array.Length, freeArrays); } freeArrays.Push(array); } } - static void ResolveMaterialIds(IReadOnlyList materials, Span materialEntityIds) + static int ResolveMeshLod(Mesh mesh, int requestedMeshLod) { - for (int i = 0; i < materialEntityIds.Length; i++) - { - Material material = i < materials.Count ? materials[i] : null; - materialEntityIds[i] = material != null ? material.GetEntityId() : EntityId.None; - } + return Mathf.Clamp(requestedMeshLod, 0, mesh.lodCount - 1); } #if ENABLE_TERRAIN_MODULE @@ -909,7 +1230,7 @@ public void Refresh(Terrain terrain, SharedMaterialSet sharedMaterials, SurfaceC bool isRegistered = _slots.TryGetValue(id, out int slot); bool isInWorld = isRegistered && _inWorld[slot]; - bool shouldBeRegistered = terrain.isActiveAndEnabled && terrain.terrainData != null; + bool shouldBeRegistered = terrain.isActiveAndEnabled && terrain.terrainData != null && !IsInPreviewScene(terrain); bool matchesWorldFilter = (terrain.renderingLayerMask & renderingLayerMaskFilter) != 0; bool shouldBeInWorld = shouldBeRegistered && matchesWorldFilter; @@ -1064,8 +1385,10 @@ void AddToWorld(int slot, Terrain terrain, SharedMaterialSet sharedMaterials, Su Debug.Assert(terrainData != null); var inputMaterial = terrain.splatBaseMaterial; EntityId inputMatEntityId = inputMaterial != null ? inputMaterial.GetEntityId() : EntityId.None; - ResolveMaterialHandleAndMask(terrain, inputMaterial, inputMatEntityId, sharedMaterials, world, _fallbackMaterial, + ResolveMaterialHandleAndMask(inputMaterial, inputMatEntityId, sharedMaterials, world, _fallbackMaterial, out EntityId acquiredMatEntityId, out MaterialHandle matHandle, out uint mask); + if (matHandle == MaterialHandle.Invalid) + return; _handles[slot] = world.AddInstance(terrain, matHandle, mask, terrain.transform.localToWorldMatrix); _inputMaterialIds[slot] = inputMatEntityId; @@ -1091,9 +1414,9 @@ void UpdateInWorld(int slot, Terrain terrain, bool transformChange, SharedMateri var inputMat = terrain.splatBaseMaterial; var inputMatEntityId = inputMat != null ? inputMat.GetEntityId() : EntityId.None; - if (inputMatEntityId != _inputMaterialIds[slot]) + if (inputMatEntityId != _inputMaterialIds[slot] || _acquiredMaterialIds[slot] == EntityId.None) { - ResolveMaterialHandleAndMask(terrain, inputMat, inputMatEntityId, sharedMaterials, world, _fallbackMaterial, + ResolveMaterialHandleAndMask(inputMat, inputMatEntityId, sharedMaterials, world, _fallbackMaterial, out EntityId acquiredMatEntityId, out MaterialHandle acquiredMatHandle, out uint mask); Span matHandles = stackalloc MaterialHandle[1] { acquiredMatHandle }; @@ -1101,7 +1424,7 @@ void UpdateInWorld(int slot, Terrain terrain, bool transformChange, SharedMateri world.UpdateInstanceMaterials(_handles[slot], matHandles); world.UpdateInstanceMask(_handles[slot], masks); - sharedMaterials.Release(_acquiredMaterialIds[slot], world); + sharedMaterials.Release(new SharedMaterialKey(_acquiredMaterialIds[slot]), world); _inputMaterialIds[slot] = inputMatEntityId; _acquiredMaterialIds[slot] = acquiredMatEntityId; @@ -1112,7 +1435,7 @@ void RemoveFromWorld(int slot, SharedMaterialSet sharedMaterials, SurfaceCacheWo { Debug.Assert(_inWorld[slot]); world.RemoveInstance(_handles[slot]); - sharedMaterials.Release(_acquiredMaterialIds[slot], world); + sharedMaterials.Release(new SharedMaterialKey(_acquiredMaterialIds[slot]), world); _handles[slot] = default; _inputMaterialIds[slot] = EntityId.None; _acquiredMaterialIds[slot] = EntityId.None; @@ -1130,17 +1453,11 @@ void RebuildInstance(int slot, SharedMaterialSet sharedMaterials, SurfaceCacheWo AddToWorld(slot, _components[slot], sharedMaterials, world); } - static void ResolveMaterialHandleAndMask(Terrain terrain, Material inputMat, EntityId inputMatEntityId, SharedMaterialSet sharedMaterials, SurfaceCacheWorld world, Material fallbackMaterial, out EntityId acquiredMatEntityId, out MaterialHandle acquiredMatHandle, out uint mask) + static void ResolveMaterialHandleAndMask(Material inputMat, EntityId inputMatEntityId, SharedMaterialSet sharedMaterials, SurfaceCacheWorld world, Material fallbackMaterial, out EntityId acquiredMatEntityId, out MaterialHandle acquiredMatHandle, out uint mask) { - mask = inputMat == null ? 0u : 1u; + bool matIsUnsetOrNoMetaPass = inputMat == null || inputMat.FindPass("Meta") == -1; - bool matIsSet = inputMat != null; - bool matIsSetAndHasMetaPass = matIsSet && inputMat.FindPass("Meta") != -1; - bool matIsUnsetOrNoMetaPass = !matIsSetAndHasMetaPass; - bool matIsSetAndNoMetaPass = matIsSet && matIsUnsetOrNoMetaPass; - - if (matIsSetAndNoMetaPass && sharedMaterials.AddMaterialMissingMetaPass(inputMatEntityId)) - Debug.LogError($"The material '{inputMat.name}' used by terrain '{terrain.gameObject.name}' does not have a 'Meta' shader pass and cannot be used by Surface Cache Global Illumination. A fallback material will be used for this material instead.", inputMat); + mask = matIsUnsetOrNoMetaPass ? 0u : 1u; // Using fallback material when there is no input material is redundant, but we do it anyway // because this buys us the simplifying assumption that we always have some material handle. @@ -1155,7 +1472,12 @@ static void ResolveMaterialHandleAndMask(Terrain terrain, Material inputMat, Ent acquiredMatEntityId = inputMatEntityId; acquiredMat = inputMat; } - acquiredMatHandle = sharedMaterials.Acquire(acquiredMatEntityId, acquiredMat, world); + acquiredMatHandle = sharedMaterials.Acquire(new SharedMaterialKey(acquiredMatEntityId), acquiredMat, world); + if (acquiredMatHandle == MaterialHandle.Invalid) + { + mask = 0u; + acquiredMatEntityId = EntityId.None; + } } } #endif @@ -1187,7 +1509,7 @@ public void Refresh(Light light, SurfaceCacheWorld world, uint renderingLayerMas bool isRegistered = _slots.TryGetValue(id, out int slot); bool isInWorld = isRegistered && _inWorld[slot]; - bool shouldBeRegistered = light.isActiveAndEnabled && !light.bakingOutput.isBaked; + bool shouldBeRegistered = light.isActiveAndEnabled && !light.bakingOutput.isBaked && !IsInPreviewScene(light); bool matchesWorldFilter = ((uint)light.renderingLayerMask & renderingLayerMaskFilter) != 0; bool shouldBeInWorld = shouldBeRegistered && matchesWorldFilter; @@ -1311,28 +1633,60 @@ struct Entry public Material Material; public MaterialHandle WorldHandle; public uint RefCount; - public MaterialPool.MaterialDescriptor Descriptor; } const EmissionMode kEmissionMode = EmissionMode.Realtime; const UVChannel kUVChannel = UVChannel.UV0; + static readonly int k_EmissionColorId = Shader.PropertyToID("_EmissionColor"); - readonly Dictionary _entries = new(); - readonly HashSet _pendingMetaPassEvals = new(); - readonly HashSet _materialsMissingMetaPass = new(); + readonly Dictionary _entries = new(); + readonly HashSet _pendingMetaPassEvals = new(); + readonly HashSet _reportedRejections = new(); + readonly List _keyScratch = new(); readonly Material _fallbackMaterial; + int _resolution = 256; public SharedMaterialSet(Material fallbackMaterial) { _fallbackMaterial = fallbackMaterial; } - public MaterialHandle Acquire(EntityId matEntityId, Material mat, SurfaceCacheWorld world) + public bool SetResolution(int resolution, SurfaceCacheWorld world) + { + if (resolution == _resolution) + return false; + + _resolution = resolution; + _reportedRejections.Clear(); + + _keyScratch.Clear(); + _keyScratch.AddRange(_entries.Keys); + foreach (var matKey in _keyScratch) + { + if (_pendingMetaPassEvals.Contains(matKey)) + continue; + + var entry = _entries[matKey]; + if (entry.Material == null) + continue; + +#if UNITY_EDITOR + var descriptor = entry.Material.FindPass("Meta") == -1 ? GetFallbackMaterialDescriptor() : CreateDescriptor(matKey, entry.Material); +#else + var descriptor = CreateDescriptor(matKey, entry.Material); +#endif + UpdateInWorld(matKey, entry, descriptor, world); + } + _keyScratch.Clear(); + return true; + } + + public MaterialHandle Acquire(in SharedMaterialKey matKey, Material mat, SurfaceCacheWorld world) { - if (_entries.TryGetValue(matEntityId, out var entry)) + if (_entries.TryGetValue(matKey, out var entry)) { entry.RefCount += 1; - _entries[matEntityId] = entry; + _entries[matKey] = entry; return entry.WorldHandle; } else @@ -1343,27 +1697,34 @@ public MaterialHandle Acquire(EntityId matEntityId, Material mat, SurfaceCacheWo #if UNITY_EDITOR if (UnityEditor.ShaderUtil.IsPassCompiled(mat, metaPassIndex)) { - descriptor = MaterialPool.ConvertUnityMaterialToMaterialDescriptor(mat, kEmissionMode); + descriptor = CreateDescriptor(matKey, mat); } else { descriptor = GetFallbackMaterialDescriptor(); - _pendingMetaPassEvals.Add(matEntityId); + _pendingMetaPassEvals.Add(matKey); UnityEditor.ShaderUtil.CompilePass(mat, metaPassIndex); } #else - descriptor = MaterialPool.ConvertUnityMaterialToMaterialDescriptor(mat, EmissionMode.Realtime); + descriptor = CreateDescriptor(matKey, mat); #endif var newHandle = world.AddMaterial(descriptor, kUVChannel); + DestroyDescriptorTextures(descriptor); + if (newHandle == MaterialHandle.Invalid) + { + _pendingMetaPassEvals.Remove(matKey); + ReportRejection(matKey.Material, mat); + return MaterialHandle.Invalid; + } + var newEntry = new Entry { RefCount = 1, WorldHandle = newHandle, - Descriptor = descriptor, Material = mat }; - _entries[matEntityId] = newEntry; + _entries[matKey] = newEntry; return newHandle; } } @@ -1373,25 +1734,22 @@ public void Update(SurfaceCacheWorld world) { if (_pendingMetaPassEvals.Count != 0) { - var evaluatedMaterials = new List(); - foreach (var matEntityId in _pendingMetaPassEvals) + var evaluatedMaterials = new List(); + foreach (var matKey in _pendingMetaPassEvals) { - var entry = _entries[matEntityId]; + var entry = _entries[matKey]; var metaPassIndex = entry.Material.FindPass("Meta"); Debug.Assert(metaPassIndex != -1); if (UnityEditor.ShaderUtil.IsPassCompiled(entry.Material, metaPassIndex)) { - DestroyDescriptorTextures(entry.Descriptor); - entry.Descriptor = MaterialPool.ConvertUnityMaterialToMaterialDescriptor(entry.Material, kEmissionMode); - world.UpdateMaterial(entry.WorldHandle, entry.Descriptor, kUVChannel); - _entries[matEntityId] = entry; - evaluatedMaterials.Add(matEntityId); + UpdateInWorld(matKey, entry, CreateDescriptor(matKey, entry.Material), world); + evaluatedMaterials.Add(matKey); } } - foreach (var matEntityId in evaluatedMaterials) + foreach (var matKey in evaluatedMaterials) { - _pendingMetaPassEvals.Remove(matEntityId); + _pendingMetaPassEvals.Remove(matKey); } } } @@ -1399,81 +1757,136 @@ public void Update(SurfaceCacheWorld world) public void Update(EntityId matEntityId, Material material, SurfaceCacheWorld world) { - Debug.Assert(_entries.ContainsKey(matEntityId)); + _keyScratch.Clear(); + foreach (var matKey in _entries.Keys) + { + if (matKey.Material == matEntityId) + _keyScratch.Add(matKey); + } + + foreach (var matKey in _keyScratch) + Update(matKey, material, world); - if (!_pendingMetaPassEvals.Contains(matEntityId)) + _keyScratch.Clear(); + } + + void Update(in SharedMaterialKey matKey, Material material, SurfaceCacheWorld world) + { + if (!_pendingMetaPassEvals.Contains(matKey)) { #if UNITY_EDITOR // If the shader was modified, the meta pass may have been deleted, or not yet compiled. var metaPassIndex = material.FindPass("Meta"); if (metaPassIndex == -1) { - var fallbackEntry = _entries[matEntityId]; - DestroyDescriptorTextures(fallbackEntry.Descriptor); - fallbackEntry.Descriptor = GetFallbackMaterialDescriptor(); - _entries[matEntityId] = fallbackEntry; - - world.UpdateMaterial(fallbackEntry.WorldHandle, in fallbackEntry.Descriptor, kUVChannel); + UpdateInWorld(matKey, _entries[matKey], GetFallbackMaterialDescriptor(), world); return; } else if (!UnityEditor.ShaderUtil.IsPassCompiled(material, metaPassIndex)) { - _pendingMetaPassEvals.Add(matEntityId); + _pendingMetaPassEvals.Add(matKey); UnityEditor.ShaderUtil.CompilePass(material, metaPassIndex); return; } #endif - var entry = _entries[matEntityId]; - DestroyDescriptorTextures(entry.Descriptor); - entry.Descriptor = MaterialPool.ConvertUnityMaterialToMaterialDescriptor(material, kEmissionMode); - _entries[matEntityId] = entry; - - world.UpdateMaterial(entry.WorldHandle, in entry.Descriptor, kUVChannel); + UpdateInWorld(matKey, _entries[matKey], CreateDescriptor(matKey, material), world); } } - public bool AddMaterialMissingMetaPass(EntityId matEntityId) + public void Release(in SharedMaterialKey matKey, SurfaceCacheWorld world) { - return _materialsMissingMetaPass.Add(matEntityId); + if (matKey.Material == EntityId.None) + return; + + Debug.Assert(_entries.ContainsKey(matKey)); + var entry = _entries[matKey]; + + if (entry.RefCount == 1) + { + RemoveHandle(matKey, world); + } + else + { + entry.RefCount -= 1; + _entries[matKey] = entry; + } } - public void RemoveMaterialMissingMetaPass(EntityId matEntityId) + public void CleanUp(SurfaceCacheWorld world) { - _materialsMissingMetaPass.Remove(matEntityId); + var keys = new SharedMaterialKey[_entries.Count]; + + int i = 0; + foreach (var key in _entries.Keys) + keys[i++] = key; + + foreach (var key in keys) + RemoveHandle(key, world); } - public bool IsReferenced(EntityId matEntityId) + MaterialPool.MaterialDescriptor CreateDescriptor(Material material) { - return _entries.ContainsKey(matEntityId); + return MaterialPool.ConvertUnityMaterialToMaterialDescriptor(material, kEmissionMode, _resolution); } - public void Release(EntityId matEntityId, SurfaceCacheWorld world) + // The overrides are applied to a copy, so the meta pass and the emission read them like material values. + MaterialPool.MaterialDescriptor CreateDescriptor(in SharedMaterialKey matKey, Material material) { - Debug.Assert(_entries.ContainsKey(matEntityId)); - var entry = _entries[matEntityId]; + if (matKey.Overrides == null) + return CreateDescriptor(material); - if (entry.RefCount == 1) + var overridden = new Material(material) { hideFlags = HideFlags.HideAndDontSave }; + try { - RemoveHandle(matEntityId, world); + ApplyOverrides(overridden, matKey.Overrides); + return CreateDescriptor(overridden); } - else + finally { - entry.RefCount -= 1; - _entries[matEntityId] = entry; + CoreUtils.Destroy(overridden); } } - public void CleanUp(SurfaceCacheWorld world) + static void ApplyOverrides(Material material, SurfaceCacheMaterialOverride[] overrides) { - var ids = new EntityId[_entries.Count]; + var shader = material.shader; + bool linear = QualitySettings.activeColorSpace == ColorSpace.Linear; + foreach (var materialOverride in overrides) + { + if (!TryFindNumericProperty(shader, materialOverride.NameId, out int propertyIndex)) + continue; - int i = 0; - foreach (var key in _entries.Keys) - ids[i++] = key; + var type = shader.GetPropertyType(propertyIndex); + var flags = shader.GetPropertyFlags(propertyIndex); - foreach (var id in ids) - RemoveHandle(id, world); + // The setters convert sRGB properties from gamma, and the override is already in the active color space. + bool isSRGB = (type == ShaderPropertyType.Color && (flags & ShaderPropertyFlags.HDR) == 0) || (flags & ShaderPropertyFlags.Gamma) != 0; + bool toGamma = isSRGB && linear; + + var value = materialOverride.Value; + if (type == ShaderPropertyType.Float || type == ShaderPropertyType.Range) + material.SetFloat(materialOverride.NameId, toGamma ? Mathf.LinearToGammaSpace(value.x) : value.x); + else + material.SetVector(materialOverride.NameId, toGamma ? (Vector4)((Color)value).gamma : value); + } + + // The inspector derives EmissiveIsBlack from the material's own emission color, which an override can replace. + var giFlags = material.globalIlluminationFlags; + bool emissiveIsBlackDerived = (giFlags & MaterialGlobalIlluminationFlags.EmissiveIsBlack) != 0 && giFlags != MaterialGlobalIlluminationFlags.EmissiveIsBlack; + if (emissiveIsBlackDerived && HasOverride(overrides, k_EmissionColorId) && material.GetColor(k_EmissionColorId).maxColorComponent > 0f) + material.globalIlluminationFlags = giFlags & ~MaterialGlobalIlluminationFlags.EmissiveIsBlack; + } + + static bool HasOverride(SurfaceCacheMaterialOverride[] overrides, int nameId) + { + foreach (var materialOverride in overrides) + { + if (materialOverride.NameId == nameId) + return true; + } + + return false; } #if UNITY_EDITOR @@ -1481,19 +1894,32 @@ MaterialPool.MaterialDescriptor GetFallbackMaterialDescriptor() { var oldAllowAsyncCompilation = UnityEditor.ShaderUtil.allowAsyncCompilation; UnityEditor.ShaderUtil.allowAsyncCompilation = false; - var descriptor = MaterialPool.ConvertUnityMaterialToMaterialDescriptor(_fallbackMaterial, kEmissionMode); + var descriptor = CreateDescriptor(_fallbackMaterial); UnityEditor.ShaderUtil.allowAsyncCompilation = oldAllowAsyncCompilation; return descriptor; } #endif - void RemoveHandle(EntityId matEntityId, SurfaceCacheWorld world) + void UpdateInWorld(in SharedMaterialKey matKey, in Entry entry, in MaterialPool.MaterialDescriptor descriptor, SurfaceCacheWorld world) + { + bool updated = world.UpdateMaterial(entry.WorldHandle, in descriptor, kUVChannel); + DestroyDescriptorTextures(descriptor); + if (!updated) + ReportRejection(matKey.Material, entry.Material); + } + + void ReportRejection(EntityId matEntityId, Material mat) + { + if (_reportedRejections.Add(matEntityId)) + Debug.LogError($"Surface Cache GI: material '{mat.name}' could not be added because the material texture atlas is full ({SystemInfo.maxTextureArraySlices} slices). Lower 'Material Resolution' on the Surface Cache GI renderer feature or share materials between objects.", mat); + } + + void RemoveHandle(in SharedMaterialKey matKey, SurfaceCacheWorld world) { - _pendingMetaPassEvals.Remove(matEntityId); - var entry = _entries[matEntityId]; + _pendingMetaPassEvals.Remove(matKey); + var entry = _entries[matKey]; world.RemoveMaterial(entry.WorldHandle); - _entries.Remove(matEntityId); - DestroyDescriptorTextures(entry.Descriptor); + _entries.Remove(matKey); } static void DestroyDescriptorTextures(in MaterialPool.MaterialDescriptor desc) diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/SurfaceCacheWorldChangeSet.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/SurfaceCacheWorldChangeSet.cs index 888181f76a1..b89aef758ec 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/SurfaceCacheWorldChangeSet.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/SurfaceCacheWorldChangeSet.cs @@ -24,6 +24,7 @@ sealed class SurfaceCacheWorldChangeSet public NativeArray EntityInstanceChangedList { get; set; } public NativeArray EntityInstanceMaterialList { get; set; } + public NativeArray EntityInstanceMaterialOverrideList { get; set; } public NativeArray EntityInstanceTransformChangedList { get; set; } public NativeArray EntityInstanceDestroyedList { get; set; } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RenderingLayerUtils.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RenderingLayerUtils.cs index 1d35f193b3c..1cdd46ff18a 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/RenderingLayerUtils.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RenderingLayerUtils.cs @@ -86,17 +86,6 @@ internal static bool RequireRenderingLayers(List rend return result; } - /// - /// Sets property that is needed to write into rendering layers texture. - /// - /// Used command buffer - /// The mask size of rendering layers texture - public static void SetupProperties(CommandBuffer cmd, MaskSize maskSize) { SetupProperties(CommandBufferHelpers.GetRasterCommandBuffer(cmd), maskSize); } - internal static void SetupProperties(RasterCommandBuffer cmd, MaskSize maskSize) - { - cmd.SetGlobalInt(ShaderPropertyId.renderingLayerMaxInt, (int)GetMaxInt(maskSize)); - } - /// /// The mask holding every bit a rendering layers texture of that size can store. Single source of truth: the /// enum to bit count mapping lives in GetBits, deriving it from the enum ordinal breaks when a value is inserted. diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RenderingUtils.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RenderingUtils.cs index 3fa9f2aa44d..79be061957c 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/RenderingUtils.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RenderingUtils.cs @@ -97,14 +97,21 @@ internal static bool useStructuredBuffer } // Persistent CBUFFERs exist on C# side as Graphics/ComputeBuffer and are filled with SetData(), unlike transient CBUFFERs that have no real existence on C# side + // Must be kept in sync with URP_PERSISTENT_CONSTANT_BUFFERS_ACTIVE in GlobalShaderVariables.hlsl internal static bool usePersistentConstantBuffer { get { - // - On GLES3 non-WebGL, CBs are disabled (not even transient, see LIGHT_SHADOWS_NO_CBUFFER) due to Adreno perf issues with large CBs - // - On WebGL, CBs remains temporarily transient due to a graphics buffer bug + // - On GLES3 non-WebGL, CBs are disabled (not even transient, see URP_PERSISTENT_CONSTANT_BUFFERS_ACTIVE) due to Adreno perf issues with large CBs + // - WebGL reports as GLES3 but keeps its light data in CBs, so it uses the persistent CB path too // - Everywhere else we use the persistent CB path for optimal performance at shader setup on native engine side. - return SystemInfo.graphicsDeviceType != GraphicsDeviceType.OpenGLES3; + // The shaders get UNITY_PLATFORM_WEBGL from the build target, so in the Editor this follows the active build target. +#if UNITY_EDITOR + bool isWebGL = UnityEditor.EditorUserBuildSettings.activeBuildTarget == UnityEditor.BuildTarget.WebGL; +#else + bool isWebGL = Application.platform == RuntimePlatform.WebGLPlayer; +#endif + return SystemInfo.graphicsDeviceType != GraphicsDeviceType.OpenGLES3 || isWebGL; } } @@ -243,6 +250,33 @@ internal static Vector2Int GetScreenBackbufferSize(Camera camera) return new Vector2Int(Screen.width, Screen.height); } + // The camera's _ZBufferParams, with the reversed-Z flip. + internal static Vector4 ComputeZBufferParams(Camera camera) + { + float far = camera.farClipPlane; + float invNear = Mathf.Approximately(camera.nearClipPlane, 0.0f) ? 0.0f : 1.0f / camera.nearClipPlane; + float invFar = Mathf.Approximately(far, 0.0f) ? 0.0f : 1.0f / far; + + // From http://www.humus.name/temp/Linearize%20depth.txt + // But as depth component textures on OpenGL always return in 0..1 range (as in D3D), we have to use + // the same constants for both D3D and OpenGL here. + // D3D is this: + float zc0 = 1.0f - far * invNear; + float zc1 = far * invNear; + + Vector4 zBufferParams = new Vector4(zc0, zc1, zc0 * invFar, zc1 * invFar); + + if (SystemInfo.usesReversedZBuffer) + { + zBufferParams.y += zBufferParams.x; + zBufferParams.x = -zBufferParams.x; + zBufferParams.w += zBufferParams.z; + zBufferParams.z = -zBufferParams.z; + } + + return zBufferParams; + } + internal static void SetupOffscreenUIViewportParams(UniversalCameraData cameraData, Material material, ref Rect pixelRect, bool isRenderToBackBufferTarget) { Vector4 offscreenUIViewportParams = new Vector4(0f, 0f, 1f, 1f); @@ -297,6 +331,12 @@ internal static void DrawRendererListObjectsWithError(RasterCommandBuffer cmd, r cmd.DrawRendererList(rl); } + // Material alpha clipping relies on _AlphaToMaskAvailable to know whether AlphaToMask may be active. + internal static void SetAlphaToMaskAvailable(RasterCommandBuffer cmd, bool enabled) + { + cmd.SetGlobalFloat(ShaderPropertyId.alphaToMaskAvailable, enabled ? 1.0f : 0.0f); + } + static readonly ShaderTagId[] s_ShaderTagValues = new ShaderTagId[1]; static readonly RenderStateBlock[] s_RenderStateBlocks = new RenderStateBlock[1]; // Create a RendererList using a RenderStateBlock override is quite common so we have this optimized utility function for it @@ -315,6 +355,27 @@ internal static void CreateRendererListWithRenderStateBlock(RenderGraph renderGr rl = renderGraph.CreateRendererList(param); } + internal static ulong GetSceneCullingMaskFromCamera(Camera camera) + { +#if UNITY_EDITOR + if (camera.overrideSceneCullingMask != 0) + return camera.overrideSceneCullingMask; + + if (camera.scene.IsValid()) + return UnityEditor.SceneManagement.EditorSceneManager.GetSceneCullingMask(camera.scene); + + switch (camera.cameraType) + { + case CameraType.SceneView: + return UnityEditor.SceneManagement.SceneCullingMasks.MainStageSceneViewObjects; + default: + return UnityEditor.SceneManagement.SceneCullingMasks.GameViewObjects; + } +#else + return 0; +#endif + } + // Caches render texture format support. SystemInfo.SupportsRenderTextureFormat allocates memory due to boxing. static readonly Dictionary s_RenderTextureFormatSupport = new Dictionary(); @@ -757,7 +818,7 @@ public static bool SetMaxRTHandlePoolCapacity(int capacity) /// internal static void AddStaleResourceToPoolOrRelease(TextureDesc desc, RTHandle handle) { - if (!UniversalRenderPipeline.s_RTHandlePool.AddResourceToPool(desc, handle, Time.frameCount)) + if (!UniversalRenderPipeline.s_RTHandlePool.AddResourceToPool(desc, handle, UniversalRenderPipeline.resourcePoolFrameIndex)) RTHandles.Release(handle); } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/SceneViewDrawMode.cs b/Packages/com.unity.render-pipelines.universal/Runtime/SceneViewDrawMode.cs index a1219f6e783..ea1f256f5a7 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/SceneViewDrawMode.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/SceneViewDrawMode.cs @@ -8,6 +8,7 @@ internal static class SceneViewDrawMode { static HashSet sceneViewHaveValidateFunction = new HashSet(); +#pragma warning disable CS0618 // Type or member is obsolete static bool RejectDrawMode(SceneView.CameraMode cameraMode) { if (cameraMode.drawMode == DrawCameraMode.ShadowCascades || @@ -28,6 +29,7 @@ static bool RejectDrawMode(SceneView.CameraMode cameraMode) return true; } +#pragma warning restore CS0618 static void UpdateSceneViewStates() { diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/ScriptableRenderer.cs b/Packages/com.unity.render-pipelines.universal/Runtime/ScriptableRenderer.cs index adfba3aec93..fc4a8616d19 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/ScriptableRenderer.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/ScriptableRenderer.cs @@ -256,32 +256,12 @@ void SetPerCameraShaderVariables(GlobalShaderVariablesUploader vars, UniversalCa scaledCameraTargetHeight *= ScalableBufferManager.heightScaleFactor; } - float far = camera.farClipPlane; - float invNear = Mathf.Approximately(camera.nearClipPlane, 0.0f) ? 0.0f : 1.0f / camera.nearClipPlane; - float invFar = Mathf.Approximately(far, 0.0f) ? 0.0f : 1.0f / far; float isOrthographic = camera.orthographic ? 1.0f : 0.0f; - // From http://www.humus.name/temp/Linearize%20depth.txt - // But as depth component textures on OpenGL always return in 0..1 range (as in D3D), we have to use - // the same constants for both D3D and OpenGL here. - // D3D is this: - float zc0 = 1.0f - far * invNear; - float zc1 = far * invNear; - - Vector4 zBufferParams = new Vector4(zc0, zc1, zc0 * invFar, zc1 * invFar); - - if (SystemInfo.usesReversedZBuffer) - { - zBufferParams.y += zBufferParams.x; - zBufferParams.x = -zBufferParams.x; - zBufferParams.w += zBufferParams.z; - zBufferParams.z = -zBufferParams.z; - } - // Camera and Screen variables as described in https://docs.unity3d.com/Manual/SL-UnityShaderVariables.html vars._ScreenParams = new Vector4(cameraWidth, cameraHeight, 1.0f + 1.0f / cameraWidth, 1.0f + 1.0f / cameraHeight); vars._ScaledScreenParams = new Vector4(scaledCameraTargetWidth, scaledCameraTargetHeight, 1.0f + 1.0f / scaledCameraTargetWidth, 1.0f + 1.0f / scaledCameraTargetHeight); - vars._ZBufferParams = zBufferParams; + vars._ZBufferParams = RenderingUtils.ComputeZBufferParams(camera); vars.unity_OrthoParams = new Vector4(camera.orthographicSize * cameraData.aspectRatio, camera.orthographicSize, 0.0f, isOrthographic); vars._ScreenSize = new Vector4(scaledCameraTargetWidth, scaledCameraTargetHeight, 1.0f / scaledCameraTargetWidth, 1.0f / scaledCameraTargetHeight); vars._ScreenSizeOverride = cameraData.screenSizeOverride; @@ -639,7 +619,7 @@ internal virtual void InitRenderGraphFrame(RenderGraph renderGraph) InitDefaultGlobalKeywords(cmd, data.cameraData); - data.shaderData.Get().PushDefaultToGlobal(cmd); + data.shaderData.GetGlobal().PushDefault(cmd); }); } } @@ -662,6 +642,7 @@ internal static void InitDefaultGlobalKeywords(IBaseCommandBuffer cmd, Universal cmd.SetKeyword(ShaderGlobalKeywords.SoftShadowsLow, false); cmd.SetKeyword(ShaderGlobalKeywords.SoftShadowsMedium, false); cmd.SetKeyword(ShaderGlobalKeywords.SoftShadowsHigh, false); + cmd.SetKeyword(ShaderGlobalKeywords.ShadowsPCSS, false); cmd.SetKeyword(ShaderGlobalKeywords.LinearToSRGBConversion, false); cmd.SetKeyword(ShaderGlobalKeywords.LightLayers, false); @@ -679,6 +660,7 @@ void InitGlobalShaderVariablesBase() // A custom renderer only gets the base vars, the URP 3D and 2D renderers add their own group. m_GlobalShaderVariablesUploader ??= new GlobalShaderVariablesUploader(GlobalShaderVariablesGroup.Base); + m_GlobalShaderVariablesUploader.useConstantBuffer = UniversalRenderPipeline.useGlobalConstantBuffer; m_GlobalShaderVariablesUploader.BeginFill(); BuildGlobalShaderVariablesBase(cameraData, m_GlobalShaderVariablesUploader); @@ -707,8 +689,7 @@ internal void SetupRenderGraphDefaultCameraProperties(RenderGraph renderGraph, i SetupCameraProperties(context, data.cameraData, isTargetFlipped); - // Push the vars again, some were re-written by cmd.SetupCameraProperties() call above. - data.shaderData.Get().PushDefaultToGlobal(context.cmd); + data.shaderData.GetGlobal().PushAfterCameraSetup(context.cmd); }); } } @@ -1047,6 +1028,7 @@ internal void FinishRenderGraphRendering(CommandBuffer cmd) { UniversalCameraData cameraData = frameData.Get(); OnFinishRenderGraphRendering(cmd); + m_GlobalShaderVariablesUploader?.EndRenderGraph(cmd); InternalFinishRenderingCommon(cmd, cameraData.resolveFinalTarget); } @@ -1249,36 +1231,42 @@ void InternalFinishRenderingCommon(CommandBuffer cmd, bool resolveFinalTarget) } } - // Tells the pipeline this camera needs the real back buffer (the OS surface, not - // resourceData.backBuffer) multisampled. The pipeline keeps it single-sampled on frames where no - // camera needs MSAA, to save bandwidth. + // Tells the pipeline this camera needs its display target multisampled: the real back buffer (the OS + // surface, not resourceData.backBuffer), or the XR eye textures for XR cameras. The pipeline keeps it + // single-sampled on frames where no camera needs MSAA, to save bandwidth. // - // Contract: any renderer that renders multisampled content directly into the real back buffer must + // Contract: any renderer that renders multisampled content directly into the display target must // call this while rendering, or the pipeline may request a single-sampled surface and that content // is silently rendered without MSAA. - private protected void ReportRealBackbufferMSAA(UniversalCameraData cameraData, bool requiresIntermediateAttachments) + private protected void ReportDisplayTargetMSAA(UniversalCameraData cameraData, bool requiresIntermediateAttachments) { - if (NeedsRealBackbufferMSAA(cameraData, this, requiresIntermediateAttachments)) - (RenderPipelineManager.currentPipeline as UniversalRenderPipeline)?.RequireRealBackbufferMSAA(); + if (NeedsDisplayTargetMSAA(cameraData, this, requiresIntermediateAttachments)) + { + var pipeline = RenderPipelineManager.currentPipeline as UniversalRenderPipeline; +#if ENABLE_VR && ENABLE_XR_MODULE + if (cameraData.xr.enabled) + { + pipeline?.RequireXRDisplayMSAA(); + return; + } +#endif + pipeline?.RequireRealBackbufferMSAA(); + } } - // True when this camera renders multisampled content into the real back buffer, so the surface must - // be multisampled. The tile-only case is the subtle one: there the back buffer shares a native render - // pass with the MSAA intermediate attachments, so it must match their sample count even though it - // isn't rendered to directly. - static bool NeedsRealBackbufferMSAA(UniversalCameraData cameraData, ScriptableRenderer renderer, bool requiresIntermediateAttachments) + // True when this camera renders multisampled content into its display target, so the surface must + // be multisampled. The tile-only case is subtle: there the back buffer shares a native render pass with the + // MSAA intermediate attachments, so it must match their sample count even though it isn't rendered to directly. + // Tile-only can still request MSAA when Deferred doesn't support it so that the fallback to Forward triggers correctly. + static bool NeedsDisplayTargetMSAA(UniversalCameraData cameraData, ScriptableRenderer renderer, bool requiresIntermediateAttachments) { -#if ENABLE_VR && ENABLE_XR_MODULE - if (cameraData.xr.enabled) - return false; -#endif - if (cameraData.targetTexture != null) - return false; - if (!(renderer.supportedRenderingFeatures.msaa && cameraData.camera.allowMSAA)) + if (cameraData.targetTexture != null || !cameraData.camera.allowMSAA) return false; - bool tileOnlyMode = renderer is UniversalRenderer { useTileOnlyMode: true }; - return tileOnlyMode || !requiresIntermediateAttachments; + if (renderer is UniversalRenderer { useTileOnlyMode: true }) + return true; + + return renderer.supportedRenderingFeatures.msaa && !requiresIntermediateAttachments; } internal static void SortStable(List list) diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Settings/RenderingCapabilitiesSettings.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Settings/RenderingCapabilitiesSettings.cs index cc1cc4f4fa6..01f6508924a 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Settings/RenderingCapabilitiesSettings.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Settings/RenderingCapabilitiesSettings.cs @@ -7,12 +7,12 @@ namespace UnityEngine.Rendering.Universal /// /// /// To change those settings, go to Editor > Project Settings in the Graphics tab (URP). - /// Changing this through the API is only allowed in the Editor. In the Player, this raises an error. + /// URP reads them every frame, so they can also change at runtime, in the Editor and in the Player. /// /// [Serializable] [SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))] - [Categorization.CategoryInfo(Name = "Rendering Capabilities", Order = 30), HideInInspector] + [Categorization.CategoryInfo(Name = "Rendering Capabilities", Order = 30)] [Categorization.ElementInfo(Order = 0)] public class RenderingCapabilitiesSettings : IRenderPipelineGraphicsSettings { @@ -33,38 +33,36 @@ internal enum Version : int #region SerializeFields [SerializeField] - [Tooltip("Developer Mode only, work in progress. Declares URP's global shader variables as a constant buffer instead of loose uniforms, on all graphics APIs. Warning, this currently costs more memory and triggers a full shaders re-compilation.")] - bool m_UseGlobalConstantBuffer = false; + [Tooltip("When enabled, URP binds its global shader variables as a persistent constant buffer instead of letting the engine fill the buffer from loose uniforms. You can't change these variables with SetGlobal*, Material.Set*, a MaterialPropertyBlock, or ComputeShader.Set*. In render graph passes, use UniversalGlobalShaderData or Universal2DGlobalShaderData instead. OpenGL ES 3 (except on WebGL) and OpenGL Core always use loose uniforms.")] + bool m_UsePersistentGlobalConstantBuffer = false; #endregion #region Data Accessors /// - /// When enabled, URP declares its global shader variables as a constant buffer instead of loose uniforms, - /// by adding the URP_GLOBAL_CONSTANT_BUFFER shader define. The define is global and applies to every - /// graphics API. Work in progress. + /// Whether URP binds its global shader variables as a persistent constant buffer (the Use Persistent Global Constant + /// Buffer setting). /// - // KNOWN LIMITATION: the value is serialized in the project but read through a per-machine preference, so - // leaving Developer Mode strips a committed define and reimports every shader, and re-entering adds it back. - // Tolerable while nothing reads useGlobalConstantBuffer, but the gate has to go before the upload path lands: - // it is #if UNITY_EDITOR, so a player reads the field directly and a non-dev-mode build would ship - // loose-uniform shaders against a cbuffer-pushing runtime. + /// + /// When enabled (persistent mode), URP binds its global constant buffer itself, and scripts can't change its variables + /// with `SetGlobal*`, `Material.Set*`, a `MaterialPropertyBlock`, or `ComputeShader.Set*`. Render graph passes change + /// them through or + /// , which work in both modes. + /// When disabled (transient mode), the engine fills the buffer from URP loose uniforms. Both modes use the same + /// shaders, so changing this setting doesn't recompile shaders. OpenGL ES 3 (except on WebGL) and OpenGL Core always + /// use loose uniforms. + /// public bool useGlobalConstantBuffer { - get + get => m_UsePersistentGlobalConstantBuffer; + set { #if UNITY_EDITOR - // Outside of Developer Mode the feature is hidden and treated as off, - // so a value set in dev mode doesn't accidentally affect normal editor sessions. - // Must be Unsupported.IsDeveloperMode(), the same source the inspector uses to decide whether to - // ignore HideInInspector: EditorPrefs.GetBool("DeveloperMode") defaults to false, while the native - // side defaults it to "is this a source build", so on a source build the toggle would show but read off. - if (!UnityEditor.Unsupported.IsDeveloperMode()) - return false; + this.SetValueAndNotify(ref m_UsePersistentGlobalConstantBuffer, value); +#else + m_UsePersistentGlobalConstantBuffer = value; #endif - return m_UseGlobalConstantBuffer; } - set => this.SetValueAndNotify(ref m_UseGlobalConstantBuffer, value); } #endregion diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Settings/URPShadowBiasSettings.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Settings/URPShadowBiasSettings.cs index 2ed490c8127..4d5f43a7dda 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Settings/URPShadowBiasSettings.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Settings/URPShadowBiasSettings.cs @@ -79,14 +79,9 @@ public ShadowDepthBiasMode depthBiasMode public ShadowNormalBiasMode normalBiasMode { get => m_NormalBiasMode; - set - { #if UNITY_EDITOR - this.SetValueAndNotify(ref m_NormalBiasMode, value, nameof(m_NormalBiasMode)); -#else - m_NormalBiasMode = value; + set => this.SetValueAndNotify(ref m_NormalBiasMode, value, nameof(m_NormalBiasMode)); #endif - } } } } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/ShadowUtils.cs b/Packages/com.unity.render-pipelines.universal/Runtime/ShadowUtils.cs index 592c02bb598..69eaa948820 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/ShadowUtils.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/ShadowUtils.cs @@ -74,12 +74,24 @@ public void Clear() /// public static class ShadowUtils { + // Must match PCSS_DISK_SAMPLE_COUNT in com.unity.render-pipelines.core/ShaderLibrary/Shadow/PCSS.hlsl + internal const int k_PCSSMaxSampleCount = 64; + + // Must match SOFT_SHADOW_QUALITY_PCSS in Shadows.hlsl. The PCF filters read it as High. + internal const float k_SoftShadowQualityPCSS = (int)SoftShadowQuality.High + 1; + internal static readonly bool m_ForceShadowPointSampling; + static readonly bool s_PCSSSupported; + + // Whether the graphics device supports PCSS at all, whatever the asset settings + internal static bool isPCSSSupported => s_PCSSSupported; + static ShadowUtils() { m_ForceShadowPointSampling = SystemInfo.graphicsDeviceType == GraphicsDeviceType.Metal && - GraphicsSettings.HasShaderDefine(Graphics.activeTier, BuiltinShaderDefine.UNITY_METAL_SHADOWS_USE_POINT_FILTERING); + GraphicsSettings.HasShaderDefine(BuiltinShaderDefine.UNITY_METAL_SHADOWS_USE_POINT_FILTERING); + s_PCSSSupported = SupportsPCSS(SystemInfo.graphicsDeviceType); } /// @@ -265,6 +277,11 @@ public static bool ExtractPointLightMatrix(ref CullingResults cullResults, Unive // Covers receivers facing the light head-on (N.L near 1) in the slope-scale mode with caster normal bias, where both the slope term and the normal bias vanish. const float k_SlopeScaleCasterDepthBias = 0.05f; + // Shadow maps with more than 16 bit depth no longer round away the receiver's own depth error. 0.001 texels was the smallest caster offset + // or receiver normal bias that removed it in head-on measurements, so both values keep a 5x margin. + const float k_HighPrecisionMinCasterDepthBias = 0.005f; + const float k_HighPrecisionReceiverNormalBiasThreshold = 0.005f; + internal static ShadowDepthBiasMode GetConfiguredDepthBiasMode(URPShadowBiasSettings shadowBiasSettings) { return shadowBiasSettings != null ? shadowBiasSettings.depthBiasMode : ShadowDepthBiasMode.Legacy; @@ -275,6 +292,12 @@ internal static ShadowNormalBiasMode GetConfiguredNormalBiasMode(URPShadowBiasSe return shadowBiasSettings != null ? shadowBiasSettings.normalBiasMode : ShadowNormalBiasMode.Caster; } + internal static bool IsShadowReceiverNormalBiasEnabled() + { + GraphicsSettings.TryGetRenderPipelineSettings(out var shadowBiasSettings); + return GetConfiguredNormalBiasMode(shadowBiasSettings) == ShadowNormalBiasMode.Receiver; + } + /// /// Returns the slope-scale depth bias to set while rendering the shadow slices of a visible light, respecting the depth bias mode configured in the URP graphics settings. /// In the slope-scale depth bias mode the maximum slope is scaled by the light's soft shadow PCF kernel radius, since wider kernels sample farther from the receiver. @@ -286,10 +309,11 @@ internal static ShadowNormalBiasMode GetConfiguredNormalBiasMode(URPShadowBiasSe /// The slope-scale depth bias to apply while rendering the light's shadow slices. public static float GetSlopeScaleDepthBias(ref VisibleLight shadowLight, UniversalShadowData shadowData, int visibleLightIndex) { - return GetSlopeScaleDepthBias(ref shadowLight, shadowData.bias, shadowData.depthBiasMode, shadowData.supportsSoftShadows, visibleLightIndex, UniversalRenderPipeline.asset); + // Only the main light uses the kernel radius setting, so the main light's cascade resolution is the one that matters + return GetSlopeScaleDepthBias(ref shadowLight, shadowData.bias, shadowData.depthBiasMode, shadowData.supportsSoftShadows, visibleLightIndex, shadowData.softShadowKernelRadiusPercent, shadowData.mainLightShadowResolution, UniversalRenderPipeline.asset); } - static float GetSlopeScaleDepthBias(ref VisibleLight shadowLight, List bias, ShadowDepthBiasMode depthBiasMode, bool supportsSoftShadows, int visibleLightIndex, UniversalRenderPipelineAsset asset) + static float GetSlopeScaleDepthBias(ref VisibleLight shadowLight, List bias, ShadowDepthBiasMode depthBiasMode, bool supportsSoftShadows, int visibleLightIndex, float softShadowKernelRadiusPercent, float shadowResolution, UniversalRenderPipelineAsset asset) { float normalizedSlopeScale = 0.0f; float softShadowKernelRadius = 1.0f; @@ -297,7 +321,7 @@ static float GetSlopeScaleDepthBias(ref VisibleLight shadowLight, List { Debug.Assert(bias != null && visibleLightIndex >= 0 && visibleLightIndex < bias.Count, "GetSlopeScaleDepthBias expects a visible light index with an entry in the shadow bias data."); normalizedSlopeScale = bias[visibleLightIndex].x; - softShadowKernelRadius = GetSoftShadowKernelRadius(ref shadowLight, supportsSoftShadows, asset); + softShadowKernelRadius = GetSoftShadowBiasKernelRadius(ref shadowLight, supportsSoftShadows, softShadowKernelRadiusPercent, shadowResolution, asset); } return GetSlopeScaleDepthBias(normalizedSlopeScale, depthBiasMode, softShadowKernelRadius); @@ -326,12 +350,12 @@ internal static float GetSlopeScaleDepthBias(float normalizedSlopeScale, ShadowD /// /// /// - [Obsolete("Use the overload taking a slopeScaleDepthBias so the configured depth bias mode is respected; retrieve the value with ShadowUtils.GetSlopeScaleDepthBias. #from(6000.7)", false)] + [Obsolete("Use the overload taking slopeScaleDepthBias and useDepthClamp so the configured depth bias mode is respected; retrieve the slope with ShadowUtils.GetSlopeScaleDepthBias and pass false for useDepthClamp to keep the previous clipping. #from(6000.7)", false)] public static void RenderShadowSlice(CommandBuffer cmd, ref ScriptableRenderContext context, ref ShadowSliceData shadowSliceData, ref ShadowDrawingSettings settings, Matrix4x4 proj, Matrix4x4 view) { - RenderShadowSlice(cmd, ref context, ref shadowSliceData, ref settings, proj, view, k_LegacySlopeScaleDepthBias); + RenderShadowSlice(cmd, ref context, ref shadowSliceData, ref settings, proj, view, k_LegacySlopeScaleDepthBias, useDepthClamp: false); } /// @@ -344,11 +368,31 @@ public static void RenderShadowSlice(CommandBuffer cmd, ref ScriptableRenderCont /// The projection matrix used while rendering. /// The view matrix used while rendering. /// The slope-scale depth bias to apply while rendering, see . + [Obsolete("Use the overload taking useDepthClamp; pass false to keep the previous clipping. #from(7000.0)", false)] public static void RenderShadowSlice(CommandBuffer cmd, ref ScriptableRenderContext context, ref ShadowSliceData shadowSliceData, ref ShadowDrawingSettings settings, Matrix4x4 proj, Matrix4x4 view, float slopeScaleDepthBias) + { + RenderShadowSlice(cmd, ref context, ref shadowSliceData, ref settings, proj, view, slopeScaleDepthBias, useDepthClamp: false); + } + + /// + /// Renders shadows to a shadow slice. + /// + /// The command buffer to record rendering commands on. + /// The rendering context. + /// The shadow slice to render. + /// The shadow drawing settings. + /// The projection matrix used while rendering. + /// The view matrix used while rendering. + /// The slope-scale depth bias to apply while rendering, see . + /// When true, casters render with depth clipping disabled (ZClip Off) so depth is clamped at the near plane instead of clipped. Pass true only for directional lights when is true. + public static void RenderShadowSlice(CommandBuffer cmd, ref ScriptableRenderContext context, + ref ShadowSliceData shadowSliceData, ref ShadowDrawingSettings settings, + Matrix4x4 proj, Matrix4x4 view, float slopeScaleDepthBias, bool useDepthClamp) { cmd.SetGlobalDepthBias(1.0f, slopeScaleDepthBias); + cmd.SetGlobalFloat(ShaderPropertyId.zClip, useDepthClamp ? 0.0f : 1.0f); cmd.SetViewport(new Rect(shadowSliceData.offsetX, shadowSliceData.offsetY, shadowSliceData.resolution, shadowSliceData.resolution)); cmd.SetViewProjectionMatrices(view, proj); @@ -358,14 +402,17 @@ public static void RenderShadowSlice(CommandBuffer cmd, ref ScriptableRenderCont context.ExecuteCommandBuffer(cmd); cmd.Clear(); - cmd.SetGlobalDepthBias(0.0f, 0.0f); // Restore previous depth bias values + // Restore previous depth bias and ZClip values + cmd.SetGlobalFloat(ShaderPropertyId.zClip, 1.0f); + cmd.SetGlobalDepthBias(0.0f, 0.0f); } internal static void RenderShadowSlice(RasterCommandBuffer cmd, ref ShadowSliceData shadowSliceData, ref RendererList shadowRendererList, - Matrix4x4 proj, Matrix4x4 view, float slopeScaleDepthBias) + Matrix4x4 proj, Matrix4x4 view, float slopeScaleDepthBias, bool useDepthClamp) { cmd.SetGlobalDepthBias(1.0f, slopeScaleDepthBias); + cmd.SetGlobalFloat(ShaderPropertyId.zClip, useDepthClamp ? 0.0f : 1.0f); cmd.SetViewport(new Rect(shadowSliceData.offsetX, shadowSliceData.offsetY, shadowSliceData.resolution, shadowSliceData.resolution)); cmd.SetViewProjectionMatrices(view, proj); @@ -373,7 +420,9 @@ internal static void RenderShadowSlice(RasterCommandBuffer cmd, cmd.DrawRendererList(shadowRendererList); cmd.DisableScissorRect(); - cmd.SetGlobalDepthBias(0.0f, 0.0f); // Restore previous depth bias values + // Restore previous depth bias and ZClip values + cmd.SetGlobalFloat(ShaderPropertyId.zClip, 1.0f); + cmd.SetGlobalDepthBias(0.0f, 0.0f); } /// @@ -383,12 +432,12 @@ internal static void RenderShadowSlice(RasterCommandBuffer cmd, /// /// /// - [Obsolete("Use the overload taking a slopeScaleDepthBias so the configured depth bias mode is respected; retrieve the value with ShadowUtils.GetSlopeScaleDepthBias. #from(6000.7)", false)] + [Obsolete("Use the overload taking slopeScaleDepthBias and useDepthClamp so the configured depth bias mode is respected; retrieve the slope with ShadowUtils.GetSlopeScaleDepthBias and pass false for useDepthClamp to keep the previous clipping. #from(6000.7)", false)] public static void RenderShadowSlice(CommandBuffer cmd, ref ScriptableRenderContext context, ref ShadowSliceData shadowSliceData, ref ShadowDrawingSettings settings) { RenderShadowSlice(cmd, ref context, ref shadowSliceData, ref settings, - shadowSliceData.projectionMatrix, shadowSliceData.viewMatrix, k_LegacySlopeScaleDepthBias); + shadowSliceData.projectionMatrix, shadowSliceData.viewMatrix, k_LegacySlopeScaleDepthBias, useDepthClamp: false); } /// @@ -399,11 +448,12 @@ public static void RenderShadowSlice(CommandBuffer cmd, ref ScriptableRenderCont /// The shadow slice to render. /// The shadow drawing settings. /// The slope-scale depth bias to apply while rendering, see . + [Obsolete("Use the overload taking proj, view and useDepthClamp; pass shadowSliceData.projectionMatrix, shadowSliceData.viewMatrix and false to keep the previous clipping. #from(7000.0)", false)] public static void RenderShadowSlice(CommandBuffer cmd, ref ScriptableRenderContext context, ref ShadowSliceData shadowSliceData, ref ShadowDrawingSettings settings, float slopeScaleDepthBias) { RenderShadowSlice(cmd, ref context, ref shadowSliceData, ref settings, - shadowSliceData.projectionMatrix, shadowSliceData.viewMatrix, slopeScaleDepthBias); + shadowSliceData.projectionMatrix, shadowSliceData.viewMatrix, slopeScaleDepthBias, useDepthClamp: false); } /// @@ -416,11 +466,11 @@ public static void RenderShadowSlice(CommandBuffer cmd, ref ScriptableRenderCont public static int GetMaxTileResolutionInAtlas(int atlasWidth, int atlasHeight, int tileCount) { int resolution = Mathf.Min(atlasWidth, atlasHeight); - int currentTileCount = atlasWidth / resolution * atlasHeight / resolution; + int currentTileCount = (atlasWidth / resolution) * (atlasHeight / resolution); while (currentTileCount < tileCount) { resolution = resolution >> 1; - currentTileCount = atlasWidth / resolution * atlasHeight / resolution; + currentTileCount = (atlasWidth / resolution) * (atlasHeight / resolution); } return resolution; } @@ -453,10 +503,13 @@ public static void ApplySliceTransform(ref ShadowSliceData shadowSliceData, int /// /// /// - /// The depth and normal bias from a visible light. In the slope-scale depth bias mode the x component (depth bias) is a small fixed texel-scaled caster offset, or 0 in the shadow-receiver normal bias mode; retrieve the rasterizer bias with GetSlopeScaleDepthBias instead. In the shadow-receiver normal bias mode the y component (normal bias) is 0; retrieve the world-space sampling offset with GetReceiverNormalBias instead. + /// The depth and normal bias from a visible light. In the slope-scale depth bias mode the x component (depth bias) is a small fixed texel-scaled caster offset, or 0 in the shadow-receiver normal bias mode unless the shadow map has more than 16 bit depth and the receiver normal bias is close to 0 or, for a main light that uses Screen Space Shadows, not applied; retrieve the rasterizer bias with GetSlopeScaleDepthBias instead. In the shadow-receiver normal bias mode the y component (normal bias) is 0; retrieve the world-space sampling offset with GetReceiverNormalBias instead. public static Vector4 GetShadowBias(ref VisibleLight shadowLight, int shadowLightIndex, ref ShadowData shadowData, Matrix4x4 lightProjectionMatrix, float shadowResolution) { - return GetShadowBias(ref shadowLight, shadowLightIndex, shadowData.bias, shadowData.supportsSoftShadows, shadowData.depthBiasMode, shadowData.normalBiasMode, lightProjectionMatrix, shadowResolution, UniversalRenderPipeline.asset); + bool highPrecisionShadowmap = shadowLight.lightType == LightType.Directional + ? IsHighPrecisionShadowmap(shadowData.mainLightShadowmapFormat, shadowData.mainLightShadowmapDepthBits) + : IsHighPrecisionShadowmap(shadowData.additionalLightsShadowmapFormat, shadowData.additionalLightsShadowmapDepthBits); + return GetShadowBias(ref shadowLight, shadowLightIndex, shadowData.bias, shadowData.supportsSoftShadows, shadowData.depthBiasMode, shadowData.normalBiasMode, shadowData.softShadowKernelRadiusPercent, lightProjectionMatrix, shadowResolution, highPrecisionShadowmap, shadowData.mainLightReceiverNormalBiasSkipped, UniversalRenderPipeline.asset); } /// @@ -467,10 +520,28 @@ public static Vector4 GetShadowBias(ref VisibleLight shadowLight, int shadowLigh /// /// /// - /// The depth and normal bias from a visible light. In the slope-scale depth bias mode the x component (depth bias) is a small fixed texel-scaled caster offset, or 0 in the shadow-receiver normal bias mode; retrieve the rasterizer bias with GetSlopeScaleDepthBias instead. In the shadow-receiver normal bias mode the y component (normal bias) is 0; retrieve the world-space sampling offset with GetReceiverNormalBias instead. + /// The depth and normal bias from a visible light. In the slope-scale depth bias mode the x component (depth bias) is a small fixed texel-scaled caster offset, or 0 in the shadow-receiver normal bias mode unless the shadow map has more than 16 bit depth and the receiver normal bias is close to 0 or, for a main light that uses Screen Space Shadows, not applied; retrieve the rasterizer bias with GetSlopeScaleDepthBias instead. In the shadow-receiver normal bias mode the y component (normal bias) is 0; retrieve the world-space sampling offset with GetReceiverNormalBias instead. public static Vector4 GetShadowBias(ref VisibleLight shadowLight, int shadowLightIndex, UniversalShadowData shadowData, Matrix4x4 lightProjectionMatrix, float shadowResolution) { - return GetShadowBias(ref shadowLight, shadowLightIndex, shadowData.bias, shadowData.supportsSoftShadows, shadowData.depthBiasMode, shadowData.normalBiasMode, lightProjectionMatrix, shadowResolution, UniversalRenderPipeline.asset); + bool highPrecisionShadowmap = shadowLight.lightType == LightType.Directional + ? IsHighPrecisionShadowmap(shadowData.mainLightShadowmapFormat, shadowData.mainLightShadowmapDepthBits) + : IsHighPrecisionShadowmap(shadowData.additionalLightsShadowmapFormat, shadowData.additionalLightsShadowmapDepthBits); + return GetShadowBias(ref shadowLight, shadowLightIndex, shadowData.bias, shadowData.supportsSoftShadows, shadowData.depthBiasMode, shadowData.normalBiasMode, shadowData.softShadowKernelRadiusPercent, lightProjectionMatrix, shadowResolution, highPrecisionShadowmap, shadowData.mainLightReceiverNormalBiasSkipped, UniversalRenderPipeline.asset); + } + + internal static bool IsHighPrecisionShadowmap(DepthBits depthBits) + { + return (int)depthBits > 16; + } + + internal static bool IsHighPrecisionShadowmap(GraphicsFormat shadowmapFormat) + { + return GraphicsFormatUtility.GetDepthBits(shadowmapFormat) > 16; + } + + internal static bool IsHighPrecisionShadowmap(GraphicsFormat shadowmapFormat, DepthBits requestedDepthBits) + { + return shadowmapFormat != GraphicsFormat.None ? IsHighPrecisionShadowmap(shadowmapFormat) : IsHighPrecisionShadowmap(requestedDepthBits); } static float GetShadowTexelSizeInWorldSpace(ref VisibleLight shadowLight, Matrix4x4 lightProjectionMatrix, float shadowResolution, float receiverBiasTexels = 0.0f) @@ -528,10 +599,10 @@ static float GetShadowTexelSizeInWorldSpace(ref VisibleLight shadowLight, Matrix /// The world-space receiver normal bias of the light's shadow slice. In the shadow-caster normal bias mode the value is 0. public static float GetReceiverNormalBias(ref VisibleLight shadowLight, int visibleLightIndex, UniversalShadowData shadowData, Matrix4x4 lightProjectionMatrix, float shadowResolution) { - return GetReceiverNormalBias(ref shadowLight, shadowData.bias, shadowData.normalBiasMode, shadowData.supportsSoftShadows, visibleLightIndex, lightProjectionMatrix, shadowResolution, UniversalRenderPipeline.asset); + return GetReceiverNormalBias(ref shadowLight, shadowData.bias, shadowData.normalBiasMode, shadowData.supportsSoftShadows, shadowData.softShadowKernelRadiusPercent, visibleLightIndex, lightProjectionMatrix, shadowResolution, UniversalRenderPipeline.asset); } - static float GetReceiverNormalBias(ref VisibleLight shadowLight, List bias, ShadowNormalBiasMode normalBiasMode, bool supportsSoftShadows, int visibleLightIndex, Matrix4x4 lightProjectionMatrix, float shadowResolution, UniversalRenderPipelineAsset asset) + static float GetReceiverNormalBias(ref VisibleLight shadowLight, List bias, ShadowNormalBiasMode normalBiasMode, bool supportsSoftShadows, float softShadowKernelRadiusPercent, int visibleLightIndex, Matrix4x4 lightProjectionMatrix, float shadowResolution, UniversalRenderPipelineAsset asset) { float normalBias = 0.0f; float texelSize = 0.0f; @@ -540,7 +611,7 @@ static float GetReceiverNormalBias(ref VisibleLight shadowLight, List b { Debug.Assert(bias != null && visibleLightIndex >= 0 && visibleLightIndex < bias.Count, "GetReceiverNormalBias expects a visible light index with an entry in the shadow bias data."); normalBias = bias[visibleLightIndex].y; - softShadowKernelRadius = GetSoftShadowKernelRadius(ref shadowLight, supportsSoftShadows, asset); + softShadowKernelRadius = GetSoftShadowBiasKernelRadius(ref shadowLight, supportsSoftShadows, softShadowKernelRadiusPercent, shadowResolution, asset); texelSize = GetShadowTexelSizeInWorldSpace(ref shadowLight, lightProjectionMatrix, shadowResolution, normalBias * softShadowKernelRadius); } @@ -561,7 +632,7 @@ internal static float GetReceiverNormalBias(float normalBias, ShadowNormalBiasMo } } - static Vector4 GetShadowBias(ref VisibleLight shadowLight, int shadowLightIndex, List bias, bool supportsSoftShadows, ShadowDepthBiasMode depthBiasMode, ShadowNormalBiasMode normalBiasMode, Matrix4x4 lightProjectionMatrix, float shadowResolution, UniversalRenderPipelineAsset asset) + static Vector4 GetShadowBias(ref VisibleLight shadowLight, int shadowLightIndex, List bias, bool supportsSoftShadows, ShadowDepthBiasMode depthBiasMode, ShadowNormalBiasMode normalBiasMode, float softShadowKernelRadiusPercent, Matrix4x4 lightProjectionMatrix, float shadowResolution, bool highPrecisionShadowmap, bool mainLightReceiverNormalBiasSkipped, UniversalRenderPipelineAsset asset) { if (bias == null || shadowLightIndex < 0 || shadowLightIndex >= bias.Count) { @@ -570,13 +641,14 @@ static Vector4 GetShadowBias(ref VisibleLight shadowLight, int shadowLightIndex, } // depth and normal bias scale is in shadowmap texel size in world space - float softShadowKernelRadius = GetSoftShadowKernelRadius(ref shadowLight, supportsSoftShadows, asset); + float softShadowKernelRadius = GetSoftShadowBiasKernelRadius(ref shadowLight, supportsSoftShadows, softShadowKernelRadiusPercent, shadowResolution, asset); // The point light guard angle grows with the receiver normal bias, so the texel size must account for it too float receiverBiasTexels = normalBiasMode == ShadowNormalBiasMode.Receiver ? bias[shadowLightIndex].y * softShadowKernelRadius : 0.0f; float texelSize = GetShadowTexelSizeInWorldSpace(ref shadowLight, lightProjectionMatrix, shadowResolution, receiverBiasTexels); - float depthBias = GetCasterDepthBias(bias[shadowLightIndex].x, depthBiasMode, normalBiasMode, texelSize); + float appliedReceiverNormalBias = shadowLight.lightType == LightType.Directional && mainLightReceiverNormalBiasSkipped ? 0.0f : bias[shadowLightIndex].y; + float depthBias = GetCasterDepthBias(bias[shadowLightIndex].x, appliedReceiverNormalBias, depthBiasMode, normalBiasMode, texelSize, highPrecisionShadowmap); float normalBias = GetCasterNormalBias(bias[shadowLightIndex].y, normalBiasMode, texelSize, shadowLight.lightType); depthBias *= softShadowKernelRadius; @@ -585,17 +657,22 @@ static Vector4 GetShadowBias(ref VisibleLight shadowLight, int shadowLightIndex, return new Vector4(depthBias, normalBias, (float)shadowLight.lightType, 0.0f); } - internal static float GetCasterDepthBias(float depthBias, ShadowDepthBiasMode depthBiasMode, ShadowNormalBiasMode normalBiasMode, float texelSize) + internal static float GetCasterDepthBias(float depthBias, float normalBias, ShadowDepthBiasMode depthBiasMode, ShadowNormalBiasMode normalBiasMode, float texelSize, bool highPrecisionShadowmap) { + bool receiverCoversHeadOn = normalBiasMode == ShadowNormalBiasMode.Receiver && normalBias >= k_HighPrecisionReceiverNormalBiasThreshold; + float minDepthBias = highPrecisionShadowmap && !receiverCoversHeadOn ? k_HighPrecisionMinCasterDepthBias : 0.0f; switch (depthBiasMode) { case ShadowDepthBiasMode.SlopeScale: - return normalBiasMode == ShadowNormalBiasMode.Caster ? -k_SlopeScaleCasterDepthBias * texelSize : 0.0f; + { + float casterDepthBias = normalBiasMode == ShadowNormalBiasMode.Caster ? k_SlopeScaleCasterDepthBias : 0.0f; + return -Mathf.Max(casterDepthBias, minDepthBias) * texelSize; + } case ShadowDepthBiasMode.Legacy: - return -depthBias * texelSize; + return -Mathf.Max(depthBias, minDepthBias) * texelSize; default: Debug.Assert(false, "Unexpected depth bias mode."); - return -depthBias * texelSize; + return -Mathf.Max(depthBias, minDepthBias) * texelSize; } } @@ -622,11 +699,13 @@ internal static float GetSoftShadowKernelRadius(ref VisibleLight shadowLight, bo if (!supportsSoftShadows || shadowLight.light.shadows != LightShadows.Soft) return 1.0f; - SoftShadowQuality softShadowQuality = SoftShadowQuality.UsePipelineSettings; - if (SupportsPerLightSoftShadowQuality() && shadowLight.light.TryGetComponent(out UniversalAdditionalLightData additionalLightData)) - softShadowQuality = additionalLightData.softShadowQuality; + SoftShadowQuality softShadowQuality = GetPerLightSoftShadowQuality(shadowLight.light, asset); + + // PCSS sizes its own filter, and widening the kernel would collapse its penumbra + if (IsPCSSEnabled(shadowLight.lightType, softShadowQuality, asset, s_PCSSSupported)) + return 1.0f; - return GetSoftShadowKernelRadius(ResolveSoftShadowQuality(softShadowQuality, asset)); + return GetSoftShadowKernelRadius(softShadowQuality); } internal static SoftShadowQuality ResolveSoftShadowQuality(SoftShadowQuality softShadowQuality, UniversalRenderPipelineAsset asset) @@ -658,6 +737,250 @@ internal static float GetSoftShadowKernelRadius(SoftShadowQuality softShadowQual return kernelRadius; } + static SoftShadowQuality GetPerLightSoftShadowQuality(Light light, UniversalRenderPipelineAsset asset) + { + SoftShadowQuality softShadowQuality = SoftShadowQuality.UsePipelineSettings; + if (SupportsPerLightSoftShadowQuality() && light != null && light.TryGetComponent(out UniversalAdditionalLightData additionalLightData)) + softShadowQuality = additionalLightData.softShadowQuality; + + return ResolveSoftShadowQuality(softShadowQuality, asset); + } + + internal static bool SupportsPCSS(GraphicsDeviceType type) + { + return type != GraphicsDeviceType.OpenGLES3 && type != GraphicsDeviceType.OpenGLCore; + } + + static bool IsPCSSEnabled(LightType lightType, SoftShadowQuality resolvedSoftShadowQuality, UniversalRenderPipelineAsset asset, bool pcssSupported) + { + if (asset == null || !SupportsPerLightSoftShadowQuality() || !pcssSupported || resolvedSoftShadowQuality < SoftShadowQuality.High) + return false; + + switch (lightType) + { + case LightType.Directional: + return asset.mainLightShadowsPCSS; + case LightType.Spot: + case LightType.Point: + return asset.additionalLightShadowsPCSS; + default: + return false; + } + } + + internal static bool IsPCSSEnabled(ref VisibleLight shadowLight, UniversalAdditionalLightData additionalLightData, bool supportsSoftShadows, UniversalRenderPipelineAsset asset) + { + Light light = shadowLight.light; + if (light == null || !supportsSoftShadows || light.shadows != LightShadows.Soft) + return false; + + SoftShadowQuality softShadowQuality = additionalLightData != null ? additionalLightData.softShadowQuality : SoftShadowQuality.UsePipelineSettings; + return IsPCSSEnabled(shadowLight.lightType, ResolveSoftShadowQuality(softShadowQuality, asset), asset, s_PCSSSupported); + } + + // Takes the resolved quality packed into the y channel of the shadow params. Spot and point lights share the toggle. + internal static bool IsAdditionalLightPCSSEnabled(float packedSoftShadowQuality, UniversalRenderPipelineAsset asset) + { + return IsAdditionalLightPCSSEnabled(packedSoftShadowQuality, asset, s_PCSSSupported); + } + + internal static bool IsAdditionalLightPCSSEnabled(float packedSoftShadowQuality, UniversalRenderPipelineAsset asset, bool pcssSupported) + { + return IsPCSSEnabled(LightType.Spot, (SoftShadowQuality)(int)packedSoftShadowQuality, asset, pcssSupported); + } + + // Ignores the asset toggle so the inspector can explain that it is off + internal static bool IsPCSSAvailableForLight(Light light, UniversalRenderPipelineAsset asset) + { + if (asset == null || light == null || !asset.supportsSoftShadows || light.shadows != LightShadows.Soft) + return false; + + if (!SupportsPerLightSoftShadowQuality()) + return false; + + return GetPerLightSoftShadowQuality(light, asset) >= SoftShadowQuality.High; + } + + internal static int GetPCSSTemporalFrameIndex(UniversalCameraData cameraData) + { + // The rotation only resolves under a temporal filter, and the wrap keeps InterleavedGradientNoise precise + return cameraData.IsTemporalAAEnabled() ? TemporalAA.CalculateTaaFrameIndex(ref cameraData.taaSettings) & 1023 : 0; + } + + internal static void GetPCSSPresetSampleCounts(PCSSSampleQuality quality, out int blockerSampleCount, out int filterSampleCount) + { + switch (quality) + { + case PCSSSampleQuality.Low: + blockerSampleCount = UniversalAdditionalLightData.k_LowSoftShadowBlockerSampleCount; + filterSampleCount = UniversalAdditionalLightData.k_LowSoftShadowFilterSampleCount; + break; + + case PCSSSampleQuality.High: + blockerSampleCount = UniversalAdditionalLightData.k_HighSoftShadowBlockerSampleCount; + filterSampleCount = UniversalAdditionalLightData.k_HighSoftShadowFilterSampleCount; + break; + + case PCSSSampleQuality.Medium: + default: + Debug.Assert(quality == PCSSSampleQuality.Medium, "Only the Low, Medium and High PCSS presets have sample counts."); + blockerSampleCount = UniversalAdditionalLightData.k_DefaultSoftShadowBlockerSampleCount; + filterSampleCount = UniversalAdditionalLightData.k_DefaultSoftShadowFilterSampleCount; + break; + } + } + + static bool UsesCustomPCSSSettings(UniversalAdditionalLightData additionalLightData) + { + return additionalLightData != null && additionalLightData.softShadowPCSSSampleQuality == PCSSSampleQuality.Custom; + } + + internal static void GetPCSSSampleCounts(UniversalAdditionalLightData additionalLightData, out int blockerSampleCount, out int filterSampleCount) + { + if (UsesCustomPCSSSettings(additionalLightData)) + { + blockerSampleCount = additionalLightData.softShadowBlockerSampleCount; + filterSampleCount = additionalLightData.softShadowFilterSampleCount; + } + else + { + PCSSSampleQuality quality = additionalLightData != null ? additionalLightData.softShadowPCSSSampleQuality : PCSSSampleQuality.Medium; + GetPCSSPresetSampleCounts(quality, out blockerSampleCount, out filterSampleCount); + } + } + + internal static void ComputeAdditionalLightPCSSParams(float shapeRadius, UniversalAdditionalLightData additionalLightData, int sliceResolution, Matrix4x4 sliceProjectionMatrix, out Vector4 pcssParams, out Vector4 zBufferParams) + { + float softnessScale = additionalLightData != null ? additionalLightData.softShadowScale : UniversalAdditionalLightData.k_DefaultSoftShadowScale; + float minFilterSize = additionalLightData != null ? additionalLightData.softShadowMinFilterSize : UniversalAdditionalLightData.k_DefaultSoftShadowMinFilterSize; + GetPCSSSampleCounts(additionalLightData, out int blockerSampleCount, out int filterSampleCount); + + // Same fit as HDGpuLightsBuilder.GetNonDirectionalSoftness in HDRP, keep the two in sync + float x = shapeRadius * softnessScale; + float x2 = x * x; + float softness = 0.02403461f + 3.452916f * x - 1.362672f * x2 + 0.6700115f * x2 * x + 0.2159474f * x2 * x2; + softness /= 100.0f; + softness *= sliceResolution / 512.0f; // Make it resolution independent whereas the baseline is 512 + + // Divided by 1000 so the user range is [0, 1], as in HDRP + float minFilterRadius = minFilterSize * 0.001f; + + pcssParams = new Vector4(softness, minFilterRadius, Mathf.Clamp(blockerSampleCount, 1, k_PCSSMaxSampleCount), Mathf.Clamp(filterSampleCount, 1, k_PCSSMaxSampleCount)); + + // From the projection, so the point light near plane clamp and guard angle are included + float m22 = sliceProjectionMatrix.m22; + float m23 = sliceProjectionMatrix.m23; + float near = m23 / (m22 - 1.0f); + float far = m23 / (m22 + 1.0f); + zBufferParams = SystemInfo.usesReversedZBuffer + ? new Vector4((far - near) / near, 1.0f, (far - near) / (near * far), 1.0f / far) + : new Vector4((near - far) / near, far / near, (near - far) / (near * far), 1.0f / near); + } + + internal static void ComputeMainLightPCSSParams(UniversalAdditionalLightData additionalLightData, ShadowSliceData[] cascadeSlices, int cascadeCount, int atlasWidth, int atlasHeight, ref MainLightShadowCascadeVectors params0, ref MainLightShadowCascadeVectors params1, ref MainLightShadowCascadeVectors atlas) + { + float angularDiameter = UniversalAdditionalLightData.k_DefaultSoftShadowAngularDiameter; + float softnessScale = UniversalAdditionalLightData.k_DefaultSoftShadowScale; + float maxPenumbraSize = UniversalAdditionalLightData.k_DefaultSoftShadowMaxPenumbraSize; + float maxSamplingDistance = UniversalAdditionalLightData.k_DefaultSoftShadowMaxSamplingDistance; + float minFilterSizeTexels = UniversalAdditionalLightData.k_DefaultSoftShadowMinFilterSizeTexels; + float minFilterMaxAngularDiameter = UniversalAdditionalLightData.k_DefaultSoftShadowMinFilterMaxAngularDiameter; + float blockerSearchAngularDiameter = UniversalAdditionalLightData.k_DefaultSoftShadowBlockerSearchAngularDiameter; + float blockerSamplingClumpExponent = UniversalAdditionalLightData.k_DefaultSoftShadowBlockerSamplingClumpExponent; + if (additionalLightData != null) + { + angularDiameter = additionalLightData.softShadowAngularDiameter; + softnessScale = additionalLightData.softShadowScale; + minFilterSizeTexels = additionalLightData.softShadowMinFilterSizeTexels; + } + + if (UsesCustomPCSSSettings(additionalLightData)) + { + maxPenumbraSize = additionalLightData.softShadowMaxPenumbraSize; + maxSamplingDistance = additionalLightData.softShadowMaxSamplingDistance; + minFilterMaxAngularDiameter = additionalLightData.softShadowMinFilterMaxAngularDiameter; + blockerSearchAngularDiameter = additionalLightData.softShadowBlockerSearchAngularDiameter; + blockerSamplingClumpExponent = additionalLightData.softShadowBlockerSamplingClumpExponent; + } + + float lightAngularDiameter = softnessScale * angularDiameter; + float halfTan = HalfAngularDiameterTangent(lightAngularDiameter); + + // The blocker search cone can only be widened, never narrowed below the cone of the light itself + float blockerSearchTan = HalfAngularDiameterTangent(Mathf.Max(blockerSearchAngularDiameter, lightAngularDiameter)); + float minFilterTan = HalfAngularDiameterTangent(Mathf.Max(Mathf.Max(minFilterMaxAngularDiameter, blockerSearchAngularDiameter), lightAngularDiameter)); + + // The shader takes the square root of the normalized range, so the authored exponent is halved + float clumpExponent = 0.5f * blockerSamplingClumpExponent; + float maxBlockerDistance = maxPenumbraSize / (2.0f * halfTan); + + float oneOverAtlasWidth = 1.0f / atlasWidth; + float oneOverAtlasHeight = 1.0f / atlasHeight; + + for (int i = 0; i < cascadeCount; ++i) + { + // The culling matrices are OpenGL style while the shader uses [0, 1] depth + Matrix4x4 projectionMatrix = cascadeSlices[i].projectionMatrix; + float projectionDepthToRadialScale = 2.0f * Mathf.Abs(projectionMatrix.m00 / projectionMatrix.m22); + float worldToDepthScale = 0.5f * Mathf.Abs(projectionMatrix.m22); + + float depth2RadialScale = halfTan * projectionDepthToRadialScale; + + params0[i] = new Vector4(depth2RadialScale, 1.0f / depth2RadialScale, maxBlockerDistance * worldToDepthScale, maxSamplingDistance * worldToDepthScale); + params1[i] = new Vector4(minFilterSizeTexels, 1.0f / (minFilterTan * projectionDepthToRadialScale), 1.0f / (blockerSearchTan * projectionDepthToRadialScale), clumpExponent); + atlas[i] = new Vector4(cascadeSlices[i].offsetX * oneOverAtlasWidth, cascadeSlices[i].offsetY * oneOverAtlasHeight, cascadeSlices[i].resolution * oneOverAtlasWidth, cascadeSlices[i].resolution * oneOverAtlasHeight); + } + + // See _MainLightPCSSAtlas in GlobalShaderVariables.hlsl + for (int i = cascadeCount; i < MainLightShadowCascadeVectors.count; ++i) + { + params0[i] = Vector4.zero; + params1[i] = Vector4.zero; + atlas[i] = Vector4.zero; + } + } + + internal static Vector4 GetMainLightPCSSScalars(UniversalAdditionalLightData additionalLightData, int tileResolution) + { + GetPCSSSampleCounts(additionalLightData, out int blockerSampleCount, out int filterSampleCount); + + // Tile texel size, since the shader compares the minimum filter radius in tile space + return new Vector4(1.0f / tileResolution, Mathf.Clamp(blockerSampleCount, 1, k_PCSSMaxSampleCount), Mathf.Clamp(filterSampleCount, 1, k_PCSSMaxSampleCount), 0.0f); + } + + static float HalfAngularDiameterTangent(float angularDiameterInDegrees) + { + // The shader divides by the radial scales this feeds + return Mathf.Max(Mathf.Tan(0.5f * Mathf.Deg2Rad * angularDiameterInDegrees), 1e-6f); + } + + internal static float GetSoftShadowKernelRadius(float softShadowKernelRadiusPercent, float shadowResolution) + { + // Narrower than half a texel, some receivers have no texel edge within reach and the penumbra turns into blocky steps + const float minSoftShadowKernelRadius = 0.5f; + + return Mathf.Max(softShadowKernelRadiusPercent * 0.01f * shadowResolution, minSoftShadowKernelRadius); + } + + static float GetSoftShadowBiasKernelRadius(ref VisibleLight shadowLight, bool supportsSoftShadows, float softShadowKernelRadiusPercent, float shadowResolution, UniversalRenderPipelineAsset asset) + { + if (!supportsSoftShadows || shadowLight.light.shadows != LightShadows.Soft) + return 1.0f; + + SoftShadowQuality softShadowQuality = GetPerLightSoftShadowQuality(shadowLight.light, asset); + + // PCSS sizes its own filter, so neither the quality's kernel nor the kernel radius applies to it + if (IsPCSSEnabled(shadowLight.lightType, softShadowQuality, asset, s_PCSSSupported)) + return 1.0f; + + float qualityKernelRadius = GetSoftShadowKernelRadius(softShadowQuality); + if (softShadowKernelRadiusPercent <= 0.0f || shadowLight.lightType != LightType.Directional) + return qualityKernelRadius; + + // It never drops below the quality's kernel, which keeps the biases of the fixed kernels, + // and follows a wider filter kernel since that samples farther from the receiver. + return Mathf.Max(qualityKernelRadius, GetSoftShadowKernelRadius(softShadowKernelRadiusPercent, shadowResolution)); + } /// /// Extract scale and bias from a fade distance to achieve a linear fading of the fade distance. @@ -731,6 +1054,11 @@ internal static void SetCameraPosition(RasterCommandBuffer cmd, Vector3 worldSpa cmd.SetGlobalVector(ShaderPropertyId.worldSpaceCameraPos, worldSpaceCameraPos); } + internal static bool ShouldUseShadowDepthClamp(bool isDirectional) + { + return isDirectional && SystemInfo.supportsDepthClamp; + } + private static RenderTextureDescriptor GetTemporaryShadowTextureDescriptor(int width, int height, int bits) { var format = GraphicsFormatUtility.GetDepthStencilFormat(bits, 0); @@ -922,12 +1250,19 @@ internal static bool SupportsPerLightSoftShadowQuality() internal static void SetPerLightSoftShadowKeyword(RasterCommandBuffer cmd, UniversalShadowData shadowData, bool hasSoftShadows) { if (SupportsPerLightSoftShadowQuality()) - cmd.SetKeyword(ShaderGlobalKeywords.SoftShadows, hasSoftShadows); + SetPerLightQualitySoftShadowKeywords(cmd, shadowData, hasSoftShadows); else // keep static quality keywords in lockstep with the per-light shadow keywords (UUM-147509) SetSoftShadowQualityShaderKeywords(cmd, shadowData, hasSoftShadows); } + // PCSS is layered on the per-light soft shadow keyword, so shaders without it keep the PCF filters + static void SetPerLightQualitySoftShadowKeywords(RasterCommandBuffer cmd, UniversalShadowData shadowData, bool enabled) + { + cmd.SetKeyword(ShaderGlobalKeywords.SoftShadows, enabled); + cmd.SetKeyword(ShaderGlobalKeywords.ShadowsPCSS, enabled && (shadowData.isMainLightPCSSEnabled || shadowData.isAdditionalLightsPCSSEnabled)); + } + internal static void SetSoftShadowQualityShaderKeywords(RasterCommandBuffer cmd, UniversalShadowData shadowData) { SetSoftShadowQualityShaderKeywords(cmd, shadowData, shadowData.isKeywordSoftShadowsEnabled); @@ -935,15 +1270,18 @@ internal static void SetSoftShadowQualityShaderKeywords(RasterCommandBuffer cmd, internal static void SetSoftShadowQualityShaderKeywords(RasterCommandBuffer cmd, UniversalShadowData shadowData, bool enabled) { - cmd.SetKeyword(ShaderGlobalKeywords.SoftShadows, enabled); if (SupportsPerLightSoftShadowQuality()) { + SetPerLightQualitySoftShadowKeywords(cmd, shadowData, enabled); cmd.SetKeyword(ShaderGlobalKeywords.SoftShadowsLow, false); cmd.SetKeyword(ShaderGlobalKeywords.SoftShadowsMedium, false); cmd.SetKeyword(ShaderGlobalKeywords.SoftShadowsHigh, false); } else { + // XR mobile uses the static quality keywords, which never take the PCSS path + cmd.SetKeyword(ShaderGlobalKeywords.SoftShadows, enabled); + cmd.SetKeyword(ShaderGlobalKeywords.ShadowsPCSS, false); if (enabled && UniversalRenderPipeline.asset?.softShadowQuality == SoftShadowQuality.Low) { cmd.SetKeyword(ShaderGlobalKeywords.SoftShadowsLow, true); @@ -1031,31 +1369,65 @@ internal static int MinimalPunctualLightShadowResolution(bool softShadow) return softShadow ? kMinimumPunctualLightSoftShadowResolution : kMinimumPunctualLightHardShadowResolution; } + static readonly GraphicsFormat[] s_ShadowmapDepthFormats = { GraphicsFormat.D16_UNorm, GraphicsFormat.D24_UNorm, GraphicsFormat.D32_SFloat }; + static readonly GraphicsFormat[] s_ShadowmapDepthStencilFormats = { GraphicsFormat.D16_UNorm_S8_UInt, GraphicsFormat.D24_UNorm_S8_UInt, GraphicsFormat.D32_SFloat_S8_UInt }; + static readonly Func s_IsShadowmapFormatSupported = format => SystemInfo.IsFormatSupported(format, GraphicsFormatUsage.Render); static bool s_WarnedNoShadowmapStencilFormat; - internal static GraphicsFormat GetShadowmapDepthStencilFormat(bool stencilBuffer) + static GraphicsFormat GetRequestedShadowmapDepthStencilFormat(DepthBits depthBits, bool stencilBuffer) { - if (stencilBuffer) + GraphicsFormat[] candidates = stencilBuffer ? s_ShadowmapDepthStencilFormats : s_ShadowmapDepthFormats; + foreach (GraphicsFormat candidate in candidates) { - // If we need stencil bits, pick whichever supported format is the smallest - if (SystemInfo.IsFormatSupported(GraphicsFormat.D16_UNorm_S8_UInt, GraphicsFormatUsage.Render)) - return GraphicsFormat.D16_UNorm_S8_UInt; - if (SystemInfo.IsFormatSupported(GraphicsFormat.D24_UNorm_S8_UInt, GraphicsFormatUsage.Render)) - return GraphicsFormat.D24_UNorm_S8_UInt; - if (SystemInfo.IsFormatSupported(GraphicsFormat.D32_SFloat_S8_UInt, GraphicsFormatUsage.Render)) - return GraphicsFormat.D32_SFloat_S8_UInt; - - // No depth-stencil format is supported here: the shadowmap falls back to depth-only and - // stencil writes silently no-op. Warn once so an enabled Shadowmap Stencil toggle that - // can't be honored on this device isn't invisible. - if (!s_WarnedNoShadowmapStencilFormat) + if (GraphicsFormatUtility.GetDepthBits(candidate) >= (int)depthBits) + return candidate; + } + + return candidates[candidates.Length - 1]; + } + + static bool TryGetSupportedShadowmapFormat(GraphicsFormat[] candidates, int minimumDepthBits, Func isFormatSupported, out GraphicsFormat format) + { + foreach (GraphicsFormat candidate in candidates) + { + if (GraphicsFormatUtility.GetDepthBits(candidate) >= minimumDepthBits && isFormatSupported(candidate)) { - s_WarnedNoShadowmapStencilFormat = true; - Debug.LogWarning("Shadowmap Stencil is enabled but this device supports no depth-stencil shadowmap format; falling back to a depth-only shadowmap (stencil writes will have no effect)."); + format = candidate; + return true; } } - return GraphicsFormatUtility.GetDepthStencilFormat(16); + format = GraphicsFormat.None; + return false; + } + + internal static GraphicsFormat SelectShadowmapDepthStencilFormat(DepthBits depthBits, bool stencilBuffer, Func isFormatSupported) + { + GraphicsFormat requested = GetRequestedShadowmapDepthStencilFormat(depthBits, stencilBuffer); + if (isFormatSupported(requested)) + return requested; + + int minimumDepthBits = GraphicsFormatUtility.GetDepthBits(requested); + if (stencilBuffer && TryGetSupportedShadowmapFormat(s_ShadowmapDepthStencilFormats, minimumDepthBits, isFormatSupported, out GraphicsFormat format)) + return format; + if (TryGetSupportedShadowmapFormat(s_ShadowmapDepthFormats, minimumDepthBits, isFormatSupported, out format)) + return format; + if (!stencilBuffer && TryGetSupportedShadowmapFormat(s_ShadowmapDepthStencilFormats, minimumDepthBits, isFormatSupported, out format)) + return format; + + return requested; + } + + internal static GraphicsFormat GetShadowmapDepthStencilFormat(DepthBits depthBits, bool stencilBuffer) + { + GraphicsFormat format = SelectShadowmapDepthStencilFormat(depthBits, stencilBuffer, s_IsShadowmapFormatSupported); + if (stencilBuffer && !GraphicsFormatUtility.IsStencilFormat(format) && !s_WarnedNoShadowmapStencilFormat) + { + s_WarnedNoShadowmapStencilFormat = true; + Debug.LogWarning($"Shadowmap Stencil is enabled, but this device doesn’t support any depth-stencil shadow map format. URP uses {format} instead, so stencil writes have no effect. To remove this warning, disable Shadowmap Stencil."); + } + + return format; } } } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/StpUtils.cs b/Packages/com.unity.render-pipelines.universal/Runtime/StpUtils.cs index 5d1d1a1998f..e0eee5adc82 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/StpUtils.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/StpUtils.cs @@ -17,7 +17,7 @@ static void CalculateJitter(int frameIndex, out Vector2 jitter, out bool allowSc static void PopulateStpConfig(UniversalCameraData cameraData, in TextureHandle inputColor, in TextureHandle inputDepth, in TextureHandle inputMotion, int debugViewIndex, in TextureHandle debugView, in TextureHandle destination, Texture2D noiseTexture, out STP.Config config) { - cameraData.camera.TryGetComponent(out var additionalCameraData); + var additionalCameraData = cameraData.additionalCameraData; Debug.Assert(additionalCameraData != null); var motionData = additionalCameraData.motionVectorsPersistentData; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/TemporalAA.cs b/Packages/com.unity.render-pipelines.universal/Runtime/TemporalAA.cs index 404a312048f..680f0e35b51 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/TemporalAA.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/TemporalAA.cs @@ -359,7 +359,8 @@ internal static string ValidateAndWarn(UniversalCameraData cameraData, ref uint reasonWarning = "because MSAA is on. Turn MSAA off on the camera or current URP Asset."; } - if(reasonWarning == null && cameraData.camera.TryGetComponent(out var additionalCameraData)) + var additionalCameraData = cameraData.additionalCameraData; + if (reasonWarning == null && additionalCameraData != null) { if (additionalCameraData.renderType == CameraRenderType.Overlay || additionalCameraData.cameraStack.Count > 0) diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/LightMinMaxZJob.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/LightMinMaxZBinsJob.cs similarity index 76% rename from Packages/com.unity.render-pipelines.universal/Runtime/Tiling/LightMinMaxZJob.cs rename to Packages/com.unity.render-pipelines.universal/Runtime/Tiling/LightMinMaxZBinsJob.cs index 513751ea59a..39319074f7d 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/LightMinMaxZJob.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/LightMinMaxZBinsJob.cs @@ -5,17 +5,19 @@ namespace UnityEngine.Rendering.Universal { - [BurstCompile] - struct LightMinMaxZJob : IJobFor + [BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)] + struct LightMinMaxZBinsJob : IJobFor { public Fixed2 worldToViews; [ReadOnly] public NativeArray lights; - public NativeArray minMaxZs; + public NativeArray minMaxZBins; public float near; + public ZBinMapping zBinMapping; + public void Execute(int index) { var lightIndex = index % lights.Length; @@ -29,18 +31,22 @@ public void Execute(int index) var minMax = math.float2(originVS.z - light.range, originVS.z + light.range); - if (light.lightType == LightType.Spot) + if (!TilingJob.HasNonZeroVolume(light)) + { + minMax.x = float.MaxValue; + minMax.y = float.MinValue; + } + else if (light.lightType == LightType.Spot) { // Based on https://iquilezles.org/www/articles/diskbbox/diskbbox.htm var angleA = math.radians(light.spotAngle) * 0.5f; - float cosAngleA = math.cos(angleA); + math.sincos(angleA, out var sinAngleA, out var cosAngleA); float coneHeight = light.range * cosAngleA; float3 spotDirectionWS = lightToWorld.c2.xyz; var endPointWS = originWS + spotDirectionWS * coneHeight; var endPointVS = math.mul(worldToView, math.float4(endPointWS, 1)).xyz; endPointVS.z *= -1; - var angleB = math.PI * 0.5f - angleA; - var coneRadius = light.range * cosAngleA * math.sin(angleA) / math.sin(angleB); + var coneRadius = light.range * sinAngleA; var a = endPointVS - originVS; // 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))); @@ -50,18 +56,11 @@ public void Execute(int index) if (-a.z < coneHeight * cosAngleA) minMax.x = math.min(originVS.z, endPointVS.z - e * coneRadius); if (a.z < coneHeight * cosAngleA) minMax.y = math.max(originVS.z, endPointVS.z + e * coneRadius); } - else if (light.lightType != LightType.Point) - { - // Currently we support only spot, point and directional lights in URP. This job only deals with the - // first two. If any other light type is found, skip that light. - minMax.x = float.MaxValue; - minMax.y = float.MinValue; - } - // Clamp to near, not 0: an orthographic near plane can be negative. + // Clamp to near, not 0: an orthographic near plane can be negative. A light entirely closer than the near + // plane keeps max < min, which ZBinMapping.ToBins turns into an empty bin span. minMax.x = math.max(minMax.x, near); - minMax.y = math.max(minMax.y, near); - minMaxZs[index] = minMax; + minMaxZBins[index] = zBinMapping.ToBins(minMax); } } } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/LightMinMaxZJob.cs.meta b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/LightMinMaxZBinsJob.cs.meta similarity index 100% rename from Packages/com.unity.render-pipelines.universal/Runtime/Tiling/LightMinMaxZJob.cs.meta rename to Packages/com.unity.render-pipelines.universal/Runtime/Tiling/LightMinMaxZBinsJob.cs.meta diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/ReflectionProbeMinMaxZJob.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/ReflectionProbeMinMaxZBinsJob.cs similarity index 72% rename from Packages/com.unity.render-pipelines.universal/Runtime/Tiling/ReflectionProbeMinMaxZJob.cs rename to Packages/com.unity.render-pipelines.universal/Runtime/Tiling/ReflectionProbeMinMaxZBinsJob.cs index 30aaaf490de..84dae8dcc7b 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/ReflectionProbeMinMaxZJob.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/ReflectionProbeMinMaxZBinsJob.cs @@ -5,8 +5,8 @@ namespace UnityEngine.Rendering.Universal { - [BurstCompile] - struct ReflectionProbeMinMaxZJob : IJobFor + [BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)] + struct ReflectionProbeMinMaxZBinsJob : IJobFor { public Fixed2 worldToViews; @@ -14,13 +14,23 @@ struct ReflectionProbeMinMaxZJob : IJobFor public NativeArray reflectionProbes; [ReadOnly] public bool reflectionProbeRotation; - public NativeArray minMaxZs; + public NativeArray minMaxZBins; + + public ZBinMapping zBinMapping; + + public float near; public void Execute(int index) { var minMax = math.float2(float.MaxValue, float.MinValue); var reflectionProbeIndex = index % reflectionProbes.Length; var reflectionProbe = reflectionProbes[reflectionProbeIndex]; + if (!TilingJob.HasNonZeroVolume(reflectionProbe)) + { + minMaxZBins[index] = zBinMapping.ToBins(minMax); + return; + } + var viewIndex = index / reflectionProbes.Length; var worldToView = worldToViews[viewIndex]; var centerWS = (float3)reflectionProbe.bounds.center; @@ -45,7 +55,9 @@ public void Execute(int index) minMax.y = math.max(minMax.y, cornerVS.z); } - minMaxZs[index] = minMax; + // As in LightMinMaxZBinsJob: a probe entirely closer than the near plane keeps max < min. + minMax.x = math.max(minMax.x, near); + minMaxZBins[index] = zBinMapping.ToBins(minMax); } } } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/ReflectionProbeMinMaxZJob.cs.meta b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/ReflectionProbeMinMaxZBinsJob.cs.meta similarity index 100% rename from Packages/com.unity.render-pipelines.universal/Runtime/Tiling/ReflectionProbeMinMaxZJob.cs.meta rename to Packages/com.unity.render-pipelines.universal/Runtime/Tiling/ReflectionProbeMinMaxZBinsJob.cs.meta diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TileRangeExpansionJob.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TileRangeExpansionJob.cs index 8bbd9d2ac3b..9fc9b1f9816 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TileRangeExpansionJob.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TileRangeExpansionJob.cs @@ -23,41 +23,53 @@ public void Execute(int jobIndex) { var rowIndex = jobIndex % tileResolution.y; var viewIndex = jobIndex / tileResolution.y; - var compactCount = 0; - var itemIndices = new NativeArray(itemsPerTile, Allocator.Temp); - var itemRanges = new NativeArray(itemsPerTile, Allocator.Temp); - // Compact the light ranges for the current row. + var rowBaseMaskIndex = viewIndex * wordsPerTile * tileResolution.x * tileResolution.y + rowIndex * wordsPerTile * tileResolution.x; + var rowRangeBase = viewIndex * rangesPerItem * itemsPerTile + 1 + rowIndex; + + var rowWordCount = tileResolution.x * wordsPerTile; + for (var i = 0; i < rowWordCount; i++) + tileMasks[rowBaseMaskIndex + i] = 0; + + // Toggle each item's bit at its first column and one past its last, then XOR left to right so the bit is set + // exactly inside the range. With one word per tile, setting the bits directly is a contiguous loop and cheaper. + // Clip to on-screen columns; the tiling job leaves one tile of off-screen slack. + var sweep = wordsPerTile > 1; for (var itemIndex = 0; itemIndex < itemsPerTile; itemIndex++) { - var range = tileRanges[viewIndex * rangesPerItem * itemsPerTile + itemIndex * rangesPerItem + 1 + rowIndex]; - if (!range.isEmpty) + var range = tileRanges[rowRangeBase + itemIndex * rangesPerItem]; + var start = math.max((int)range.start, 0); + var end = math.min((int)range.end, tileResolution.x - 1); + if (start > end) continue; + + var wordIndex = itemIndex / 32; + var itemMask = 1u << (itemIndex % 32); + if (sweep) { - itemIndices[compactCount] = (short)itemIndex; - itemRanges[compactCount] = range; - compactCount++; + tileMasks[rowBaseMaskIndex + start * wordsPerTile + wordIndex] ^= itemMask; + if (end + 1 < tileResolution.x) + tileMasks[rowBaseMaskIndex + (end + 1) * wordsPerTile + wordIndex] ^= itemMask; + } + else + { + for (var tileIndex = start; tileIndex <= end; tileIndex++) + tileMasks[rowBaseMaskIndex + tileIndex * wordsPerTile + wordIndex] |= itemMask; } } - var rowBaseMaskIndex = viewIndex * wordsPerTile * tileResolution.x * tileResolution.y + rowIndex * wordsPerTile * tileResolution.x; - for (var tileIndex = 0; tileIndex < tileResolution.x; tileIndex++) + if (sweep) { - var tileBaseIndex = rowBaseMaskIndex + tileIndex * wordsPerTile; - for (var i = 0; i < compactCount; i++) + // The running value stays in a register; XOR-ing through tileMasks would serialize on store-to-load latency. + for (var wordIndex = 0; wordIndex < wordsPerTile; wordIndex++) { - var itemIndex = (int)itemIndices[i]; - var wordIndex = itemIndex / 32; - var itemMask = 1u << (itemIndex % 32); - var range = itemRanges[i]; - if (range.Contains((short)tileIndex)) + var running = 0u; + for (var i = rowBaseMaskIndex + wordIndex; i < rowBaseMaskIndex + rowWordCount; i += wordsPerTile) { - tileMasks[tileBaseIndex + wordIndex] |= itemMask; + running ^= tileMasks[i]; + tileMasks[i] = running; } } } - - itemIndices.Dispose(); - itemRanges.Dispose(); } } } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.Geometry.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.Geometry.cs new file mode 100644 index 00000000000..8b3d6cf956e --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.Geometry.cs @@ -0,0 +1,351 @@ +using Unity.Mathematics; + +namespace UnityEngine.Rendering.Universal +{ + // Static sphere, circle and cone geometry shared by the perspective and orthographic light tiling. + partial struct TilingJob + { + // 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 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; + } + + /// + /// Finds the points where the tangents from the origin touch a 2D circle. Returns false if the origin is inside it. + /// + static bool GetCircleHorizon(float2 center, float radius, out float2 p0, out float2 p1) + { + // 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 lSq = dSq - square(radius); + if (lSq < 0f || dSq == 0f) + { + p0 = p1 = 0; + return false; + } + + var l = math.sqrt(lSq); + var side = l * radius * math.float2(-center.y, center.x); + p0 = (square(l) * center + side) / dSq; + p1 = (square(l) * center - side) / dSq; + return true; + } + + /// + /// Where the rays (x, y, 1) of view-plane rows touch a sphere. A ray d touches it where dot(d, c)^2 = |d|^2 * (|c|^2 - r^2), + /// a quadratic in x, solved here divided by |c|^2 to keep its coefficients near 1; the point is d * dot(d, c) / |d|^2. + /// + internal struct SphereRowTangents + { + float3 m_Center; + float3 m_UnitCenter; + float m_TangentFraction; + + public SphereRowTangents(float3 center, float radiusSq) + { + var centerLengthSq = math.lengthsq(center); + var tangentLengthSq = centerLengthSq - radiusSq; + m_Center = center; + m_UnitCenter = tangentLengthSq > 0f ? center * math.rsqrt(centerLengthSq) : 0f; + m_TangentFraction = tangentLengthSq > 0f ? tangentLengthSq / centerLengthSq : 0f; + } + + /// + /// Finds the points touched by the rays of the row at height y. Returns which of the two exist; there are none when + /// the origin is inside the sphere. + /// + public bool2 Find(float y, out float3 p0, out float3 p1) + { + p0 = p1 = 0; + if (m_TangentFraction <= 0f) + return false; + + var m = y * m_UnitCenter.y + m_UnitCenter.z; + var n = y * y + 1f; + var found = SolveQuadratic(square(m_UnitCenter.x) - m_TangentFraction, m_UnitCenter.x * m, m * m - m_TangentFraction * n, out var x); + if (!math.any(found)) + return found; + + var d0 = math.float3(x.x, y, 1f); + var d1 = math.float3(x.y, y, 1f); + p0 = d0 * (math.dot(d0, m_Center) / math.lengthsq(d0)); + p1 = d1 * (math.dot(d1, m_Center) / math.lengthsq(d1)); + return found; + } + } + + /// + /// Finds 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. Returns false if there are none. + /// + static bool GetSphereSectionRowPoints(float3 center, float radiusSq, float depth, float planeY, out float3 p0, out float3 p1) + { + var y = planeY * depth; + var halfWidthSq = radiusSq - square(depth - center.z) - square(y - center.y); + if (halfWidthSq < 0f) + { + p0 = p1 = 0; + return false; + } + + var halfWidth = math.sqrt(halfWidthSq); + p0 = math.float3(center.x - halfWidth, y, depth); + p1 = math.float3(center.x + halfWidth, y, depth); + return true; + } + + /// + /// Finds the two points of intersection of a 3D circle and the plane z = near. Returns false if there are none. + /// + static bool GetCircleClipPoints(float3 circleCenter, float3 circleNormal, float circleRadius, float near, out float3 p0, out float3 p1) + { + p0 = p1 = 0; + + // The intersection of two planes is a line where the direction is the cross product of the two plane normals. + // In this case, it is the plane containing the circle, and the near plane. A circle parallel to the plane has none. + var cross = math.cross(circleNormal, math.float3(0, 0, 1)); + if (math.lengthsq(cross) == 0f) + return false; + var lineDirection = math.normalize(cross); + + // Find a direction on the circle plane towards the nearest point on the intersection line. + // It has to be perpendicular to the circle normal to be in the circle plane. The direction to the closest + // point on a line is perpendicular to the line direction. Thus this is given by the cross product of the + // line direction and the circle normal, as this gives us a vector that is perpendicular to both of those. + var nearestDirection = math.cross(lineDirection, circleNormal); + + // Distance from circle center to the intersection line along `nearestDirection`. + // This is done using a ray-plane intersection, where the plane is the near plane. + // ({0, 0, near} - circleCenter) . {0, 0, 1} / (nearestDirection . {0, 0, 1}) + var distance = (near - circleCenter.z) / nearestDirection.z; + if (math.abs(distance) > circleRadius) + return false; + + // The point on the line nearest to the circle center when traveling only in the circle plane. + var nearestPoint = circleCenter + nearestDirection * distance; + + // Any line through a circle makes a chord where the endpoints are the intersections with the circle. + // The half length of the circle chord can be found by constructing a right triangle from three points: + // (a) The circle center. + // (b) The nearest point. + // (c) A point that is on circle and the intersection line. + // The hypotenuse is formed by (a) and (c) and will have length `circleRadius` as it is on the circle. + // The known side if formed by (a) and (b), which we have already calculated the distance of in `distance`. + // The unknown side formed by (b) and (c) is then found using Pythagoras. + var chordHalfLength = math.sqrt(square(circleRadius) - square(distance)); + p0 = nearestPoint + lineDirection * chordHalfLength; + p1 = nearestPoint - lineDirection * chordHalfLength; + return true; + } + + /// + /// Calculates the horizon of a circle orthogonally projected to a plane as seen from the origin on the plane. Returns + /// false if the origin is inside the projected ellipse. + /// + /// The center of the circle projected onto the plane. + /// The radius of the circle. + /// The major axis of the ellipse formed by the projection of the circle. + /// 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 . + internal static bool 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. + var vl = math.length(V); + if (vl < 1e-6f) + { + uv1 = math.float2(radius, 0); + uv2 = math.float2(-radius, 0); + return true; + } + + var ul = math.length(U); + + // Normalize U and V in the plane. + var u = U / ul; + var v = V / vl; + + // Major and minor axis of the ellipse. + var a = ul * radius; + var b = vl * radius; + + // 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. + var q = math.float2(math.dot(-center, u), math.dot(-center, v)) / math.float2(a, b); + var qq = math.lengthsq(q); + if (qq < 1f) + { + uv1 = uv2 = 0; + return false; + } + + var side = math.sqrt(qq - 1f) * math.float2(-q.y, q.x); + uv1 = (q + side) / qq * radius; + uv2 = (q - side) / qq * radius; + return true; + } + + /// + /// Intersects a 3D circle with a plane, given as the line a * s + b * t + k = 0 in the circle's (s, t) coordinates, as the + /// view-space x and z of the two points. Returns false if the line misses the circle. + /// + static bool IntersectCircleLine(float a, float b, float k, float3 circleCenter, float3 circleU, float3 circleV, float circleRadiusSq, out float2 xz0, out float2 xz1) + { + xz0 = xz1 = 0; + + // The points are (-k * (a, b) +- sqrt(r^2 * (a^2 + b^2) - k^2) * (-b, a)) / (a^2 + b^2). Planes parallel to the circle + // (a = b = 0) give the whole circle or nothing, which the other bounds cover. + var lengthSq = a * a + b * b; + var discriminant = circleRadiusSq * lengthSq - k * k; + if (lengthSq == 0f || discriminant < 0f) + return false; + + var root = math.sqrt(discriminant); + var invLengthSq = math.rcp(lengthSq); + var s = (-k * a + math.float2(-root, root) * b) * invLengthSq; + var t = (-k * b + math.float2(root, -root) * a) * invLengthSq; + xz0 = circleCenter.xz + s.x * circleU.xz + t.x * circleV.xz; + xz1 = circleCenter.xz + s.y * circleU.xz + t.y * circleV.xz; + return true; + } + + /// + /// 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. Returns false if there are none. + /// + static bool 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.lengthsq(toCamera) == 0f || math.dot(math.normalize(toCamera), axis) >= cosHalfAngle) + { + return false; + } + + // 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 false; + } + + 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; + return true; + } + + /// + /// 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 + { + 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; + } + + /// + /// Finds the points with extreme y. Returns which of the two exist. + /// + public bool2 GetYExtremes(out float3 p0, out float3 p1) + { + var d = m_Axis; + var found = SolveQuadratic(d.z * d.z - m_SinSq, -d.y * d.z * m_Z, m_Z * m_Z * (d.y * d.y - m_SinSq), out var y); + var denominator = d.x * d.x - m_CosSq; + if (denominator == 0f) + { + p0 = p1 = 0; + return false; + } + + var x = -d.x * (d.y * y + d.z * m_Z) / denominator; + p0 = ToView(x.x, y.x); + p1 = ToView(x.y, y.y); + return found; + } + + /// + /// Finds the points with extreme x. Returns which of the two exist. + /// + public bool2 GetXExtremes(out float3 p0, out float3 p1) + { + var d = m_Axis; + var found = SolveQuadratic(d.z * d.z - m_SinSq, -d.x * d.z * m_Z, m_Z * m_Z * (d.x * d.x - m_SinSq), out var x); + var denominator = d.y * d.y - m_CosSq; + if (denominator == 0f) + { + p0 = p1 = 0; + return false; + } + + var y = -d.y * (d.x * x + d.z * m_Z) / denominator; + p0 = ToView(x.x, y.x); + p1 = ToView(x.y, y.y); + return found; + } + + /// + /// Finds the points at view-space height y. Returns which of the two exist. + /// + public bool2 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 found = SolveQuadratic(d.x * d.x - m_CosSq, d.x * k, k * k - m_CosSq * (y * y + m_Z * m_Z), out var x); + p0 = ToView(x.x, y); + p1 = ToView(x.y, y); + return found; + } + + float3 ToView(float x, float y) => math.float3(m_Vertex.xy + math.float2(x, y), m_Depth); + } + + /// + /// Finds the roots of a * t^2 + 2 * b * t + c = 0 and returns which of the two exist: none for a negative + /// discriminant, and only c / q if a is 0. + /// + static bool2 SolveQuadratic(float a, float b, float c, out float2 roots) + { + roots = 0; + var discriminant = b * b - a * c; + if (discriminant < 0f) + return false; + + // Avoids the cancellation in -b + sqrt(b^2 - ac) by computing that root as c / q. + var q = -(b + (b < 0f ? -math.sqrt(discriminant) : math.sqrt(discriminant))); + var found = math.bool2(a != 0f, q != 0f); + roots = math.select(0f, math.float2(q, c) / math.select(1f, math.float2(a, q), found), found); + return found; + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.Geometry.cs.meta b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.Geometry.cs.meta new file mode 100644 index 00000000000..3bbb3229b75 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.Geometry.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 90140b5c5a58400eb0f6a6d1bc63df38 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.OrthographicLight.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.OrthographicLight.cs new file mode 100644 index 00000000000..2b84aa4d123 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.OrthographicLight.cs @@ -0,0 +1,191 @@ +using Unity.Mathematics; + +namespace UnityEngine.Rendering.Universal +{ + // Orthographic point/spot light tiling: the same outline as the perspective case, without a perspective divide. + partial struct TilingJob + { + void TileLightOrthographic(int lightIndex) + { + var light = lights[lightIndex]; + if (!HasNonZeroVolume(light)) + { + return; + } + + var lightToWorld = (float4x4)light.localToWorldMatrix; + var lightPosVS = math.mul(worldToViews[m_ViewIndex], math.float4(lightToWorld.c3.xyz, 1)).xyz; + lightPosVS.z *= -1; + var range = math.min(light.range, k_MaxDistance); + if (lightPosVS.z - range > far || lightPosVS.z + range < near) + return; + 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 rangeSq = square(range); + var cosHalfAngle = math.cos(halfAngle); + var sinHalfAngle = math.sin(halfAngle); + var coneHeight = cosHalfAngle * range; + + // 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 = 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 hasSilhouette = false; + var coneDistanceTolerance = 1e-5f * (math.length(lightPosVS) + range); + + if (isSpot) + { + // Extremes of the cone base circle, and its points on the near and far planes. An axis along y or x leaves + // the circle no extent along that axis. + var circleUp = math.float3(0, 1, 0) - lightDirVS * lightDirVS.y; + if (math.lengthsq(circleUp) > 0f) + { + circleUp = math.normalize(circleUp) * circleRadius; + ExpandOrthographicIfInDepthRange(circleCenter - circleUp); + ExpandOrthographicIfInDepthRange(circleCenter + circleUp); + } + var circleRight = math.float3(1, 0, 0) - lightDirVS * lightDirVS.x; + if (math.lengthsq(circleRight) > 0f) + { + circleRight = math.normalize(circleRight) * circleRadius; + 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); + } + } + + // 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; + var foundY = section.GetYExtremes(out var p0Y, out var p1Y); + var foundX = section.GetXExtremes(out var p0X, out var p1X); + if (foundY.x && IsOnCone(p0Y, lightPosVS, lightDirVS, cosHalfAngle, sinHalfAngle, coneHeight, coneDistanceTolerance)) ExpandOrthographic(p0Y); + if (foundY.y && IsOnCone(p1Y, lightPosVS, lightDirVS, cosHalfAngle, sinHalfAngle, coneHeight, coneDistanceTolerance)) ExpandOrthographic(p1Y); + if (foundX.x && IsOnCone(p0X, lightPosVS, lightDirVS, cosHalfAngle, sinHalfAngle, coneHeight, coneDistanceTolerance)) ExpandOrthographic(p0X); + if (foundX.y && IsOnCone(p1X, lightPosVS, lightDirVS, cosHalfAngle, sinHalfAngle, coneHeight, coneDistanceTolerance)) ExpandOrthographic(p1X); + } + + // Silhouette lines of the cone as seen along the view direction. + hasSilhouette = GetConeSideTangentPoints(math.float3(0, 0, -1), lightDirVS, cosHalfAngle, circleRadius, coneHeight, range, coneU, coneV, out l1, out l2); + } + + 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; + var planeY = math.lerp(viewPlaneBottoms[m_ViewIndex], viewPlaneTops[m_ViewIndex], planeIndex * tileScaleInv.y); + + for (var i = 0; i < 3; i++) + { + if (!sphereOutline[i]) + continue; + var depth = i == 0 ? lightPosVS.z : i == 1 ? near : far; + var halfWidthSq = rangeSq - square(depth - lightPosVS.z) - square(planeY - lightPosVS.y); + if (halfWidthSq < 0f) + continue; + var halfWidth = math.sqrt(halfWidthSq); + 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) + { + // The row is the plane y = planeY. + if (IntersectCircleLine(coneU.y, coneV.y, circleCenter.y - planeY, circleCenter, coneU, coneV, square(circleRadius), out var circle0, out var circle1)) + { + if (IsDepthInRange(circle0.y)) ExpandRangeOrthographic(ref planeRange, circle0.x); + if (IsDepthInRange(circle1.y)) ExpandRangeOrthographic(ref planeRange, circle1.x); + } + + if (hasSilhouette) + { + ExpandRangeOrthographicAtRow(ref planeRange, lightPosVS, l1, planeY); + ExpandRangeOrthographicAtRow(ref planeRange, lightPosVS, l2, planeY); + } + + for (var i = 0; i < 2; i++) + { + if (!coneCrosses[i]) + continue; + var found = (i == 0 ? nearSection : farSection).IntersectRow(planeY, out var p0, out var p1); + if (found.x && IsOnCone(p0, lightPosVS, lightDirVS, cosHalfAngle, sinHalfAngle, coneHeight, coneDistanceTolerance)) ExpandRangeOrthographic(ref planeRange, p0.x); + if (found.y && IsOnCone(p1, lightPosVS, lightDirVS, cosHalfAngle, sinHalfAngle, coneHeight, coneDistanceTolerance)) ExpandRangeOrthographic(ref planeRange, p1.x); + } + } + + MergeTileRangeRows(planeIndex, planeRange); + } + + tileRanges[m_Offset] = m_TileYRange; + } + + // Expands a row range where the segment from origin to origin + line crosses the row plane y = planeY. + void ExpandRangeOrthographicAtRow(ref InclusiveRange range, float3 origin, float3 line, float planeY) + { + if (line.y == 0f) + return; + var p = origin + line * ((planeY - origin.y) / line.y); + if (IsOnSegment(p, origin, line)) ExpandRangeOrthographic(ref range, p.x); + } + + // 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); + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.OrthographicLight.cs.meta b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.OrthographicLight.cs.meta new file mode 100644 index 00000000000..56632b4472e --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.OrthographicLight.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 2fd4ce49f790f457bb1e4da662248930 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.PerspectiveLight.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.PerspectiveLight.cs new file mode 100644 index 00000000000..a4ccd74f296 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.PerspectiveLight.cs @@ -0,0 +1,299 @@ +using System.Runtime.CompilerServices; +using Unity.Mathematics; + +namespace UnityEngine.Rendering.Universal +{ + // Perspective point/spot light tiling: the sphere, and for spots the cone base, sides and near/far sections. + partial struct TilingJob + { + void TileLight(int lightIndex) + { + var light = lights[lightIndex]; + if (!HasNonZeroVolume(light)) + { + return; + } + + var lightToWorld = (float4x4)light.localToWorldMatrix; + var lightPositionVS = math.mul(worldToViews[m_ViewIndex], math.float4(lightToWorld.c3.xyz, 1)).xyz; + lightPositionVS.z *= -1; + var range = math.min(light.range, k_MaxDistance); + if (lightPositionVS.z - range > far || lightPositionVS.z + range < near) + return; + if (light.lightType == LightType.Point && SphereContainsNearPlane(lightPositionVS, range)) + { + CoverAllTiles(); + return; + } + if (IsInDepthRange(lightPositionVS)) ExpandY(lightPositionVS); + var lightDirectionVS = math.normalize(math.mul(worldToViews[m_ViewIndex], math.float4(lightToWorld.c2.xyz, 0)).xyz); + lightDirectionVS.z *= -1; + + var halfAngle = math.radians(light.spotAngle * 0.5f); + var rangesq = square(range); + var cosHalfAngle = math.cos(halfAngle); + var coneHeight = cosHalfAngle * range; + 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. + if (GetCircleHorizon(lightPositionVS.yz, range, out var horizonY0, out var horizonY1)) + { + ExpandYIfInSphereCap(math.float3(lightPositionVS.x, horizonY0), lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot); + ExpandYIfInSphereCap(math.float3(lightPositionVS.x, horizonY1), lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot); + } + if (GetCircleHorizon(lightPositionVS.xz, range, out var horizonX0, out var horizonX1)) + { + 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); + } + + var sphereRowTangents = new SphereRowTangents(lightPositionVS, rangesq); + var sectionRadiusSq = rangesq - math.float2(square(near - lightPositionVS.z), square(far - lightPositionVS.z)); + var sphereCrossesPlane = sectionRadiusSq >= 0f; + for (var i = 0; i < 2; i++) + { + if (!sphereCrossesPlane[i]) + continue; + var depth = i == 0 ? near : far; + var sectionRadius = math.sqrt(sectionRadiusSq[i]); + 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) + { + // Cone base + var baseRadiusSq = math.max(range * range - coneHeight * coneHeight, 0f); + var baseRadius = math.sqrt(baseRadiusSq); + var baseCenter = lightPositionVS + lightDirectionVS * coneHeight; + + // Project cone base (a circle) into the YZ plane, find the horizon points, and re-construct view space position of found points. + // When projecting a circle to a plane, it becomes an ellipse where the major axis is parallel to the line + // of intersection of the projection plane and the circle plane. We can get this by taking the cross product + // of the two plane normals, as the line of intersection will have to be a vector in both planes, and thus + // orthogonal to both normals. + // If the two plane normals are parallel, the cross product would return 0. In that case, the circle will + // project to a line segment, so we pick a vector in the plane pointing in the direction we're interested + // in finding horizon points in. + var baseUY = math.abs(math.abs(lightDirectionVS.x) - 1) < 1e-6f ? math.float3(0, 1, 0) : math.normalize(math.cross(lightDirectionVS, math.float3(1, 0, 0))); + var baseVY = math.cross(lightDirectionVS, baseUY); + if (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 (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. + var baseUX = math.abs(math.abs(lightDirectionVS.y) - 1) < 1e-6f ? math.float3(1, 0, 0) : math.normalize(math.cross(lightDirectionVS, math.float3(0, 1, 0))); + var baseVX = math.cross(lightDirectionVS, baseUX); + if (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 (IsInDepthRange(baseX1)) ExpandY(baseX1); + if (IsInDepthRange(baseX2)) ExpandY(baseX2); + } + + // 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); + } + + 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 and far planes. + // From https://www.iquilezles.org/www/articles/diskbbox/diskbbox.htm + 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); + + 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++) + { + if (i == 0 ? !coneIsClipping : !coneCrossesFar) + continue; + var section = i == 0 ? nearSection : farSection; + var foundY = section.GetYExtremes(out var p0Y, out var p1Y); + if (foundY.x && ConicPointIsValid(p0Y)) ExpandY(p0Y); + if (foundY.y && ConicPointIsValid(p1Y)) ExpandY(p1Y); + + var foundX = section.GetXExtremes(out var p0X, out var p1X); + if (foundX.x && ConicPointIsValid(p0X)) ExpandY(p0X); + if (foundX.y && 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. + var hasSilhouette = GetConeSideTangentPoints(-lightPositionVS, lightDirectionVS, cosHalfAngle, baseRadius, coneHeight, range, coneU, coneV, out var l1, out var l2); + + // Where the cone sides cross the bottom and top of the screen. + if (hasSilhouette) + { + 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 and sphere. + for (var planeIndex = m_TileYRange.start; planeIndex <= m_TileYRange.end + 1; planeIndex++) + { + var planeRange = InclusiveRange.empty; + + // Y-position on the view plane (Z=1) + var planeY = math.lerp(viewPlaneBottoms[m_ViewIndex], viewPlaneTops[m_ViewIndex], planeIndex * tileScaleInv.y); + + ExpandSphereRow(ref planeRange, planeY, sphereRowTangents, lightPositionVS, range, lightDirectionVS, cosHalfAngle, isSpot, sphereCrossesPlane); + + // Intersect lines with y-plane and clip if needed. + if (hasSilhouette) + { + var planeNormal = math.float3(0, 1, -planeY); + ExpandTileXAtRowPlane(ref planeRange, lightPositionVS, l1, planeNormal); + ExpandTileXAtRowPlane(ref planeRange, lightPositionVS, l2, planeNormal); + } + + // The row plane through the camera has normal (0, 1, -planeY). + var circleLineA = baseUY.y - planeY * baseUY.z; + var circleLineB = baseVY.y - planeY * baseVY.z; + var circleLineK = baseCenter.y - planeY * baseCenter.z; + if (IntersectCircleLine(circleLineA, circleLineB, circleLineK, baseCenter, baseUY, baseVY, baseRadiusSq, out var circleXZ0, out var circleXZ1)) + { + ExpandTileXIfInDepthRange(ref planeRange, circleXZ0); + ExpandTileXIfInDepthRange(ref planeRange, circleXZ1); + } + + if (coneIsClipping) + { + var found = nearSection.IntersectRow(planeY * near, out var p0, out var p1); + if (found.x && ConicPointIsValid(p0)) ExpandTileX(ref planeRange, ViewToTileSpace(p0).x); + if (found.y && ConicPointIsValid(p1)) ExpandTileX(ref planeRange, ViewToTileSpace(p1).x); + } + + if (coneCrossesFar) + { + var found = farSection.IntersectRow(planeY * far, out var p0, out var p1); + if (found.x && ConicPointIsValid(p0)) ExpandTileX(ref planeRange, ViewToTileSpace(p0).x); + if (found.y && ConicPointIsValid(p1)) ExpandTileX(ref planeRange, ViewToTileSpace(p1).x); + } + + MergeTileRangeRows(planeIndex, planeRange); + } + } + + m_TileYRange.Clamp(0, (short)(tileCount.y - 1)); + + // Spots already swept the sphere together with the cone above. + if (!isSpot) + { + 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); + ExpandSphereRow(ref planeRange, planeY, sphereRowTangents, lightPositionVS, range, lightDirectionVS, cosHalfAngle, isSpot, sphereCrossesPlane); + MergeTileRangeRows(planeIndex, planeRange); + } + } + + tileRanges[m_Offset] = m_TileYRange; + } + + // Every tile's frustum starts on the near-plane rectangle, so a sphere containing it covers all tiles. + bool SphereContainsNearPlane(float3 center, float radius) + { + var viewportToNear = (math.float4(0, 0, 1, 1) - m_ViewToViewportScaleBias.zwzw) / m_ViewToViewportScaleBias.xyxy * near; + var dx = math.max(math.abs(viewportToNear.x - center.x), math.abs(viewportToNear.z - center.x)); + var dy = math.max(math.abs(viewportToNear.y - center.y), math.abs(viewportToNear.w - center.y)); + return square(dx) + square(dy) + square(near - center.z) <= square(radius); + } + + void CoverAllTiles() + { + var fullRow = new InclusiveRange(0, (short)(tileCount.x - 1)); + for (var row = 0; row < tileCount.y; row++) + tileRanges[m_Offset + 1 + row] = fullRow; + tileRanges[m_Offset] = new InclusiveRange(0, (short)(tileCount.y - 1)); + } + + // Where the plane through the origin and the view-plane row at height planeY crosses the outline of the sphere. + // Runs per row per light; Burst does not inline it on its own. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + void ExpandSphereRow(ref InclusiveRange planeRange, float planeY, in SphereRowTangents sphereRowTangents, float3 lightPositionVS, float range, float3 lightDirectionVS, float cosHalfAngle, bool isSpot, bool2 sphereCrossesPlane) + { + var found = sphereRowTangents.Find(planeY, out var sphereTile0, out var sphereTile1); + if (found.x) ExpandTileXIfInSphereCap(ref planeRange, sphereTile0, lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot); + if (found.y) ExpandTileXIfInSphereCap(ref planeRange, sphereTile1, lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot); + for (var i = 0; i < 2; i++) + { + // Checked once per light, so most rows skip the near and far sections entirely. + if (sphereCrossesPlane[i] && GetSphereSectionRowPoints(lightPositionVS, square(range), 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); + } + } + } + + void ExpandYIfInSphereCap(float3 positionVS, float3 lightPositionVS, float3 lightDirectionVS, float cosHalfAngle, bool isSpot) + { + if (IsInSphereCap(positionVS, lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot)) ExpandY(positionVS); + } + + void ExpandTileXIfInSphereCap(ref InclusiveRange range, float3 positionVS, float3 lightPositionVS, float3 lightDirectionVS, float cosHalfAngle, bool isSpot) + { + if (IsInSphereCap(positionVS, lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot)) ExpandTileX(ref range, ViewToTileSpace(positionVS).x); + } + + // 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 planeNormal = math.float3(0, 1, -planeY); + var denominator = math.dot(line, planeNormal); + if (denominator == 0f) + return; + var t = math.dot(-origin, planeNormal) / denominator; + var positionVS = origin + line * t; + if (t >= 0 && t <= 1 && IsInDepthRange(positionVS)) ExpandY(positionVS); + } + + void ExpandTileXIfInDepthRange(ref InclusiveRange planeRange, float2 xzVS) + { + if (IsDepthInRange(xzVS.y)) ExpandTileX(ref planeRange, ViewToTileSpace(math.float3(xzVS.x, 0f, xzVS.y)).x); + } + + // Expands a row range where the segment from origin to origin + line crosses the row plane through the camera. + void ExpandTileXAtRowPlane(ref InclusiveRange planeRange, float3 origin, float3 line, float3 planeNormal) + { + var denominator = math.dot(line, planeNormal); + if (denominator == 0f) + return; + var t = math.dot(-origin, planeNormal) / denominator; + var positionVS = origin + line * t; + if (t >= 0 && t <= 1 && IsInDepthRange(positionVS)) ExpandTileX(ref planeRange, ViewToTileSpace(positionVS).x); + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.PerspectiveLight.cs.meta b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.PerspectiveLight.cs.meta new file mode 100644 index 00000000000..7b3feed2dd8 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.PerspectiveLight.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 18d2b0230bb604ddda12c23c8efd44d0 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.ReflectionProbe.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.ReflectionProbe.cs new file mode 100644 index 00000000000..1794b0e3092 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.ReflectionProbe.cs @@ -0,0 +1,174 @@ +using System; +using Unity.Mathematics; + +namespace UnityEngine.Rendering.Universal +{ + // Reflection probe tiling: box edges clipped to the depth range, projected to a 2D convex hull. + partial struct TilingJob + { + const int k_CubePointCount = 8; + + // Cube corners between the near and far planes, plus a near and a far clip point for each of the 12 edges. + const int k_MaxClippedPointCount = k_CubePointCount + 4 * 3 * 2; + + static readonly float3[] k_CubePoints = + { + new(-1, -1, -1), + new(-1, -1, +1), + new(-1, +1, -1), + new(-1, +1, +1), + new(+1, -1, -1), + new(+1, -1, +1), + new(+1, +1, -1), + new(+1, +1, +1), + }; + + // Each item represents 3 lines, with x being the start index and yzw the end indices. + static readonly int4[] k_CubeLineIndices = + { + // (-1, -1, -1) -> {(+1, -1, -1), (-1, +1, -1), (-1, -1, +1)} + new(0, 4, 2, 1), + + // (-1, +1, +1) -> {(+1, +1, +1), (-1, -1, +1), (-1, +1, -1)} + new(3, 7, 1, 2), + + // (+1, -1, +1) -> {(-1, -1, +1), (+1, +1, +1), (+1, -1, -1)} + new(5, 1, 7, 4), + + // (+1, +1, -1) -> {(-1, +1, -1), (+1, -1, -1), (+1, +1, +1)} + new(6, 2, 4, 7), + }; + + void TileReflectionProbe(int index) + { + // The algorithm used here works by clipping all the lines of the cube against the near-plane, and then + // projects the resulting points to the view plane. These points are then used to construct a 2D convex + // hull, which we can iterate linearly to get the lines on screen making up the cube. + + var reflectionProbe = reflectionProbes[index - lights.Length]; + if (!HasNonZeroVolume(reflectionProbe)) + return; + + var centerWS = (float3)reflectionProbe.bounds.center; + var extentsWS = (float3)reflectionProbe.bounds.extents; + quaternion rotation; + if (reflectionProbeRotation) + rotation = (quaternion)reflectionProbe.localToWorldMatrix.rotation; + else + rotation = quaternion.identity; + + // The vertices of the cube in view space. + Span points = stackalloc float3[k_CubePointCount]; + // 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. + Span clippedPoints = stackalloc float2[k_MaxClippedPointCount]; + var clippedPointsCount = 0; + var leftmostIndex = 0; + for (var i = 0; i < k_CubePoints.Length; i++) + { + var rotatedPointsWS = centerWS + math.rotate(rotation, extentsWS * k_CubePoints[i]); + var point = math.mul(worldToViews[m_ViewIndex], math.float4(rotatedPointsWS, 1)).xyz; + point.z *= -1; + points[i] = point; + if (IsInDepthRange(point)) + { + var clippedPoint = isOrthographic ? point.xy : point.xy/point.z; + var clippedIndex = clippedPointsCount++; + clippedPoints[clippedIndex] = clippedPoint; + if (clippedPoint.x < clippedPoints[leftmostIndex].x) leftmostIndex = clippedIndex; + } + } + + // 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]; + var p0 = points[indices.x]; + for (var j = 0; j < 3; j++) + { + var p1 = points[indices[j+1]]; + for (var k = 0; k < 2; k++) + { + 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++; + clippedPoints[clippedIndex] = clippedPoint; + if (clippedPoint.x < clippedPoints[leftmostIndex].x) leftmostIndex = clippedIndex; + } + } + } + + // Construct the convex hull. It is formed by the line loop consisting of the points in the array. + Span hullPoints = stackalloc float2[k_MaxClippedPointCount]; + var hullPointsCount = 0; + + if (clippedPointsCount > 0) + { + // Start with the leftmost point, as that is guaranteed to be on the hull. + var hullPointIndex = leftmostIndex; + + // Find the remaining hull points until we end up back at the leftmost point. + do + { + var hullPoint = clippedPoints[hullPointIndex]; + ExpandY(math.float3(hullPoint, 1)); + hullPoints[hullPointsCount++] = hullPoint; + + // Find the endpoint resulting in the leftmost turning line. This line will be a part of the hull. + var endpointIndex = 0; + var endpointLine = clippedPoints[endpointIndex] - hullPoint; + for (var i = 0; i < clippedPointsCount; i++) + { + var candidateLine = clippedPoints[i] - hullPoint; + var det = math.determinant(math.float2x2(endpointLine, candidateLine)); + + // Check if point i lies on the left side of the line to the current endpoint, or if it lies + // collinear to the current endpoint but farther away. + if (endpointIndex == hullPointIndex || det > 0 || (det == 0.0f && math.lengthsq(candidateLine) > math.lengthsq(endpointLine))) + { + endpointIndex = i; + endpointLine = candidateLine; + } + } + + hullPointIndex = endpointIndex; + } while (hullPointIndex != leftmostIndex && hullPointsCount < clippedPointsCount); + + m_TileYRange.Clamp(0, (short)(tileCount.y - 1)); + + // Calculate tile plane ranges for sphere. + 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); + + for (var i = 0; i < hullPointsCount; i++) + { + var hp0 = hullPoints[i]; + var hp1 = hullPoints[(i + 1) % hullPointsCount]; + + // planeY = hp0 + t * (hp1 - hp0) => planeY - hp0 = t * (hp1 - hp0) => (planeY - hp0) / (hp1 - hp0) = t + // A horizontal edge's endpoints are also endpoints of the neighboring edges, which cover them. + if (hp1.y == hp0.y) continue; + var t = (planeY - hp0.y) / (hp1.y - hp0.y); + if (t < 0 || t > 1) continue; + var x = math.lerp(hp0.x, hp1.x, t); + + var p = math.float3(x, planeY, 1); + var pTS = isOrthographic ? ViewToTileSpaceOrthographic(p) : ViewToTileSpace(p); + ExpandTileX(ref planeRange, pTS.x); + } + + MergeTileRangeRows(planeIndex, planeRange); + } + + tileRanges[m_Offset] = m_TileYRange; + } + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.ReflectionProbe.cs.meta b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.ReflectionProbe.cs.meta new file mode 100644 index 00000000000..078a3b545ed --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.ReflectionProbe.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 9c3465db6b22241bcbd57517352a899c \ No newline at end of file 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 86ded9b3cfe..6277b52917e 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.cs @@ -5,8 +5,10 @@ namespace UnityEngine.Rendering.Universal { - [BurstCompile(FloatMode = FloatMode.Default, DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)] - struct TilingJob : IJobFor + // Projects each light/probe into per-row tile ranges; TileRangeExpansionJob turns them into tile masks. + // tileRanges per entity: [m_Offset] = tile row (Y) range, [m_Offset + 1 + row] = column (X) range. + [BurstCompile(FloatMode = FloatMode.Fast, DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)] + partial struct TilingJob : IJobFor { [ReadOnly] public NativeArray lights; @@ -32,17 +34,20 @@ struct TilingJob : IJobFor public Fixed2 viewToViewportScaleBiases; public int2 tileCount; public float near; + public float far; public bool isOrthographic; InclusiveRange m_TileYRange; int m_Offset; int m_ViewIndex; + float4 m_ViewToViewportScaleBias; float2 m_CenterOffset; public void Execute(int jobIndex) { var index = jobIndex % itemsPerTile; m_ViewIndex = jobIndex / itemsPerTile; + m_ViewToViewportScaleBias = viewToViewportScaleBiases[m_ViewIndex]; m_Offset = jobIndex * rangesPerItem; m_TileYRange = new InclusiveRange(short.MaxValue, short.MinValue); @@ -64,490 +69,12 @@ public void Execute(int jobIndex) } } - void TileLight(int lightIndex) - { - var light = lights[lightIndex]; - if (light.lightType != LightType.Point && light.lightType != LightType.Spot) - { - return; - } - - 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); - var lightDirectionVS = math.normalize(math.mul(worldToViews[m_ViewIndex], math.float4(lightToWorld.c2.xyz, 0)).xyz); - lightDirectionVS.z *= -1; - - var halfAngle = math.radians(light.spotAngle * 0.5f); - var range = light.range; - 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); - - if (light.lightType == LightType.Spot) - { - // Cone base - var baseRadius = math.sqrt(range * range - coneHeight * coneHeight); - var baseCenter = lightPositionVS + lightDirectionVS * coneHeight; - - // Project cone base (a circle) into the YZ plane, find the horizon points, and re-construct view space position of found points. - // When projecting a circle to a plane, it becomes an ellipse where the major axis is parallel to the line - // of intersection of the projection plane and the circle plane. We can get this by taking the cross product - // of the two plane normals, as the line of intersection will have to be a vector in both planes, and thus - // orthogonal to both normals. - // If the two plane normals are parallel, the cross product would return 0. In that case, the circle will - // project to a line segment, so we pick a vector in the plane pointing in the direction we're interested - // in finding horizon points in. - var baseUY = math.abs(math.abs(lightDirectionVS.x) - 1) < 1e-6f ? math.float3(0, 1, 0) : math.normalize(math.cross(lightDirectionVS, math.float3(1, 0, 0))); - var baseVY = math.cross(lightDirectionVS, baseUY); - 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); - - // 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. - var baseUX = math.abs(math.abs(lightDirectionVS.y) - 1) < 1e-6f ? math.float3(1, 0, 0) : math.normalize(math.cross(lightDirectionVS, math.float3(0, 1, 0))); - var baseVX = math.cross(lightDirectionVS, baseUX); - 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); - - // Handle base circle clipping by intersecting it with the near-plane if needed. - if (GetCircleClipPoints(baseCenter, lightDirectionVS, baseRadius, near, out var baseClip0, out var baseClip1)) - { - ExpandY(baseClip0); - ExpandY(baseClip1); - } - - bool ConicPointIsValid(float3 p) => - math.dot(math.normalize(p - lightPositionVS), lightDirectionVS) >= 0 && - math.dot(p - lightPositionVS, lightDirectionVS) <= coneHeight; - - // Calculate Z bounds of cone and check if it's overlapping with the near plane. - // 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 coneV = math.cross(lightDirectionVS, coneU); - - if (coneIsClipping) - { - 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 (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); - 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); - - { - 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); - } - - m_TileYRange.Clamp(0, (short)(tileCount.y - 1)); - - // Calculate tile plane ranges for cone. - for (var planeIndex = m_TileYRange.start; planeIndex <= m_TileYRange.end + 1; planeIndex++) - { - var planeRange = InclusiveRange.empty; - - // Y-position on the view plane (Z=1) - var planeY = math.lerp(viewPlaneBottoms[m_ViewIndex], viewPlaneTops[m_ViewIndex], planeIndex * tileScaleInv.y); - - var planeNormal = math.float3(0, 1, -planeY); - - // 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) 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) ExpandTileX(ref planeRange, ViewToTileSpace(l2x).x); - - if (IntersectCircleYPlane(planeY, baseCenter, lightDirectionVS, baseUY, baseVY, baseRadius, out var circleTile0, out var circleTile1)) - { - if (circleTile0.z >= near) ExpandTileX(ref planeRange, ViewToTileSpace(circleTile0).x); - if (circleTile1.z >= near) 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)) 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; 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)) ExpandTileX(ref planeRange, ViewToTileSpace(sphereTile0).x); - if (SpherePointIsValid(sphereTile1)) ExpandTileX(ref planeRange, ViewToTileSpace(sphereTile1).x); - - MergeTileRangeRows(planeIndex, planeRange); - } - - tileRanges[m_Offset] = m_TileYRange; - } - - void TileLightOrthographic(int lightIndex) - { - var light = lights[lightIndex]; - var lightToWorld = (float4x4)light.localToWorldMatrix; - var lightPosVS = math.mul(worldToViews[m_ViewIndex], math.float4(lightToWorld.c3.xyz, 1)).xyz; - lightPosVS.z *= -1; - ExpandOrthographic(lightPosVS); - var lightDirVS = math.mul(worldToViews[m_ViewIndex], math.float4(lightToWorld.c2.xyz, 0)).xyz; - lightDirVS.z *= -1; - lightDirVS = math.normalize(lightDirVS); - - var halfAngle = math.radians(light.spotAngle * 0.5f); - var range = light.range; - var rangeSq = square(range); - var cosHalfAngle = math.cos(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); - - 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 circleBoundX0 = circleCenter - circleRight * circleRadius; - var circleBoundX1 = circleCenter + circleRight * circleRadius; - ExpandOrthographic(circleBoundY0); - ExpandOrthographic(circleBoundY1); - ExpandOrthographic(circleBoundX0); - ExpandOrthographic(circleBoundX1); - } - - m_TileYRange.Clamp(0, (short)(tileCount.y - 1)); - - // 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); - } - - // Tile plane ranges - 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) - { - // Circle - if (planeY >= circleBoundY0.y && planeY <= circleBoundY1.y) - { - 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); - } - - // 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); } - } - - MergeTileRangeRows(planeIndex, planeRange); - } - - tileRanges[m_Offset] = m_TileYRange; - } - - static readonly float3[] k_CubePoints = - { - new(-1, -1, -1), - new(-1, -1, +1), - new(-1, +1, -1), - new(-1, +1, +1), - new(+1, -1, -1), - new(+1, -1, +1), - new(+1, +1, -1), - new(+1, +1, +1), - }; - - // Each item represents 3 lines, with x being the start index and yzw the end indices. - static readonly int4[] k_CubeLineIndices = - { - // (-1, -1, -1) -> {(+1, -1, -1), (-1, +1, -1), (-1, -1, +1)} - new(0, 4, 2, 1), - - // (-1, +1, +1) -> {(+1, +1, +1), (-1, -1, +1), (-1, +1, -1)} - new(3, 7, 1, 2), - - // (+1, -1, +1) -> {(-1, -1, +1), (+1, +1, +1), (+1, -1, -1)} - new(5, 1, 7, 4), - - // (+1, +1, -1) -> {(-1, +1, -1), (+1, -1, -1), (+1, +1, +1)} - new(6, 2, 4, 7), - }; - - void TileReflectionProbe(int index) - { - // The algorithm used here works by clipping all the lines of the cube against the near-plane, and then - // projects the resulting points to the view plane. These points are then used to construct a 2D convex - // hull, which we can iterate linearly to get the lines on screen making up the cube. - - var reflectionProbe = reflectionProbes[index - lights.Length]; - var centerWS = (float3)reflectionProbe.bounds.center; - var extentsWS = (float3)reflectionProbe.bounds.extents; - quaternion rotation; - if (reflectionProbeRotation) - rotation = (quaternion)reflectionProbe.localToWorldMatrix.rotation; - else - rotation = quaternion.identity; - - // 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); - var clippedPointsCount = 0; - var leftmostIndex = 0; - for (var i = 0; i < k_CubePoints.Length; i++) - { - var rotatedPointsWS = centerWS + math.rotate(rotation, extentsWS * k_CubePoints[i]); - var point = math.mul(worldToViews[m_ViewIndex], math.float4(rotatedPointsWS, 1)).xyz; - point.z *= -1; - points[i] = point; - if (point.z >= near) - { - var clippedPoint = isOrthographic ? point.xy : point.xy/point.z; - var clippedIndex = clippedPointsCount++; - clippedPoints[clippedIndex] = clippedPoint; - if (clippedPoint.x < clippedPoints[leftmostIndex].x) leftmostIndex = clippedIndex; - } - } - - // 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. - for (var i = 0; i < k_CubeLineIndices.Length; i++) - { - var indices = k_CubeLineIndices[i]; - var p0 = points[indices.x]; - 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) - { - var d = (near - 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++; - clippedPoints[clippedIndex] = clippedPoint; - if (clippedPoint.x < clippedPoints[leftmostIndex].x) leftmostIndex = clippedIndex; - } - } - } - - // Construct the convex hull. It is formed by the line loop consisting of the points in the array. - var hullPoints = new NativeArray(clippedPointsCount, Allocator.Temp); - var hullPointsCount = 0; - - if (clippedPointsCount > 0) - { - // Start with the leftmost point, as that is guaranteed to be on the hull. - var hullPointIndex = leftmostIndex; - - // Find the remaining hull points until we end up back at the leftmost point. - do - { - var hullPoint = clippedPoints[hullPointIndex]; - ExpandY(math.float3(hullPoint, 1)); - hullPoints[hullPointsCount++] = hullPoint; - - // Find the endpoint resulting in the leftmost turning line. This line will be a part of the hull. - var endpointIndex = 0; - var endpointLine = clippedPoints[endpointIndex] - hullPoint; - for (var i = 0; i < clippedPointsCount; i++) - { - var candidateLine = clippedPoints[i] - hullPoint; - var det = math.determinant(math.float2x2(endpointLine, candidateLine)); - - // Check if point i lies on the left side of the line to the current endpoint, or if it lies - // collinear to the current endpoint but farther away. - if (endpointIndex == hullPointIndex || det > 0 || (det == 0.0f && math.lengthsq(candidateLine) > math.lengthsq(endpointLine))) - { - endpointIndex = i; - endpointLine = candidateLine; - } - } - - hullPointIndex = endpointIndex; - } while (hullPointIndex != leftmostIndex && hullPointsCount < clippedPointsCount); - - m_TileYRange.Clamp(0, (short)(tileCount.y - 1)); - - // Calculate tile plane ranges for sphere. - 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); - - for (var i = 0; i < hullPointsCount; i++) - { - var hp0 = hullPoints[i]; - var hp1 = hullPoints[(i + 1) % hullPointsCount]; - - // planeY = hp0 + t * (hp1 - hp0) => planeY - hp0 = t * (hp1 - hp0) => (planeY - hp0) / (hp1 - hp0) = t - var t = (planeY - hp0.y) / (hp1.y - hp0.y); - if (t < 0 || t > 1) continue; - var x = math.lerp(hp0.x, hp1.x, t); - - var p = math.float3(x, planeY, 1); - var pTS = isOrthographic ? ViewToTileSpaceOrthographic(p) : ViewToTileSpace(p); - ExpandTileX(ref planeRange, pTS.x); - } - - MergeTileRangeRows(planeIndex, planeRange); - } - - tileRanges[m_Offset] = m_TileYRange; - } - - hullPoints.Dispose(); - clippedPoints.Dispose(); - points.Dispose(); - } - /// /// Project onto Z=1, scale and offset into [0, tileCount] /// float2 ViewToTileSpace(float3 positionVS) { - return (positionVS.xy / positionVS.z * viewToViewportScaleBiases[m_ViewIndex].xy + viewToViewportScaleBiases[m_ViewIndex].zw) * tileScale; + return (positionVS.xy / positionVS.z * m_ViewToViewportScaleBias.xy + m_ViewToViewportScaleBias.zw) * tileScale; } /// @@ -555,11 +82,19 @@ float2 ViewToTileSpace(float3 positionVS) /// float2 ViewToTileSpaceOrthographic(float3 positionVS) { - return (positionVS.xy * viewToViewportScaleBiases[m_ViewIndex].xy + viewToViewportScaleBiases[m_ViewIndex].zw) * tileScale; + return (positionVS.xy * m_ViewToViewportScaleBias.xy + m_ViewToViewportScaleBias.zw) * tileScale; } void ExpandY(float3 positionVS) => ExpandTile(ViewToTileSpace(positionVS)); + bool IsInDepthRange(float3 positionVS) => IsDepthInRange(positionVS.z); + + bool IsDepthInRange(float depth) => depth >= near && depth <= far; + + // 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 ExpandOrthographic(float3 positionVS) => ExpandTile(ViewToTileSpaceOrthographic(positionVS)); void ExpandRangeOrthographic(ref InclusiveRange range, float xVS) => ExpandTileX(ref range, ViewToTileSpaceOrthographic(xVS).x); @@ -569,8 +104,6 @@ float2 ViewToTileSpaceOrthographic(float3 positionVS) /// 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)); @@ -587,7 +120,6 @@ void ExpandTile(float2 positionTS) // 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)); } @@ -608,351 +140,14 @@ void MergeTileRangeRows(int planeIndex, InclusiveRange planeRange) 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) - { - 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; - - // Center of circle horizon - var c = direction * (l * h / radius); - - p0 = math.float2(float.MinValue, 1f); - p1 = math.float2(float.MaxValue, 1f); - - // Handle clipping - if (center.y - radius < near) - { - p0 = math.float2(center.x + clipRadius, near); - p1 = math.float2(center.x - clipRadius, near); - } - - // Compare by x/z, not x: clip and horizon points lie at different depths. - var c0 = c + math.float2(-direction.y, direction.x) * h; - if (square(d) >= square(radius) && c0.y >= near) - { - if (c0.x / c0.y > p0.x / p0.y) { p0 = c0; } - if (c0.x / c0.y < p1.x / p1.y) { p1 = c0; } - } - - var c1 = c + math.float2(direction.y, -direction.x) * h; - if (square(d) >= square(radius) && c1.y >= near) - { - if (c1.x / c1.y > p0.x / p0.y) { p0 = c1; } - if (c1.x / c1.y < p1.x / p1.y) { p1 = c1; } - } - } - - static void GetSphereYPlaneHorizon(float3 center, float sphereRadius, float near, float clipRadius, float y, out float3 left, out float3 right) - { - // 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. - 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. - 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; - - var rightCandidate = rightOnPlane.x * planeU + rightOnPlane.y * planeV; - if (rightCandidate.z >= near) right = rightCandidate; - } - } - - /// - /// Finds the two points of intersection of a 3D circle and the near plane. - /// - static bool GetCircleClipPoints(float3 circleCenter, float3 circleNormal, float circleRadius, float near, out float3 p0, out float3 p1) - { - // The intersection of two planes is a line where the direction is the cross product of the two plane normals. - // In this case, it is the plane containing the circle, and the near plane. - var lineDirection = math.normalize(math.cross(circleNormal, math.float3(0, 0, 1))); - - // Find a direction on the circle plane towards the nearest point on the intersection line. - // It has to be perpendicular to the circle normal to be in the circle plane. The direction to the closest - // point on a line is perpendicular to the line direction. Thus this is given by the cross product of the - // line direction and the circle normal, as this gives us a vector that is perpendicular to both of those. - var nearestDirection = math.cross(lineDirection, circleNormal); - - // Distance from circle center to the intersection line along `nearestDirection`. - // This is done using a ray-plane intersection, where the plane is the near plane. - // ({0, 0, near} - circleCenter) . {0, 0, 1} / (nearestDirection . {0, 0, 1}) - var distance = (near - circleCenter.z) / nearestDirection.z; - - // The point on the line nearest to the circle center when traveling only in the circle plane. - var nearestPoint = circleCenter + nearestDirection * distance; + // Bound on view-space distances and light ranges, so powers of them stay finite under FloatMode.Fast; float precision + // at this distance is already far coarser than anything a camera renders. + internal const float k_MaxDistance = 1e9f; - // Any line through a circle makes a chord where the endpoints are the intersections with the circle. - // The half length of the circle chord can be found by constructing a right triangle from three points: - // (a) The circle center. - // (b) The nearest point. - // (c) A point that is on circle and the intersection line. - // The hypotenuse is formed by (a) and (c) and will have length `circleRadius` as it is on the circle. - // The known side if formed by (a) and (b), which we have already calculated the distance of in `distance`. - // The unknown side formed by (b) and (c) is then found using Pythagoras. - var chordHalfLength = math.sqrt(square(circleRadius) - square(distance)); - p0 = nearestPoint + lineDirection * chordHalfLength; - p1 = nearestPoint - lineDirection * chordHalfLength; + // Items without a volume affect no pixel and are skipped. Only point and spot lights are clustered. + internal static bool HasNonZeroVolume(in VisibleLight light) => + light.range > 0f && (light.lightType == LightType.Point || (light.lightType == LightType.Spot && light.spotAngle > 0f)); - 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. - /// - /// The center of the circle projected onto the plane. - /// The radius of the circle. - /// The major axis of the ellipse formed by the projection of the circle. - /// 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) - { - // 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. - var vl = math.length(V); - if (vl < 1e-6f) - { - uv1 = math.float2(radius, 0); - uv2 = math.float2(-radius, 0); - } - 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; - - // 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); - } - } - - static bool IntersectCircleYPlane( - float y, float3 circleCenter, float3 circleNormal, 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. - var x1 = lineCenter + l * lineDirection; - var x2 = lineCenter - l * lineDirection; - p1 = circleCenter + x1.x * circleU + x1.y * circleV; - p2 = circleCenter + x2.x * circleU + x2.y * circleV; - - 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) - { - l1 = l2 = 0; - - var toCamera = -vertex; - if (math.dot(math.normalize(toCamera), axis) >= cosHalfAngle) - { - return; - } - - // 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; - } - - 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; - } - - 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); - } - - // 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) - { - 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); - } - - static float2 FindNearConicYTheta(float near, float3 o, float3 d, float r, float3 u, float3 v, float y) - { - 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); - } + internal static bool HasNonZeroVolume(in VisibleReflectionProbe probe) => math.all((float3)probe.bounds.extents > 0f); } } 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..a94f42088d3 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/ZBinningJob.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/ZBinningJob.cs @@ -6,6 +6,29 @@ namespace UnityEngine.Rendering.Universal { + struct ZBinMapping + { + public float scale; + public float offset; + public int binCount; + public bool isOrthographic; + + // Widens ranges slightly so CPU/GPU log2 rounding at a bin edge cannot drop the edge bin. + const float k_EdgeBias = 1e-3f; + + // Clamped to [-1, binCount] so depths outside the bins yield empty bin spans. + public int ToBin(float z, float bias) + { + var bin = (isOrthographic ? z : math.log2(z)) * scale + offset + bias; + return (int)math.clamp(bin, -1f, binCount); + } + + // An empty or non-finite depth range, e.g. an item entirely closer than the near plane or a light with a broken transform, + // gives an empty bin span without evaluating log2. + public int2 ToBins(float2 minMaxZ) => + !math.all(math.isfinite(minMaxZ)) || minMaxZ.x > minMaxZ.y ? math.int2(0, -1) : math.int2(ToBin(minMaxZ.x, -k_EdgeBias), ToBin(minMaxZ.y, k_EdgeBias)); + } + [BurstCompile(FloatMode = FloatMode.Fast, DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)] struct ZBinningJob : IJobFor { @@ -14,15 +37,14 @@ struct ZBinningJob : IJobFor public const int headerLength = 2; + // A header whose min index is above its max index, which the shader iterates as empty. + public const uint emptyHeader = ushort.MaxValue; + [NativeDisableParallelForRestriction] public NativeArray bins; [ReadOnly] - public NativeArray minMaxZs; - - public float zBinScale; - - public float zBinOffset; + public NativeArray minMaxZBins; public int binCount; @@ -36,8 +58,6 @@ struct ZBinningJob : IJobFor public int viewCount; - public bool isOrthographic; - static uint EncodeHeader(uint min, uint max) { return (min & 0xFFFF) | ((max & 0xFFFF) << 16); @@ -58,14 +78,16 @@ public void Execute(int jobIndex) var binOffset = viewIndex * binCount; - var emptyHeader = EncodeHeader(ushort.MaxValue, ushort.MinValue); for (var binIndex = binStart; binIndex <= binEnd; binIndex++) { - bins[(binOffset + binIndex) * (headerLength + wordsPerTile) + 0] = emptyHeader; - bins[(binOffset + binIndex) * (headerLength + wordsPerTile) + 1] = emptyHeader; + var baseIndex = (binOffset + binIndex) * (headerLength + wordsPerTile); + bins[baseIndex + 0] = emptyHeader; + bins[baseIndex + 1] = emptyHeader; + for (var wordIndex = 0; wordIndex < wordsPerTile; wordIndex++) + bins[baseIndex + headerLength + wordIndex] = 0; } - // Regarding itemOffset: minMaxZs contains [lights view 0, lights view 1, probes view 0, probes view 1] when + // Regarding itemOffset: minMaxZBins contains [lights view 0, lights view 1, probes view 0, probes view 1] when // using XR single pass instanced, and otherwise [lights, probes]. So we figure out what the offset is based // on the view count and index. @@ -80,9 +102,9 @@ void FillZBins(int binStart, int binEnd, int itemStart, int itemEnd, int headerI { for (var index = itemStart; index < itemEnd; index++) { - var minMax = minMaxZs[itemOffset + index]; - 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); + var minMax = minMaxZBins[itemOffset + index]; + var minBin = math.max(minMax.x, binStart); + var maxBin = math.min(minMax.y, binEnd); var wordIndex = index / 32; var bitMask = 1u << (index % 32); diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalAdditionalCameraData.cs b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalAdditionalCameraData.cs index 11c505a5abb..17d89864c93 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalAdditionalCameraData.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalAdditionalCameraData.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using Unity.Scripting.LifecycleManagement; using UnityEditor; using UnityEngine.Serialization; using UnityEngine.Assertions; @@ -387,7 +386,6 @@ internal static void GetVolumeLayerMaskAndTrigger(this Camera camera, UniversalA static class CameraTypeUtility { - [NoAutoStaticsCleanup] // Reflection data cache, no need to clear. static readonly string[] s_CameraTypeNames = Enum.GetNames(typeof(CameraRenderType)); public static string GetName(this CameraRenderType type) diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalAdditionalLightData.cs b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalAdditionalLightData.cs index cd50ec00426..3181e35455f 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalAdditionalLightData.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalAdditionalLightData.cs @@ -25,6 +25,17 @@ public static UniversalAdditionalLightData GetUniversalAdditionalLightData(this } } + /// + /// The PCSS sample count preset of a light. Higher presets reduce noise at a GPU cost. + /// + internal enum PCSSSampleQuality + { + Low, + Medium, + High, + Custom, + } + /// /// Class containing various additional light data used by URP. /// @@ -169,6 +180,163 @@ public SoftShadowQuality softShadowQuality } [SerializeField] SoftShadowQuality m_SoftShadowQuality = SoftShadowQuality.UsePipelineSettings; + // PCSS defaults, also used for a light without this component + internal const float k_DefaultSoftShadowAngularDiameter = 0.5f; + internal const float k_DefaultSoftShadowScale = 1.0f; + internal const int k_DefaultSoftShadowBlockerSampleCount = 24; + internal const int k_DefaultSoftShadowFilterSampleCount = 16; + internal const float k_DefaultSoftShadowMaxPenumbraSize = 0.56f; + internal const float k_DefaultSoftShadowMaxSamplingDistance = 0.5f; + internal const float k_DefaultSoftShadowMinFilterSizeTexels = 1.5f; + internal const float k_DefaultSoftShadowMinFilterMaxAngularDiameter = 10.0f; + internal const float k_DefaultSoftShadowBlockerSearchAngularDiameter = 12.0f; + internal const float k_DefaultSoftShadowBlockerSamplingClumpExponent = 2.0f; + internal const float k_DefaultSoftShadowMinFilterSize = 0.1f; + + // PCSS sample counts of the Low and High presets. Medium uses the defaults above. + internal const int k_LowSoftShadowBlockerSampleCount = 12; + internal const int k_LowSoftShadowFilterSampleCount = 8; + internal const int k_HighSoftShadowBlockerSampleCount = 32; + internal const int k_HighSoftShadowFilterSampleCount = 24; + + /// + /// The angular diameter in degrees of the main directional light, which sets how wide its PCSS penumbra grows. + /// Spot and point lights use instead. + /// + [Tooltip("Controls the angular diameter of the light in degrees, which sets how wide the PCSS penumbra grows with distance. The sun is roughly 0.5 degrees.")] + internal float softShadowAngularDiameter + { + get => m_SoftShadowAngularDiameter; + set => m_SoftShadowAngularDiameter = Mathf.Max(value, 0.0f); + } + [SerializeField, Min(0f)] float m_SoftShadowAngularDiameter = k_DefaultSoftShadowAngularDiameter; + + /// + /// The multiplier applied to the PCSS penumbra size of this light, on top of its angular diameter or shape radius. + /// + [Tooltip("Controls the multiplier applied to the PCSS penumbra size, so shadows can be softened without changing the size of the light.")] + internal float softShadowScale + { + get => m_SoftShadowScale; + set => m_SoftShadowScale = Mathf.Max(value, 0.0f); + } + [SerializeField, Min(0f)] float m_SoftShadowScale = k_DefaultSoftShadowScale; + + /// + /// The PCSS sample count preset of this light. + /// The presets use the default tuning values, and uses the sample counts and tuning values set on this light. + /// + [Tooltip("Controls how many shadow map samples PCSS takes per pixel. Higher quality reduces noise but has lower performance. Lower settings rely on temporal anti-aliasing to hide noise. Select Custom to set the sample counts and tuning values yourself.")] + internal PCSSSampleQuality softShadowPCSSSampleQuality + { + get => m_SoftShadowPCSSSampleQuality; + set => m_SoftShadowPCSSSampleQuality = value; + } + [SerializeField] PCSSSampleQuality m_SoftShadowPCSSSampleQuality = PCSSSampleQuality.Medium; + + /// + /// The number of samples the PCSS blocker search takes, clamped to 1 to 64. + /// + [Tooltip("Controls the number of samples the PCSS blocker search takes. Higher values reduce noise but have lower performance.")] + internal int softShadowBlockerSampleCount + { + get => m_SoftShadowBlockerSampleCount; + set => m_SoftShadowBlockerSampleCount = Mathf.Clamp(value, 1, ShadowUtils.k_PCSSMaxSampleCount); + } + [SerializeField, Range(1, ShadowUtils.k_PCSSMaxSampleCount)] int m_SoftShadowBlockerSampleCount = k_DefaultSoftShadowBlockerSampleCount; + + /// + /// The number of samples the PCSS filtering phase takes, clamped to 1 to 64. + /// + [Tooltip("Controls the number of samples the PCSS filtering phase takes. Higher values reduce noise but have lower performance.")] + internal int softShadowFilterSampleCount + { + get => m_SoftShadowFilterSampleCount; + set => m_SoftShadowFilterSampleCount = Mathf.Clamp(value, 1, ShadowUtils.k_PCSSMaxSampleCount); + } + [SerializeField, Range(1, ShadowUtils.k_PCSSMaxSampleCount)] int m_SoftShadowFilterSampleCount = k_DefaultSoftShadowFilterSampleCount; + + /// + /// The world-space upper bound on the PCSS penumbra size of the main directional light. + /// + [Tooltip("Controls the world-space upper bound on the PCSS penumbra size. This acts as a safety clamp.")] + internal float softShadowMaxPenumbraSize + { + get => m_SoftShadowMaxPenumbraSize; + set => m_SoftShadowMaxPenumbraSize = Mathf.Max(value, 0.0f); + } + [SerializeField, Min(0f)] float m_SoftShadowMaxPenumbraSize = k_DefaultSoftShadowMaxPenumbraSize; + + /// + /// The world-space distance, at most, that the PCSS filter of the main directional light moves the depth each sample compares against towards the light. + /// The sample positions on the shadow map do not change. + /// + [Tooltip("Controls the world-space distance, at most, that PCSS moves the depth each sample compares against towards the light. This does not move the samples across the shadow map. Useful for reducing light bleeding.")] + internal float softShadowMaxSamplingDistance + { + get => m_SoftShadowMaxSamplingDistance; + set => m_SoftShadowMaxSamplingDistance = Mathf.Max(value, 0.0f); + } + [SerializeField, Min(0f)] float m_SoftShadowMaxSamplingDistance = k_DefaultSoftShadowMaxSamplingDistance; + + /// + /// The smallest PCSS filter radius of the main directional light, in shadow map texels. + /// + [Tooltip("Controls the smallest PCSS filter radius in shadow map texels. Useful for hiding flickering at shadow contact points.")] + internal float softShadowMinFilterSizeTexels + { + get => m_SoftShadowMinFilterSizeTexels; + set => m_SoftShadowMinFilterSizeTexels = Mathf.Max(value, 0.0f); + } + [SerializeField, Min(0f)] float m_SoftShadowMinFilterSizeTexels = k_DefaultSoftShadowMinFilterSizeTexels; + + /// + /// The angular diameter in degrees the minimum PCSS filter cone of the main directional light widens to. + /// Values below , or below the scaled angular diameter of the light, are raised to the larger of the two. + /// + [Tooltip("Controls the angle in degrees the minimum PCSS filter cone widens to. Values below Blocker Search Angle, or below Angular Diameter multiplied by Softness Scale, are raised to the larger of the two.")] + internal float softShadowMinFilterMaxAngularDiameter + { + get => m_SoftShadowMinFilterMaxAngularDiameter; + set => m_SoftShadowMinFilterMaxAngularDiameter = Mathf.Max(value, 0.0f); + } + [SerializeField, Min(0f)] float m_SoftShadowMinFilterMaxAngularDiameter = k_DefaultSoftShadowMinFilterMaxAngularDiameter; + + /// + /// The angular diameter in degrees of the PCSS blocker search cone of the main directional light. + /// Values below the scaled angular diameter of the light are raised to it. + /// + [Tooltip("Controls the angle in degrees of the PCSS blocker search cone. Wider angles reduce light bleeding. Values below Angular Diameter multiplied by Softness Scale are raised to it.")] + internal float softShadowBlockerSearchAngularDiameter + { + get => m_SoftShadowBlockerSearchAngularDiameter; + set => m_SoftShadowBlockerSearchAngularDiameter = Mathf.Max(value, 0.0f); + } + [SerializeField, Min(0f)] float m_SoftShadowBlockerSearchAngularDiameter = k_DefaultSoftShadowBlockerSearchAngularDiameter; + + /// + /// How strongly the PCSS blocker search samples of the main directional light clump towards the center of the search cone. + /// + [Tooltip("Controls how strongly the PCSS blocker search samples clump towards the center of the search cone.")] + internal float softShadowBlockerSamplingClumpExponent + { + get => m_SoftShadowBlockerSamplingClumpExponent; + set => m_SoftShadowBlockerSamplingClumpExponent = Mathf.Max(value, 0.0f); + } + [SerializeField, Min(0f)] float m_SoftShadowBlockerSamplingClumpExponent = k_DefaultSoftShadowBlockerSamplingClumpExponent; + + /// + /// The smallest PCSS filter radius of a spot or point light. + /// The range 0 to 1 maps to 0 to about 4 shadow map texels. + /// + [Tooltip("Controls the smallest PCSS filter radius. The range 0 to 1 maps to 0 to about 4 shadow map texels. Useful for hiding flickering at shadow contact points.")] + internal float softShadowMinFilterSize + { + get => m_SoftShadowMinFilterSize; + set => m_SoftShadowMinFilterSize = Mathf.Clamp01(value); + } + [SerializeField, Range(0f, 1f)] float m_SoftShadowMinFilterSize = k_DefaultSoftShadowMinFilterSize; + #if VOLUMETRIC_FOG /// /// When enabled, this light interacts with volumetric fog. @@ -238,7 +406,7 @@ internal void SyncLightAndShadowLayers() if (light) light.renderingLayerMask = m_CustomShadowLayers ? m_ShadowRenderingLayersMask : m_RenderingLayersMask; } - + enum Version { Initial = 0, diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipeline.cs b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipeline.cs index 1ba62a60411..d069df45e90 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipeline.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipeline.cs @@ -290,13 +290,39 @@ internal static bool UseDynamicBranchFogKeyword() private UniversalRenderPipelineGlobalSettings m_GlobalSettings; - // Set by any camera that needs the real back buffer multisampled; one camera keeps it on for the - // whole frame. Reset and consumed only in Render() so it can never be read stale. - private bool m_FrameNeedsRealBackbufferMSAA; + struct DisplayMSAARequest + { + // Set by any camera that needs the surface multisampled; one camera keeps it on for the + // whole frame. Reset and consumed only in Render() so it can never be read stale. + bool m_NeededThisFrame; + + // Hysteresis on dropping MSAA to 1: counts consecutive frames not needing MSAA so a per-frame + // flip-flop of the decision doesn't keep reallocating the surface. + int m_FramesSinceNeeded; - // Hysteresis on dropping back buffer MSAA to 1: counts consecutive frames not needing back buffer - // MSAA so a per-frame flip-flop of the decision doesn't keep reallocating the back buffer. - private int m_FramesSinceRealBackbufferMSAANeeded; + public void BeginFrame() => m_NeededThisFrame = false; + public void Require() => m_NeededThisFrame = true; + public void ResetDowngradeDelay() => m_FramesSinceNeeded = 0; + + // Returns the sample count to request. Upgrades apply immediately; downgrades wait out the + // hysteresis, since extra MSAA frames cost only bandwidth, never correctness. + public int Resolve(int assetSamples, int currentSamples) + { + if (m_NeededThisFrame) + { + m_FramesSinceNeeded = 0; + return assetSamples; // upgrade immediately + } + if (++m_FramesSinceNeeded >= realBackbufferMSAADowngradeDelayFrames) + return 1; // downgrade only after the delay + return currentSamples; // hold current during the delay + } + } + + // The real backbuffer and XR eye textures each need their own: a camera with allowXRRendering disabled + // will render into the real back buffer in the same frame as the XR cameras render into the eye textures. + private DisplayMSAARequest m_RealBackbufferMSAARequest; + private DisplayMSAARequest m_XRDisplayMSAARequest; // Must be > 1: when the renderer configuration changes for only a few frames (different render passes // enqueued, e.g. by the volume system), this keeps us from setting back buffer MSAA to 1 and back @@ -320,6 +346,41 @@ internal static bool UseDynamicBranchFogKeyword() [NoAutoStaticsCleanup] internal static RenderGraph s_RenderGraph; [NoAutoStaticsCleanup] internal static RTHandleResourcePool s_RTHandlePool; +#if UNITY_EDITOR + // Time.frameCount does not advance while an edit mode view repaints, so pooled resources would never age. + [NoAutoStaticsCleanup] static int s_ResourcePoolFrameIndex; + [NoAutoStaticsCleanup] static int s_LastResourcePoolFrameCount; + + internal static int resourcePoolFrameIndex => s_ResourcePoolFrameIndex; + + static void AdvanceResourcePoolFrameIndex(List cameras) + { + int frameCount = Time.frameCount; + int frameDelta = frameCount - s_LastResourcePoolFrameCount; + s_LastResourcePoolFrameCount = frameCount; + + if (frameDelta != 0) + { + s_ResourcePoolFrameIndex += Math.Max(frameDelta, 1); + return; + } + + if (Application.isPlaying) + return; + + foreach (var camera in cameras) + { + if (camera.cameraType != CameraType.Preview) + { + s_ResourcePoolFrameIndex++; + return; + } + } + } +#else + internal static int resourcePoolFrameIndex => Time.frameCount; +#endif + // Store locally the value on the instance due as the Render Pipeline Asset data might change before the disposal of the asset, making some APV Resources leak. internal bool apvIsEnabled = false; @@ -413,7 +474,7 @@ public UniversalRenderPipeline(UniversalRenderPipelineAsset asset) // Apply the asset's MSAA to the back buffer at bind time so it doesn't lag asset changes by a // frame; ApplyRealBackbufferMSAARequest still turns it off per-frame when no camera needs it. RequestRealBackbufferMSAA(asset.msaaSampleCount); - m_FramesSinceRealBackbufferMSAANeeded = 0; + m_RealBackbufferMSAARequest.ResetDowngradeDelay(); var defaultVolumeProfileSettings = GraphicsSettings.GetRenderPipelineSettings(); VolumeManager.instance.Initialize(defaultVolumeProfileSettings.volumeProfile, asset.volumeProfile); @@ -421,6 +482,7 @@ public UniversalRenderPipeline(UniversalRenderPipelineAsset asset) // Configure initial XR settings MSAASamples msaaSamples = (MSAASamples)Mathf.Clamp(Mathf.NextPowerOfTwo(QualitySettings.antiAliasing), (int)MSAASamples.None, (int)MSAASamples.MSAA8x); XRSystem.SetDisplayMSAASamples(msaaSamples); + m_XRDisplayMSAARequest.ResetDowngradeDelay(); XRSystem.SetRenderScale(asset.renderScale); Lightmapping.SetDelegate(s_LightsDelegate); @@ -553,6 +615,7 @@ protected override void Dispose(bool disposing) CameraCaptureBridge.enabled = false; ConstantBuffer.ReleaseAll(); + ConstantBufferPropertyWarnings.OnPipelineDisposed(); VolumeManager.instance.Deinitialize(); DisposeAdditionalCameraData(); @@ -648,17 +711,30 @@ public void Dispose() /// protected override void Render(ScriptableRenderContext renderContext, List cameras) { - // RenderPipelineManager calls this once per frame: reset the back buffer MSAA request, let each - // camera rendered here report its need, then apply. Cameras rendered outside this path (render - // requests) are not counted — safe only because they target a destination texture, never the back - // buffer. If that changes, this decision becomes incomplete. - m_FrameNeedsRealBackbufferMSAA = false; - RenderCameras(renderContext, cameras); - ApplyRealBackbufferMSAARequest(); + ConstantBufferPropertyWarnings.BeginRender(); + try + { + // RenderPipelineManager calls this once per frame: reset the back buffer MSAA request, let each + // camera rendered here report its need, then apply. Cameras rendered outside this path (render + // requests) are not counted — safe only because they target a destination texture, never the back + // buffer. If that changes, this decision becomes incomplete. + m_RealBackbufferMSAARequest.BeginFrame(); + m_XRDisplayMSAARequest.BeginFrame(); + RenderCameras(renderContext, cameras); + ApplyRealBackbufferMSAARequest(); + ApplyXRDisplayMSAARequest(); + } + finally + { + ConstantBufferPropertyWarnings.EndRender(); + } } void RenderCameras(ScriptableRenderContext renderContext, List cameras) { +#if UNITY_EDITOR + AdvanceResourcePoolFrameIndex(cameras); +#endif SetHDRState(cameras); int cameraCount = cameras.Count; @@ -681,10 +757,7 @@ void RenderCameras(ScriptableRenderContext renderContext, List cameras) GraphicsSettings.lightsUseColorTemperature = true; SetupPerFrameShaderConstants(); - var cbSettings = GraphicsSettings.GetRenderPipelineSettings(); - useGlobalConstantBuffer = cbSettings != null && cbSettings.useGlobalConstantBuffer; - - XRSystem.SetDisplayMSAASamples((MSAASamples)asset.msaaSampleCount); + RefreshGlobalConstantBufferFlag(); #if UNITY_ENABLE_CHECKS if (DebugManager.instance.isAnyDebugUIActive) @@ -740,7 +813,7 @@ void RenderCameras(ScriptableRenderContext renderContext, List cameras) } s_RenderGraph.EndFrame(); - s_RTHandlePool.PurgeUnusedResources(Time.frameCount); + s_RTHandlePool.PurgeUnusedResources(resourcePoolFrameIndex); // Clean up expired upscaler contexts (unused for > 400 frames) if (upscaling != null) @@ -757,32 +830,19 @@ void RenderCameras(ScriptableRenderContext renderContext, List cameras) #endif } - // Renderers call this (via ScriptableRenderer.ReportRealBackbufferMSAA) to report that a camera needs + // Renderers call this (via ScriptableRenderer.ReportDisplayTargetMSAA) to report that a camera needs // the real back buffer multisampled. internal void RequireRealBackbufferMSAA() { - m_FrameNeedsRealBackbufferMSAA = true; + m_RealBackbufferMSAARequest.Require(); } // Only sets the request for the next frame. The current frame already imported the live back buffer // value (Screen.currentBackbufferMSAASamples) into RenderGraph, so rendering stays correct no matter // when the surface is actually reallocated (deferred to the next frame on platforms like Metal). - // Upgrades apply immediately; downgrades wait out the hysteresis, since extra MSAA frames cost only - // bandwidth, never correctness. private void ApplyRealBackbufferMSAARequest() { - int desired; - if (m_FrameNeedsRealBackbufferMSAA) - { - m_FramesSinceRealBackbufferMSAANeeded = 0; - desired = asset.msaaSampleCount; // upgrade immediately - } - else if (++m_FramesSinceRealBackbufferMSAANeeded >= realBackbufferMSAADowngradeDelayFrames) - desired = 1; // downgrade only after the delay - else - desired = Screen.msaaSamples; // hold current during the delay - - RequestRealBackbufferMSAA(desired); + RequestRealBackbufferMSAA(m_RealBackbufferMSAARequest.Resolve(asset.msaaSampleCount, Screen.msaaSamples)); } // Sets the real back buffer MSAA count, clamped to 1 where MSAA is resolved explicitly (the @@ -796,6 +856,23 @@ private void RequestRealBackbufferMSAA(int samples) Screen.SetMSAASamples(samples); } + // XR counterpart of RequireRealBackbufferMSAA, for the XR eye textures. + internal void RequireXRDisplayMSAA() + { + m_XRDisplayMSAARequest.Require(); + } + + // XR counterpart of ApplyRealBackbufferMSAARequest. The eye textures are reallocated at the next XR + // frame start, and URP imports their live descriptor each frame, so rendering stays correct. + private void ApplyXRDisplayMSAARequest() + { + if (!XRSystem.displayActive) + return; + + int samples = m_XRDisplayMSAARequest.Resolve(asset.msaaSampleCount, (int)XRSystem.GetDisplayMSAASamples()); + XRSystem.SetDisplayMSAASamples((MSAASamples)samples); + } + /// /// Check whether RenderRequest is supported /// @@ -861,6 +938,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) { @@ -872,29 +953,38 @@ protected override void ProcessRenderRequests(ScriptableRenderConte camera.targetTexture = temporaryRT ? temporaryRT : destination; // Do not call Render() here — it must run once per frame (see its back buffer MSAA bookkeeping). - if (standardRequest != null) - { - RenderCameras(context, new List{ camera }); - } - else + ConstantBufferPropertyWarnings.BeginRender(); + try { - if (camera.targetTexture != null) + if (standardRequest != null) { - camera.targetTexture.IncrementUpdateCount(); + RenderCameras(context, new List{ camera }); } - - using (UnityEngine.Pool.ListPool.Get(out var tmp)) + else { - tmp.Add(camera); + if (camera.targetTexture != null) + { + camera.targetTexture.IncrementUpdateCount(); + } - using (new ContextRenderingScope(context, tmp)) - using (new CameraRenderingScope(context, camera)) + using (UnityEngine.Pool.ListPool.Get(out var tmp)) { - camera.gameObject.TryGetComponent(out var additionalCameraData); - RenderSingleCameraInternal(context, camera, ref additionalCameraData); + tmp.Add(camera); + + using (new ContextRenderingScope(context, tmp)) + using (new CameraRenderingScope(context, camera)) + { + camera.gameObject.TryGetComponent(out var additionalCameraData); + UpdateVolumeFramework(camera, additionalCameraData); + RenderSingleCameraInternal(context, camera, ref additionalCameraData); + } } } } + finally + { + ConstantBufferPropertyWarnings.EndRender(); + } if(temporaryRT) { @@ -967,7 +1057,17 @@ protected override void ProcessRenderRequests(ScriptableRenderConte [Obsolete("RenderSingleCamera is obsolete, please use RenderPipeline.SubmitRenderRequest with UniversalRenderer.SingleCameraRequest as RequestData type. #from(2023.1)")] public static void RenderSingleCamera(ScriptableRenderContext context, Camera camera) { - RenderSingleCameraInternal(context, camera); + ConstantBufferPropertyWarnings.BeginRender(); + try + { + camera.gameObject.TryGetComponent(out var additionalCameraData); + UpdateVolumeFramework(camera, additionalCameraData); + RenderSingleCameraInternal(context, camera); + } + finally + { + ConstantBufferPropertyWarnings.EndRender(); + } } internal static void RenderSingleCameraInternal(ScriptableRenderContext context, Camera camera, bool isLastBaseCamera = true) @@ -1002,6 +1102,9 @@ internal static void RenderSingleCameraInternal(ScriptableRenderContext context, return; } + // Render requests don't go through RenderCameras. + RefreshGlobalConstantBufferFlag(); + var frameData = GetRenderer(camera, additionalCameraData).frameData; var cameraData = CreateCameraData(frameData, camera, additionalCameraData); InitializeAdditionalCameraData(camera, additionalCameraData, true, isLastBaseCamera, cameraData); @@ -1088,7 +1191,8 @@ static void RenderSingleCamera(ScriptableRenderContext context, UniversalCameraD SetupPerCameraShaderConstants(cmd); ProbeVolumesOptions apvOptions = null; - if (camera.TryGetComponent(out var additionalCameraData)) + var additionalCameraData = cameraData.additionalCameraData; + if (additionalCameraData != null) apvOptions = additionalCameraData.volumeStack?.GetComponent(); bool supportProbeVolume = asset != null && asset.lightProbeSystem == LightProbeSystem.ProbeVolumes; @@ -1470,7 +1574,6 @@ static void RenderCameraStack(ScriptableRenderContext context, Camera baseCamera } #endif - InitializeAdditionalCameraData(overlayCamera, overlayAdditionalCameraData, false, isLastBaseCamera, overlayCameraData); overlayCameraData.camera = overlayCamera; overlayCameraData.baseCamera = baseCamera; @@ -1494,6 +1597,9 @@ static void RenderCameraStack(ScriptableRenderContext context, Camera baseCamera UpdateVolumeFramework(overlayCamera, overlayAdditionalCameraData); #endif + // We call InitializeAdditionalCameraData once per overlay camera, as for the base camera. + // The call comes after the XR setup above and after the BeginCameraRendering callbacks, + // which can move the camera. bool isLastOverlayCamera = i == lastActiveOverlayCameraIndex; InitializeAdditionalCameraData(overlayCamera, overlayAdditionalCameraData, isLastOverlayCamera, isLastBaseCamera, overlayCameraData); @@ -1772,7 +1878,7 @@ internal static void SetSupportedRenderingFeatures(UniversalRenderPipelineAsset SupportedRenderingFeatures.active.rendersUIOverlay = true; } - static ScriptableRenderer GetRenderer(Camera camera, UniversalAdditionalCameraData additionalCameraData) + internal static ScriptableRenderer GetRenderer(Camera camera, UniversalAdditionalCameraData additionalCameraData) { var renderer = additionalCameraData != null ? additionalCameraData.scriptableRenderer : null; if (renderer == null || camera.cameraType == CameraType.SceneView) @@ -1780,6 +1886,23 @@ static ScriptableRenderer GetRenderer(Camera camera, UniversalAdditionalCameraDa return renderer; } + static ShadowsVolumeOverride s_DefaultShadowsVolume; + + // Players only create the volume component types found in the Default Volume Profile, so the stack can lack this one. + internal static ShadowsVolumeOverride GetShadowsVolume(VolumeStack stack) + { + var shadowsVolume = stack.GetComponent(); + if (shadowsVolume != null) + return shadowsVolume; + + if (s_DefaultShadowsVolume == null) + { + s_DefaultShadowsVolume = ScriptableObject.CreateInstance(); + s_DefaultShadowsVolume.hideFlags = HideFlags.HideAndDontSave; + } + return s_DefaultShadowsVolume; + } + internal static void InitializeScaledDimensions(Camera camera, UniversalCameraData cameraData) { cameraData.scaledWidth = Mathf.Max(1, (int) (camera.pixelWidth * cameraData.renderScale)); @@ -2144,11 +2267,15 @@ static void InitializeAdditionalCameraData(Camera camera, UniversalAdditionalCam { using var profScope = new ProfilingScope(Profiling.Pipeline.initializeAdditionalCameraData); + cameraData.additionalCameraData = additionalCameraData; + var renderer = GetRenderer(camera, additionalCameraData); var settings = asset; bool anyShadowsEnabled = settings.supportsMainLightShadows || settings.supportsAdditionalLightShadows; - cameraData.maxShadowDistance = Mathf.Min(settings.shadowDistance, camera.farClipPlane); + Debug.Assert(VolumeManager.instance.stack != null); + var shadowsVolume = GetShadowsVolume(VolumeManager.instance.stack); + cameraData.maxShadowDistance = Mathf.Min(shadowsVolume.maxShadowDistance.value, camera.farClipPlane); cameraData.maxShadowDistance = (anyShadowsEnabled && cameraData.maxShadowDistance >= camera.nearClipPlane) ? cameraData.maxShadowDistance : 0.0f; bool isSceneViewCamera = cameraData.isSceneViewCamera; @@ -2325,10 +2452,15 @@ static UniversalShadowData CreateShadowData(ContextContainer frameData, Universa s_ShadowBiasData.Clear(); s_ShadowResolutionData.Clear(); - shadowData.shadowmapDepthBufferBits = 16; - shadowData.mainLightShadowCascadeBorder = urpAsset.cascadeBorder; - shadowData.mainLightShadowCascadesCount = urpAsset.shadowCascadeCount; - shadowData.mainLightShadowCascadesSplit = GetMainLightCascadeSplit(shadowData.mainLightShadowCascadesCount, urpAsset); + shadowData.mainLightShadowmapDepthBits = urpAsset.mainLightShadowmapDepthBits; + shadowData.additionalLightsShadowmapDepthBits = urpAsset.additionalLightsShadowmapDepthBits; +#pragma warning disable 618 + shadowData.shadowmapDepthBufferBits = (int)shadowData.mainLightShadowmapDepthBits; +#pragma warning restore 618 + var shadowsVolume = GetShadowsVolume(VolumeManager.instance.stack); + shadowData.mainLightShadowCascadeBorder = shadowsVolume.lastCascadeBorder.value; + shadowData.mainLightShadowCascadesCount = shadowsVolume.cascadeCount.value; + shadowData.mainLightShadowCascadesSplit = shadowsVolume.GetCascadeSplit(); shadowData.mainLightShadowmapWidth = urpAsset.mainLightShadowmapResolution; shadowData.mainLightShadowmapHeight = urpAsset.mainLightShadowmapResolution; shadowData.additionalLightsShadowmapWidth = shadowData.additionalLightsShadowmapHeight = @@ -2337,6 +2469,8 @@ static UniversalShadowData CreateShadowData(ContextContainer frameData, Universa // This will be setup in AdditionalLightsShadowCasterPass. shadowData.isKeywordAdditionalLightShadowsEnabled = false; shadowData.isKeywordSoftShadowsEnabled = false; + shadowData.isMainLightPCSSEnabled = false; + shadowData.isAdditionalLightsPCSSEnabled = false; // Those fields must be setup after ApplyAdaptivePerformance is called on RenderingData. // This is because this function can currently modify mainLightShadowmapWidth, mainLightShadowmapHeight and mainLightShadowCascadesCount. @@ -2383,7 +2517,7 @@ static UniversalShadowData CreateShadowData(ContextContainer frameData, Universa if (i == mainLightIndex) continue; - ref VisibleLight vl = ref visibleLights.UnsafeElementAtMutable(i); + ref VisibleLight vl = ref visibleLights.UnsafeElementAt(i); // UniversalRP doesn't support additional directional light shadows yet if (vl.lightType == LightType.Spot || vl.lightType == LightType.Point) @@ -2419,7 +2553,7 @@ static UniversalShadowData CreateShadowData(ContextContainer frameData, Universa continue; } - ref VisibleLight vl = ref visibleLights.UnsafeElementAtMutable(i); + ref VisibleLight vl = ref visibleLights.UnsafeElementAt(i); Light light = vl.light; UniversalAdditionalLightData data = null; if (light != null) @@ -2452,6 +2586,7 @@ static UniversalShadowData CreateShadowData(ContextContainer frameData, Universa GraphicsSettings.TryGetRenderPipelineSettings(out var shadowBiasSettings); shadowData.depthBiasMode = ShadowUtils.GetConfiguredDepthBiasMode(shadowBiasSettings); shadowData.normalBiasMode = ShadowUtils.GetConfiguredNormalBiasMode(shadowBiasSettings); + shadowData.softShadowKernelRadiusPercent = urpAsset.softShadowKernelRadiusPercent; shadowData.supportsSoftShadows = urpAsset.supportsSoftShadows && (shadowData.supportsMainLightShadows || shadowData.supportsAdditionalLightShadows); return shadowData; @@ -2464,17 +2599,6 @@ static CullContextData CreateCullContextData(ContextContainer frameData, Scripta return cullData; } - private static Vector3 GetMainLightCascadeSplit(int mainLightShadowCascadesCount, UniversalRenderPipelineAsset urpAsset) - { - switch (mainLightShadowCascadesCount) - { - case 1: return new Vector3(1.0f, 0.0f, 0.0f); - case 2: return new Vector3(urpAsset.cascade2Split, 1.0f, 0.0f); - case 3: return urpAsset.cascade3Split; - default: return urpAsset.cascade4Split; - } - } - static void InitializeMainLightShadowResolution(UniversalShadowData shadowData) { int maxAtlasResolution = PlatformAutoDetect.maxSupportedShadowAtlasResolution; @@ -2702,7 +2826,7 @@ static int GetBrightestDirectionalLightIndex(UniversalRenderPipelineAsset settin int totalVisibleLights = visibleLights.Length; for (int i = 0; i < totalVisibleLights; ++i) { - ref VisibleLight currVisibleLight = ref visibleLights.UnsafeElementAtMutable(i); + ref VisibleLight currVisibleLight = ref visibleLights.UnsafeElementAt(i); Light currLight = currVisibleLight.light; // Particle system lights have the light property as null. We sort lights so all particles lights @@ -2744,10 +2868,44 @@ static int GetMainLightIndex(UniversalRenderPipelineAsset settings, NativeArray< /// /// Whether URP uploads its global shader variables as a persistent constant buffer. - /// Read once per frame, this setting cannot change between the cameras of a frame. + /// Refreshed by RefreshGlobalConstantBufferFlag before anything renders. /// internal static bool useGlobalConstantBuffer { get; private set; } + /// + /// Reads the requested mode into useGlobalConstantBuffer, see . + /// + internal static void RefreshGlobalConstantBufferFlag() + { + bool wasPersistent = useGlobalConstantBuffer; + useGlobalConstantBuffer = IsGlobalConstantBufferRequested(); + + // The engine doesn't fill a bound constant buffer, so back in the transient mode the slot must be unbound. + if (wasPersistent && !useGlobalConstantBuffer) + GlobalShaderVariablesUploader.UnbindGlobal(); + } + + /// + /// Whether URP's shaders declare its global constant buffer on this graphics API, see GlobalShaderVariables.hlsl. + /// OpenGL ES 3 outside WebGL and OpenGL Core keep loose uniforms. + /// + internal static bool IsGlobalConstantBufferSupported() + { + return RenderingUtils.usePersistentConstantBuffer && SystemInfo.graphicsDeviceType != GraphicsDeviceType.OpenGLCore; + } + + /// + /// The Use Persistent Global Constant Buffer setting, where . + /// + internal static bool IsGlobalConstantBufferRequested() + { + if (!IsGlobalConstantBufferSupported()) + return false; + + var cbSettings = GraphicsSettings.GetRenderPipelineSettings(); + return cbSettings != null && cbSettings.useGlobalConstantBuffer; + } + /// /// Inverse width of the LOD cross fade dithering texture, resolved once per frame from the pipeline asset. /// The renderers read it to fill their global shader variables, see GlobalShaderVariablesBase. @@ -2758,9 +2916,6 @@ void SetupPerFrameShaderConstants() { using var profScope = new ProfilingScope(Profiling.Pipeline.setupPerFrameShaderConstants); - // Required for 2D Unlit Shadergraph master node as it doesn't currently support hidden properties. - Shader.SetGlobalColor(ShaderPropertyId.rendererColor, Color.white); - Texture2D ditheringTexture = null; switch (asset.lodCrossFadeDitheringType) { diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipelineCore.cs b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipelineCore.cs index f84d0c23d83..b1414c5b1db 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipelineCore.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipelineCore.cs @@ -648,8 +648,19 @@ internal ShadowData(ContextContainer frameData) /// /// The number of bits used. /// + [Obsolete("Use mainLightShadowmapDepthBits or additionalLightsShadowmapDepthBits. #from(7000.0)", false)] public ref int shadowmapDepthBufferBits => ref frameData.Get().shadowmapDepthBufferBits; + /// + /// The depth buffer precision of the main light shadow map. + /// + public ref DepthBits mainLightShadowmapDepthBits => ref frameData.Get().mainLightShadowmapDepthBits; + + /// + /// The depth buffer precision of the additional lights shadow map atlas. + /// + public ref DepthBits additionalLightsShadowmapDepthBits => ref frameData.Get().additionalLightsShadowmapDepthBits; + /// /// A list of shadow bias. /// @@ -664,6 +675,14 @@ internal ShadowData(ContextContainer frameData) internal ref ShadowNormalBiasMode normalBiasMode => ref frameData.Get().normalBiasMode; + internal ref GraphicsFormat mainLightShadowmapFormat => ref frameData.Get().mainLightShadowmapFormat; + + internal ref GraphicsFormat additionalLightsShadowmapFormat => ref frameData.Get().additionalLightsShadowmapFormat; + + internal ref bool mainLightReceiverNormalBiasSkipped => ref frameData.Get().mainLightReceiverNormalBiasSkipped; + + internal ref float softShadowKernelRadiusPercent => ref frameData.Get().softShadowKernelRadiusPercent; + internal ref bool isKeywordAdditionalLightShadowsEnabled => ref frameData.Get().isKeywordAdditionalLightShadowsEnabled; internal ref bool isKeywordSoftShadowsEnabled => ref frameData.Get().isKeywordSoftShadowsEnabled; internal ref int mainLightShadowResolution => ref frameData.Get().mainLightShadowResolution; @@ -820,6 +839,7 @@ internal static class ShaderPropertyId public static readonly int cameraToWorldMatrix = Shader.PropertyToID("unity_CameraToWorld"); public static readonly int shadowBias = Shader.PropertyToID("_ShadowBias"); + public static readonly int zClip = Shader.PropertyToID("_ZClip"); public static readonly int lightDirection = Shader.PropertyToID("_LightDirection"); public static readonly int lightPosition = Shader.PropertyToID("_LightPosition"); @@ -845,9 +865,6 @@ internal static class ShaderPropertyId // This uniform is specific to the RTHandle system public static readonly int rtHandleScale = Shader.PropertyToID("_RTHandleScale"); - // Required for 2D Unlit Shadergraph master node as it doesn't currently support hidden properties. - public static readonly int rendererColor = Shader.PropertyToID("_RendererColor"); - public static readonly int ditheringTexture = Shader.PropertyToID("_DitheringTexture"); public static readonly int ditheringTextureInvSize = Shader.PropertyToID("_DitheringTextureInvSize"); @@ -922,8 +939,7 @@ internal static class ShaderGlobalKeywords public static readonly GlobalKeyword SoftShadowsLow = GlobalKeyword.Create(ShaderKeywordStrings.SoftShadowsLow); public static readonly GlobalKeyword SoftShadowsMedium = GlobalKeyword.Create(ShaderKeywordStrings.SoftShadowsMedium); public static readonly GlobalKeyword SoftShadowsHigh = GlobalKeyword.Create(ShaderKeywordStrings.SoftShadowsHigh); - public static readonly GlobalKeyword MainLightShadowsSoftPcss = GlobalKeyword.Create(ShaderKeywordStrings.MainLightShadowsSoftPcss); - public static readonly GlobalKeyword AdditionalLightShadowsSoftPcss = GlobalKeyword.Create(ShaderKeywordStrings.AdditionalLightShadowsSoftPcss); + public static readonly GlobalKeyword ShadowsPCSS = GlobalKeyword.Create(ShaderKeywordStrings.ShadowsPCSS); public static readonly GlobalKeyword MixedLightingSubtractive = GlobalKeyword.Create(ShaderKeywordStrings.MixedLightingSubtractive); // Backward compatibility public static readonly GlobalKeyword LightmapShadowMixing = GlobalKeyword.Create(ShaderKeywordStrings.LightmapShadowMixing); public static readonly GlobalKeyword ShadowsShadowMask = GlobalKeyword.Create(ShaderKeywordStrings.ShadowsShadowMask); @@ -1005,6 +1021,7 @@ internal static class ShaderGlobalKeywords public static readonly GlobalKeyword DEPTH_AS_INPUT_ATTACHMENT_MSAA = GlobalKeyword.Create(ShaderKeywordStrings.DEPTH_AS_INPUT_ATTACHMENT_MSAA); public static readonly GlobalKeyword LightFalloffQuadratic = GlobalKeyword.Create(ShaderKeywordStrings.LightFalloffQuadratic); + public static readonly GlobalKeyword ShadowReceiverNormalBias = GlobalKeyword.Create(ShaderKeywordStrings.ShadowReceiverNormalBias); // TODO: Move following keywords to Local keywords? // https://docs.unity3d.com/ScriptReference/Rendering.LocalKeyword.html @@ -1101,11 +1118,8 @@ public static class ShaderKeywordStrings /// Keyword used for high quality soft shadows. public const string SoftShadowsHigh = "_SHADOWS_SOFT_HIGH"; - /// Keyword used for PCSS (Percentage-Closer Soft Shadows) on the main directional light. - internal const string MainLightShadowsSoftPcss = "_MAIN_LIGHT_SHADOWS_SOFT_PCSS"; - - /// Keyword used for PCSS (Percentage-Closer Soft Shadows) on additional punctual lights. - internal const string AdditionalLightShadowsSoftPcss = "_ADDITIONAL_LIGHT_SHADOWS_SOFT_PCSS"; + /// Keyword used alongside SoftShadows when at least one light uses PCSS (Percentage-Closer Soft Shadows). Each light still selects its own filter. + public const string ShadowsPCSS = "_SHADOWS_PCSS"; /// Deprecated keyword, equivalent to LightmapShadowMixing without ShadowsShadowMask. Use those instead. public const string MixedLightingSubtractive = "_MIXED_LIGHTING_SUBTRACTIVE"; // Backward compatibility @@ -1432,6 +1446,9 @@ public static class ShaderKeywordStrings /// Keyword used to enable Built-in Render Pipeline compatible light falloff. public const string LightFalloffQuadratic = "_LIGHT_FALLOFF_QUADRATIC"; + + /// Keyword used to apply the shadow normal bias at the shadow receiver. + public const string ShadowReceiverNormalBias = "_SHADOW_RECEIVER_NORMAL_BIAS"; } public sealed partial class UniversalRenderPipeline diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipelineGlobalSettings.cs b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipelineGlobalSettings.cs index d60c15bd5b1..b19b115f07b 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipelineGlobalSettings.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipelineGlobalSettings.cs @@ -30,7 +30,7 @@ partial class UniversalRenderPipelineGlobalSettings : RenderPipelineGlobalSettin internal bool IsAtLastVersion() => k_LastVersion == m_AssetVersion; - internal const int k_LastVersion = 16; + internal const int k_LastVersion = 17; #pragma warning disable CS0414 [SerializeField][FormerlySerializedAs("k_AssetVersion")] @@ -194,6 +194,12 @@ public static void UpgradeAsset(EntityId assetInstanceID) asset.m_AssetVersion = 16; } + if (asset.m_AssetVersion < 17) + { + MigrateShadowSettingsToVolumeProfiles(asset); + asset.m_AssetVersion = 17; + } + // If the asset version has changed, means that a migration step has been executed if (assetVersionBeforeUpgrade != asset.m_AssetVersion) EditorUtility.SetDirty(asset); @@ -337,11 +343,12 @@ static void MigrateScreenSpaceAmbientOcclusionToVolumeProfiles(UniversalRenderPi { // SSAO is now driven by the volume stack, so the renderer feature settings are no longer read. // The default profile goes first because a quality profile can reference that same asset. - MigrateScreenSpaceAmbientOcclusionToDefaultVolumeProfile(data); - MigrateScreenSpaceAmbientOcclusionToQualityVolumeProfiles(); + var reportedAssets = new HashSet(); + MigrateScreenSpaceAmbientOcclusionToDefaultVolumeProfile(data, reportedAssets); + MigrateScreenSpaceAmbientOcclusionToQualityVolumeProfiles(reportedAssets); } - static void MigrateScreenSpaceAmbientOcclusionToQualityVolumeProfiles() + static void MigrateScreenSpaceAmbientOcclusionToQualityVolumeProfiles(HashSet reportedAssets) { var migratedProfiles = new Dictionary(); foreach (var urpAsset in EnumerateQualityLevelPipelineAssets()) @@ -362,13 +369,14 @@ static void MigrateScreenSpaceAmbientOcclusionToQualityVolumeProfiles() continue; var ssaoOverride = profile.Add(overrides: true); + WarnIfRenderersHaveDifferentSettings(urpAsset, ssaoFeature, reportedAssets); CopyRendererFeatureSettingsToVolumeOverride(ssaoFeature, ssaoOverride); - PersistVolumeOverride(profile, ssaoOverride); + PersistVolumeOverride(profile, ssaoOverride, "Screen Space Ambient Occlusion"); migratedProfiles.Add(profile, urpAsset); } } - static void MigrateScreenSpaceAmbientOcclusionToDefaultVolumeProfile(UniversalRenderPipelineGlobalSettings data) + static void MigrateScreenSpaceAmbientOcclusionToDefaultVolumeProfile(UniversalRenderPipelineGlobalSettings data, HashSet reportedAssets) { // The default profile is shared by every quality level, so it can only hold the active pipeline's settings var profile = GetOrCreateGraphicsSettings(data).volumeProfile; @@ -379,16 +387,19 @@ static void MigrateScreenSpaceAmbientOcclusionToDefaultVolumeProfile(UniversalRe if (profile.Has()) return; + var urpAsset = GraphicsSettings.currentRenderPipeline as UniversalRenderPipelineAsset; ScreenSpaceAmbientOcclusion ssaoFeature = null; - bool active = GraphicsSettings.currentRenderPipeline is UniversalRenderPipelineAsset urpAsset - && TryGetActiveScreenSpaceAmbientOcclusionFeature(urpAsset, out ssaoFeature); + bool active = urpAsset != null && TryGetActiveScreenSpaceAmbientOcclusionFeature(urpAsset, out ssaoFeature); var ssaoOverride = profile.Add(overrides: active); if (active) + { + WarnIfRenderersHaveDifferentSettings(urpAsset, ssaoFeature, reportedAssets); CopyRendererFeatureSettingsToVolumeOverride(ssaoFeature, ssaoOverride); + } - PersistVolumeOverride(profile, ssaoOverride); + PersistVolumeOverride(profile, ssaoOverride, "Screen Space Ambient Occlusion"); } static IEnumerable EnumerateQualityLevelPipelineAssets() @@ -408,25 +419,77 @@ static IEnumerable EnumerateQualityLevelPipelineAs static bool TryGetActiveScreenSpaceAmbientOcclusionFeature(UniversalRenderPipelineAsset urpAsset, out ScreenSpaceAmbientOcclusion ssaoFeature) { + if (urpAsset.TryGetRendererData(urpAsset.m_DefaultRendererIndex, out var defaultRendererData) + && TryGetActiveScreenSpaceAmbientOcclusionFeature(defaultRendererData, out ssaoFeature)) + return true; + + // Cameras can render with any renderer of the asset, so fall back to the first one that has the feature + foreach (var rendererData in urpAsset.rendererDataList) + { + if (TryGetActiveScreenSpaceAmbientOcclusionFeature(rendererData, out ssaoFeature)) + return true; + } + ssaoFeature = null; - return urpAsset.TryGetRendererData(urpAsset.m_DefaultRendererIndex, out var rendererData) - && rendererData != null + return false; + } + + static bool TryGetActiveScreenSpaceAmbientOcclusionFeature(ScriptableRendererData rendererData, out ScreenSpaceAmbientOcclusion ssaoFeature) + { + ssaoFeature = null; + return rendererData != null && rendererData.TryGetRendererFeature(out ssaoFeature) && ssaoFeature.isActive; } - static void PersistVolumeOverride(VolumeProfile profile, VolumeComponent volumeOverride) + static void WarnIfRenderersHaveDifferentSettings(UniversalRenderPipelineAsset urpAsset, ScreenSpaceAmbientOcclusion migratedFeature, HashSet reportedAssets) + { + if (!reportedAssets.Add(urpAsset)) + return; + + string migratedRendererName = null; + var skippedRendererNames = new List(); + foreach (var rendererData in urpAsset.rendererDataList) + { + if (!TryGetActiveScreenSpaceAmbientOcclusionFeature(rendererData, out var ssaoFeature)) + continue; + + if (ssaoFeature == migratedFeature) + migratedRendererName = rendererData.name; + else if (!HaveSameMigratedSettings(ssaoFeature, migratedFeature) && !skippedRendererNames.Contains(rendererData.name)) + skippedRendererNames.Add(rendererData.name); + } + + if (skippedRendererNames.Count == 0) + return; + + Debug.LogWarning($"URP: The pipeline asset '{urpAsset.name}' has renderers with different Screen Space Ambient Occlusion settings. " + + $"Only the settings of '{migratedRendererName}' were migrated to the volume override. If you need the others, add them to a volume manually.\n" + + $"Not migrated: '{string.Join("', '", skippedRendererNames)}'"); + } + + static bool HaveSameMigratedSettings(ScreenSpaceAmbientOcclusion a, ScreenSpaceAmbientOcclusion b) + { +#pragma warning disable CS0618 // Type or member is obsolete + var x = a.settings; + var y = b.settings; +#pragma warning restore CS0618 + return (x.Intensity, x.Radius, x.Falloff, x.DirectLightingStrength, x.Downsample, x.AfterOpaque, x.AOMethod, x.Source, x.NormalSamples, x.Samples, x.BlurQuality) + == (y.Intensity, y.Radius, y.Falloff, y.DirectLightingStrength, y.Downsample, y.AfterOpaque, y.AOMethod, y.Source, y.NormalSamples, y.Samples, y.BlurQuality); + } + + static bool PersistVolumeOverride(VolumeProfile profile, VolumeComponent volumeOverride, string settingsName) { // A profile that only lives in memory cannot hold the override as a sub-asset if (!EditorUtility.IsPersistent(profile)) - return; + return true; // A read-only profile cannot store the override, and the version bump would hide the loss if (!AssetDatabase.MakeEditable(AssetDatabase.GetAssetPath(profile))) { - Debug.LogWarning($"URP: The volume profile '{profile.name}' is not editable, so its Screen Space Ambient Occlusion settings were not migrated. " + + Debug.LogWarning($"URP: The volume profile '{AssetLinkUtils.AssetLink(profile)}' is not editable, so its {settingsName} settings were not migrated. " + "Make the asset editable and add the override manually."); - return; + return false; } AssetDatabase.AddObjectToAsset(volumeOverride, profile); @@ -435,6 +498,7 @@ static void PersistVolumeOverride(VolumeProfile profile, VolumeComponent volumeO EditorUtility.SetDirty(volumeOverride); EditorUtility.SetDirty(profile); AssetDatabase.SaveAssetIfDirty(profile); + return true; } static void CopyRendererFeatureSettingsToVolumeOverride(ScreenSpaceAmbientOcclusion feature, ScreenSpaceAmbientOcclusionVolumeOverride ssaoOverride) @@ -513,6 +577,326 @@ static void MigrateLightFalloffMode(UniversalRenderPipelineGlobalSettings data) } } + internal struct ShadowSettingsValues : IEquatable + { + internal float maxShadowDistance; + internal int cascadeCount; + internal float split0; + internal float split1; + internal float split2; + internal float lastCascadeBorder; + + internal static ShadowSettingsValues FromCascadeSplitSets(float maxShadowDistance, int cascadeCount, + float cascade2Split, Vector2 cascade3Split, Vector3 cascade4Split, float lastCascadeBorder) + { + var values = new ShadowSettingsValues + { + maxShadowDistance = maxShadowDistance, + cascadeCount = cascadeCount, + split0 = cascade4Split.x, + split1 = cascade4Split.y, + split2 = cascade4Split.z, + lastCascadeBorder = lastCascadeBorder + }; + + if (cascadeCount == 2) + { + values.split0 = cascade2Split; + } + else if (cascadeCount == 3) + { + values.split0 = cascade3Split.x; + values.split1 = cascade3Split.y; + } + + return values; + } + + internal readonly bool IsDefault() + { + var defaults = CreateInstance(); + bool isDefault = Mathf.Approximately(maxShadowDistance, defaults.maxShadowDistance.value) + && cascadeCount == defaults.cascadeCount.value + && Mathf.Approximately(split0, defaults.cascadeSplit0.value) + && Mathf.Approximately(split1, defaults.cascadeSplit1.value) + && Mathf.Approximately(split2, defaults.cascadeSplit2.value) + && Mathf.Approximately(lastCascadeBorder, defaults.lastCascadeBorder.value); + DestroyImmediate(defaults); + return isDefault; + } + + public readonly bool Equals(ShadowSettingsValues other) + { + return maxShadowDistance == other.maxShadowDistance + && cascadeCount == other.cascadeCount + && split0 == other.split0 + && split1 == other.split1 + && split2 == other.split2 + && lastCascadeBorder == other.lastCascadeBorder; + } + + public override readonly bool Equals(object obj) => obj is ShadowSettingsValues other && Equals(other); + + public override readonly int GetHashCode() => HashCode.Combine(maxShadowDistance, cascadeCount, split0, split1, split2, lastCascadeBorder); + } + + static ShadowSettingsValues ReadObsoleteShadowSettings(UniversalRenderPipelineAsset urpAsset) + { +#pragma warning disable 618 // Type or member is obsolete + return ShadowSettingsValues.FromCascadeSplitSets( + urpAsset.m_ObsoleteShadowDistance, + urpAsset.m_ObsoleteShadowCascadeCount, + urpAsset.m_ObsoleteCascade2Split, + urpAsset.m_ObsoleteCascade3Split, + urpAsset.m_ObsoleteCascade4Split, + urpAsset.m_ObsoleteCascadeBorder); +#pragma warning restore 618 + } + + static void MigrateShadowSettingsToVolumeProfiles(UniversalRenderPipelineGlobalSettings data) + { + MigrateShadowSettingsToVolumeProfiles(data, FindPipelineAssets()); + } + + internal static void MigratePendingShadowSettingsToVolumeProfiles(List urpAssets) + { + if (GraphicsSettings.GetSettingsForRenderPipeline() is not UniversalRenderPipelineGlobalSettings data + || data.m_AssetVersion < 17) + return; + + bool needsMigration = false; + foreach (var urpAsset in urpAssets) + needsMigration |= urpAsset.m_ShadowSettingsMigrationPending; + + if (needsMigration) + MigrateShadowSettingsToVolumeProfiles(data, FindPipelineAssets()); + } + + internal static bool HasUnmigratedShadowSettings(UniversalRenderPipelineAsset urpAsset, bool inReadOnlyPackage) + { + return urpAsset.m_ShadowSettingsMigrationPending + && isInReadOnlyPackage(AssetDatabase.GetAssetPath(urpAsset)) == inReadOnlyPackage + && !ReadObsoleteShadowSettings(urpAsset).IsDefault(); + } + + internal static Predicate isInReadOnlyPackage = assetPath => + UnityEditor.PackageManager.PackageInfo.FindForAssetPath(assetPath) is { } package + && package.source != UnityEditor.PackageManager.PackageSource.Embedded + && package.source != UnityEditor.PackageManager.PackageSource.Local; + + internal static List FindPipelineAssets() + { + var paths = new List(); + foreach (var guid in AssetDatabase.FindAssets("t:UniversalRenderPipelineAsset")) + paths.Add(AssetDatabase.GUIDToAssetPath(guid)); + paths.Sort(StringComparer.Ordinal); + + var urpAssets = new List(paths.Count); + foreach (var path in paths) + { + var urpAsset = AssetDatabase.LoadAssetAtPath(path); + if (urpAsset != null) + urpAssets.Add(urpAsset); + } + return urpAssets; + } + + static void MigrateShadowSettingsToVolumeProfiles(UniversalRenderPipelineGlobalSettings data, List urpAssets) + { + var defaultProfile = data.TryGet(typeof(URPDefaultVolumeProfileSettings), out var settings) + && settings is URPDefaultVolumeProfileSettings defaultProfileSettings ? defaultProfileSettings.volumeProfile : null; + + var groups = new List<(VolumeProfile source, ShadowSettingsValues values, List members)>(); + var groupIndices = new Dictionary<(VolumeProfile source, ShadowSettingsValues values), int>(); + foreach (var urpAsset in urpAssets) + { + if (!urpAsset.m_ShadowSettingsMigrationPending) + continue; + + var values = ReadObsoleteShadowSettings(urpAsset); + bool isDefault = values.IsDefault(); + + string assetPath = AssetDatabase.GetAssetPath(urpAsset); + if (isInReadOnlyPackage(assetPath)) + { + if (!isDefault) + Debug.LogWarning($"URP: The pipeline asset '{AssetLinkUtils.AssetLink(urpAsset)}' is in a read-only package, so its {nameof(ShadowsVolumeOverride)} settings were not migrated. " + + "Update the package, or copy the asset into the Assets folder and use the copy."); + continue; + } + + var profile = urpAsset.volumeProfile; + if (isDefault || (profile != null && profile.Has())) + { + MarkShadowSettingsMigrated(urpAsset); + continue; + } + + if (!IsPipelineAssetEditable(urpAsset)) + continue; + + if (profile != null && groupIndices.TryGetValue((profile, values), out int groupIndex)) + { + groups[groupIndex].members.Add(urpAsset); + continue; + } + + if (profile != null) + groupIndices.Add((profile, values), groups.Count); + groups.Add((profile, values, new List { urpAsset })); + } + + var lines = new List(); + var sources = new List(); + bool anyShared = false; + foreach (var (source, values, members) in groups) + { + string name = members.Count == 1 ? $"{members[0].name}_VolumeProfile" : $"{source.name}_Shadows"; + var newProfile = CreateVolumeProfileCopy(source, VolumeProfilePathNextTo(members[0], name)); + if (!WriteShadowSettings(newProfile, values)) + { + AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(newProfile)); + continue; + } + + foreach (var member in members) + { + AssignVolumeProfile(member, newProfile); + MarkShadowSettingsMigrated(member); + } + + if (source == null) + continue; + + lines.Add(DescribeVolumeProfileCopy(members, newProfile, source, defaultProfile) + "."); + anyShared |= members.Count > 1; + if (!sources.Contains(source)) + sources.Add(source); + } + + foreach (var source in sources) + { + var remainingUsers = urpAssets.FindAll(urpAsset => urpAsset.volumeProfile == source); + if (remainingUsers.Count > 0) + lines.Add(DescribeRemainingUsers(source, remainingUsers) + "."); + } + + if (lines.Count > 0) + Debug.LogWarning("URP: Shadow distance and cascade settings moved to Shadows volume overrides in new volume profiles, " + + "so later changes to the previous volume profiles no longer apply to these pipeline assets." + + (anyShared ? " Pipeline assets with the same volume profile and shadow settings share one new profile." : string.Empty) + "\n" + + string.Join("\n", lines)); + } + + static void MarkShadowSettingsMigrated(UniversalRenderPipelineAsset urpAsset) + { + if (!AssetDatabase.MakeEditable(AssetDatabase.GetAssetPath(urpAsset))) + return; + + urpAsset.m_ShadowSettingsMigrationPending = false; + EditorUtility.SetDirty(urpAsset); + AssetDatabase.SaveAssetIfDirty(urpAsset); + } + + internal static VolumeProfile CreateQualityVolumeProfile(UniversalRenderPipelineAsset urpAsset) where T : VolumeComponent + { + if (!IsPipelineAssetEditable(urpAsset)) + return null; + + var profile = CreateVolumeProfileCopy(urpAsset.volumeProfile, VolumeProfilePathNextTo(urpAsset, $"{urpAsset.name}_VolumeProfile")); + AssignVolumeProfile(urpAsset, profile); + return profile; + } + + static bool IsPipelineAssetEditable(UniversalRenderPipelineAsset urpAsset) where T : VolumeComponent + { + if (AssetDatabase.MakeEditable(AssetDatabase.GetAssetPath(urpAsset))) + return true; + + Debug.LogWarning($"URP: The pipeline asset '{AssetLinkUtils.AssetLink(urpAsset)}' is not editable, so its {typeof(T).Name} settings were not migrated. " + + "Make the asset editable and add the override to its volume profile manually."); + return false; + } + + static string VolumeProfilePathNextTo(UniversalRenderPipelineAsset urpAsset, string name) + { + string folder = Path.GetDirectoryName(AssetDatabase.GetAssetPath(urpAsset)).Replace('\\', '/'); + return AssetDatabase.GenerateUniqueAssetPath($"{folder}/{name}.asset"); + } + + static VolumeProfile CreateVolumeProfileCopy(VolumeProfile source, string path) where T : VolumeComponent + { + var profile = CreateInstance(); + AssetDatabase.CreateAsset(profile, path); + + if (source != null) + { + foreach (var sourceComponent in source.components) + { + if (sourceComponent == null || sourceComponent is T) + continue; + + var component = Instantiate(sourceComponent); + component.name = sourceComponent.name; + component.hideFlags = sourceComponent.hideFlags; + profile.components.Add(component); + AssetDatabase.AddObjectToAsset(component, profile); + } + } + + EditorUtility.SetDirty(profile); + AssetDatabase.SaveAssetIfDirty(profile); + return profile; + } + + static void AssignVolumeProfile(UniversalRenderPipelineAsset urpAsset, VolumeProfile profile) + { + urpAsset.volumeProfile = profile; + EditorUtility.SetDirty(urpAsset); + AssetDatabase.SaveAssetIfDirty(urpAsset); + } + + internal static string DescribeVolumeProfileCopy(List urpAssets, VolumeProfile copy, VolumeProfile source, VolumeProfile defaultProfile) + { + return $"{AssetLinks(urpAssets)} now {(urpAssets.Count == 1 ? "uses" : "use")} '{AssetLinkUtils.AssetLink(copy)}', a copy of " + + (source == defaultProfile ? $"the default volume profile '{AssetLinkUtils.AssetLink(source)}'" : $"'{AssetLinkUtils.AssetLink(source)}'"); + } + + internal static string DescribeRemainingUsers(VolumeProfile source, List urpAssets) + { + return $"'{AssetLinkUtils.AssetLink(source)}' is still used by {AssetLinks(urpAssets)}"; + } + + static string AssetLinks(List urpAssets) + { + var links = new List(urpAssets.Count); + foreach (var urpAsset in urpAssets) + links.Add($"'{AssetLinkUtils.AssetLink(urpAsset)}'"); + return string.Join(", ", links); + } + + internal static bool WriteShadowSettings(VolumeProfile profile, in ShadowSettingsValues values) + { + var shadowsOverride = profile.Add(overrides: true); + CopyShadowSettingsToVolumeOverride(values, shadowsOverride); + if (PersistVolumeOverride(profile, shadowsOverride, "Shadows")) + return true; + + profile.Remove(); + CoreUtils.Destroy(shadowsOverride); + return false; + } + + static void CopyShadowSettingsToVolumeOverride(in ShadowSettingsValues values, ShadowsVolumeOverride shadowsOverride) + { + shadowsOverride.maxShadowDistance.value = values.maxShadowDistance; + shadowsOverride.cascadeCount.value = values.cascadeCount; + shadowsOverride.cascadeSplit0.value = values.split0; + shadowsOverride.cascadeSplit1.value = values.split1; + shadowsOverride.cascadeSplit2.value = values.split2; + shadowsOverride.lastCascadeBorder.value = values.lastCascadeBorder; + } + #endif // #if UNITY_EDITOR #endregion diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipelineRenderGraph.cs b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipelineRenderGraph.cs index 9b0b625e3c6..c0af3f8b24f 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipelineRenderGraph.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipelineRenderGraph.cs @@ -17,7 +17,7 @@ static void RecordAndExecuteRenderGraph(RenderGraph renderGraph, ScriptableRende generateDebugData = camera.cameraType != CameraType.Preview && !camera.isProcessingRenderRequest, commandBuffer = cmd, scriptableRenderContext = context, - currentFrameIndex = Time.frameCount, + currentFrameIndex = resourcePoolFrameIndex, renderTextureUVOriginStrategy = renderTextureUVOriginStrategy, }; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderer.cs b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderer.cs index efe948076e1..d757d921da2 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderer.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderer.cs @@ -197,6 +197,9 @@ internal RenderingMode renderingModeActual { bool m_ShadowmapStencil; StencilState m_DefaultStencilState; LightCookieManager m_LightCookieManager; +#if VOLUMETRIC_FOG + FogVolumeManager m_FogVolumeManager; +#endif IntermediateTextureMode m_IntermediateTextureMode; // Materials used in URP Scriptable Render Passes @@ -219,8 +222,9 @@ internal RenderingMode renderingModeActual { internal bool postProcessEnabled { get; set; } internal DeferredLights deferredLights { get => m_DeferredLights; } -#if VOLUMETRIC_FOG internal ForwardLights forwardLights { get => m_ForwardLights; } +#if VOLUMETRIC_FOG + internal FogVolumeManager fogVolumeManager { get => m_FogVolumeManager; } #endif internal LayerMask prepassLayerMask { get; set; } internal LayerMask opaqueLayerMask { get; set; } @@ -326,6 +330,10 @@ public UniversalRenderer(UniversalRendererData data) : base(data) m_LightCookieManager = new LightCookieManager(ref settings); } +#if VOLUMETRIC_FOG + m_FogVolumeManager = new FogVolumeManager(); +#endif + this.stripShadowsOffVariants = data.stripShadowsOffVariants; this.stripAdditionalLightOffVariants = data.stripAdditionalLightOffVariants; #if ENABLE_VR && ENABLE_XR_MODULE @@ -337,7 +345,7 @@ public UniversalRenderer(UniversalRendererData data) : base(data) ForwardLights.InitParams forwardInitParams; forwardInitParams.lightCookieManager = m_LightCookieManager; - forwardInitParams.forwardPlus = data.renderingMode == RenderingMode.DeferredPlus || data.renderingMode == RenderingMode.ForwardPlus; + forwardInitParams.clustering = data.renderingMode == RenderingMode.DeferredPlus || data.renderingMode == RenderingMode.ForwardPlus; m_ForwardLights = new ForwardLights(forwardInitParams); //m_DeferredLights.LightCulling = data.lightCulling; this.m_RenderingMode = data.renderingMode; @@ -511,6 +519,9 @@ internal override void UpdateSupportedRenderingFeatures() protected override void Dispose(bool disposing) { m_ForwardLights.Cleanup(); +#if VOLUMETRIC_FOG + m_FogVolumeManager.Dispose(); +#endif m_GlobalShaderVariablesUploader?.Release(); m_FinalBlitPass?.Dispose(); @@ -727,7 +738,7 @@ public override void FinishRendering(CommandBuffer cmd) // Over time, more settings should be folded into these structs so that the recording methods are fully // decoupled from scattered state. - // Aggregates decisions regarding which rendering stages will actually execute this frame. Derived from + // Aggregates decisions regarding which rendering stages will actually execute this frame, and their targets. Derived from // camera settings, culling masks, shadow distance, and technique requirements (e.g. depth priming). struct RenderStages { @@ -736,6 +747,8 @@ struct RenderStages internal bool drawOpaquePass; internal bool drawTransparentPass; internal bool drawDeferredLightingPass; + + internal bool depthTextureProducedByPrepass; } // Aggregates texture and resource requirements declared by ScriptableRenderPasses and internal features. @@ -918,7 +931,7 @@ static bool RequiresIntermediateColorTexture(UniversalCameraData cameraData, in bool requiresBlitForOffscreenCamera = applyPostProcessing || renderPassInputs.requiresColorTexture || requiresExplicitMsaaResolve || !cameraData.isDefaultViewport || requestedColorHistory; if (isOffscreenRender) - return requiresBlitForOffscreenCamera; + return requiresBlitForOffscreenCamera || isScaledRender; return requiresBlitForOffscreenCamera || isScaledRender || isScalableBufferManagerUsed || cameraData.isHdrEnabled || !isCompatibleBackbufferTextureDimension || isCapturing || cameraData.requireSrgbConversion; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRendererDebug.cs b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRendererDebug.cs index b36bd2ea315..74c02d9326d 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRendererDebug.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRendererDebug.cs @@ -59,7 +59,6 @@ private void SetupRenderGraphFinalPassDebug(RenderGraph renderGraph, ContextCont { UniversalResourceData resourceData = frameData.Get(); UniversalCameraData cameraData = frameData.Get(); - UniversalShadowData shadowData = frameData.Get(); if ((DebugHandler != null) && DebugHandler.IsActiveForCamera(cameraData.isPreviewCamera)) { @@ -98,6 +97,8 @@ private void SetupRenderGraphFinalPassDebug(RenderGraph renderGraph, ContextCont // The debug texture for STP is filled later during post-process rendering so we cannot assign the resource now or it will be invalid if (fullScreenDebugMode != DebugFullScreenMode.STP) { + TextureHandle atlasTexture = TextureHandle.nullHandle; + // Render into the debug texture { ImportResourceParams importParams = new ImportResourceParams(); @@ -128,37 +129,39 @@ private void SetupRenderGraphFinalPassDebug(RenderGraph renderGraph, ContextCont } case DebugFullScreenMode.AdditionalLightsShadowMap: { - BlitToDebugTexture(renderGraph, resourceData.additionalShadowsTexture, debugTexture); + atlasTexture = resourceData.additionalShadowsTexture; + BlitToDebugTexture(renderGraph, atlasTexture, debugTexture); break; } case DebugFullScreenMode.MainLightShadowMap: { - BlitToDebugTexture(renderGraph, resourceData.mainShadowsTexture, debugTexture); + atlasTexture = resourceData.mainShadowsTexture; + BlitToDebugTexture(renderGraph, atlasTexture, debugTexture); break; } case DebugFullScreenMode.AdditionalLightsCookieAtlas: { // Copy atlas texture to make it "readonly". Direct reference (debug=atlas) can lead to handle->texture reallocation. - var textureHandle = + atlasTexture = m_LightCookieManager is { AdditionalLightsCookieAtlasTexture: not null } ? renderGraph.ImportTexture(m_LightCookieManager .AdditionalLightsCookieAtlasTexture) : TextureHandle.nullHandle; - BlitToDebugTexture(renderGraph, textureHandle, debugTexture); + BlitToDebugTexture(renderGraph, atlasTexture, debugTexture); break; } case DebugFullScreenMode.ReflectionProbeAtlas: { // Copy atlas texture to make it "readonly". Direct reference (debug=atlas) can lead to handle->texture reallocation. - var textureHandle = + atlasTexture = m_ForwardLights.reflectionProbeManager.atlasRT != null ? renderGraph.ImportTexture(RTHandles.Alloc( m_ForwardLights.reflectionProbeManager.atlasRT, transferOwnership: true)) : TextureHandle.nullHandle; - BlitToDebugTexture(renderGraph, textureHandle, debugTexture); + BlitToDebugTexture(renderGraph, atlasTexture, debugTexture); break; } case DebugFullScreenMode.Custom: @@ -178,22 +181,11 @@ private void SetupRenderGraphFinalPassDebug(RenderGraph renderGraph, ContextCont } } - // Textures that are not in screen aspect ratio need to be corrected + // Ensure that atlas is not stretched, but doesn't take up more than the percentage in any dimension. + if (atlasTexture.IsValid()) { - RenderTexture source = null; - switch (fullScreenDebugMode) - { - case DebugFullScreenMode.AdditionalLightsShadowMap: source = shadowData.shadowPassGroup?.additionalLightShadowmapPass?.m_AdditionalLightsShadowmapHandle?.rt; break; - case DebugFullScreenMode.MainLightShadowMap: source = shadowData.shadowPassGroup?.mainLightShadowmapPass?.m_MainLightShadowmapTexture?.rt; break; - case DebugFullScreenMode.AdditionalLightsCookieAtlas: source = m_LightCookieManager?.AdditionalLightsCookieAtlasTexture?.rt; break; - case DebugFullScreenMode.ReflectionProbeAtlas: source = m_ForwardLights?.reflectionProbeManager.atlasRT; break; - default: - break; - } - - // Ensure that atlas is not stretched, but doesn't take up more than the percentage in any dimension. - if (source != null) - CorrectForTextureAspectRatio(ref width, ref height, source.width, source.height); + var desc = renderGraph.GetTextureDesc(atlasTexture); + CorrectForTextureAspectRatio(ref width, ref height, desc.width, desc.height); } } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRendererRenderGraph.cs b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRendererRenderGraph.cs index f3b963bd3ea..9ba6de457bd 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRendererRenderGraph.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRendererRenderGraph.cs @@ -364,6 +364,8 @@ bool RequiresIntermediateAttachments(UniversalCameraData cameraData, in RenderPa requireColorTexture |= HasPassesRequiringIntermediateTexture(activeRenderPassQueue); requireColorTexture |= RequiresIntermediateColorTexture(cameraData, in renderPassInputs, usesDeferredLighting, applyPostProcessing); requireColorTexture |= overlayUIRequiresComposition; + requireColorTexture |= DebugHandler != null && DebugHandler.RequiresIntermediateTexture(cameraData.isPreviewCamera) && + !(useTileOnlyMode && cameraData.resolveToScreen); bool requestedDepthHistory = (cameraData.historyManager == null) ? false : cameraData.historyManager.IsAccessRequested(); @@ -526,7 +528,11 @@ void ClearCameraTargets(RenderGraph renderGraph, UniversalResourceData resourceD // The clear pass is only required if either color or depth needs clearing. var clearParams = GetClearCameraParams(cameraData); if (clearParams.mustClearColor || clearParams.mustClearDepth) - InitializeCameraTargetsPass.Render(renderGraph, resourceData.activeColorTexture, resourceData.activeDepthTexture); + { + InitializeCameraTargetsPass.Render(renderGraph, + clearParams.mustClearColor ? resourceData.activeColorTexture : TextureHandle.nullHandle, + clearParams.mustClearDepth ? resourceData.activeDepthTexture : TextureHandle.nullHandle); + } } void SetupTargetHandles(UniversalCameraData cameraData) @@ -712,16 +718,16 @@ void UpdateGlobalShaderVariables() // mask, so pushing or restoring the defaults only re-sends those variables instead of all of them. var uploader = m_GlobalShaderVariablesUploader; - // Misc. Only written when a pass consuming the rendering layers texture is recorded, like the loose - // uniform path, which set it from those passes. - if (m_RequiresRenderingLayer) + // Misc. Only written when a pass encodes the rendering layers. + if (m_RequiresRenderingLayer || (usesDeferredLighting && m_DeferredLights.UseRenderingLayers)) uploader._RenderingLayerMaxInt = RenderingLayerUtils.GetMaxInt(m_RenderingLayersMaskSize); // Motion vectors. Update() already ran for this camera before the record, so the matrices are final here. // Left out under XR single pass: there the shaders resolve both names onto the per eye Stereo arrays that // MotionVectorRenderPass sets, so filling these two would upload values nothing reads. bool isXRSinglePass = cameraData.xr.enabled && cameraData.xr.singlePassEnabled; - if (!isXRSinglePass && cameraData.camera.TryGetComponent(out var additionalCameraData)) + var additionalCameraData = cameraData.additionalCameraData; + if (!isXRSinglePass && additionalCameraData != null) { var motionData = additionalCameraData.motionVectorsPersistentData; uploader._NonJitteredViewProjMatrix = motionData.GetViewProjectionNoJitter(cameraData.xr); @@ -733,7 +739,7 @@ void UpdateGlobalShaderVariables() // Shadows ShadowPassGroup shadowPassGroup = GetShadowPassGroup(cameraData, shadowData); - shadowPassGroup.mainLightShadowmapPass.UpdateGlobalShaderVariables(uploader, lightData, shadowData); + shadowPassGroup.mainLightShadowmapPass.UpdateGlobalShaderVariables(uploader, cameraData, lightData, shadowData); shadowPassGroup.additionalLightShadowmapPass.UpdateGlobalShaderVariables(uploader, shadowData.supportsSoftShadows); } @@ -747,7 +753,7 @@ private class InitPassData private class SetupPassData { internal UniversalCameraData cameraData; - // The classic interface from shaderData.Get() always pushes every group, this specific render func needs Base alone but this is an exception not the norm. + // The internal uploader, for PushAfterCameraSetup(), which the public interfaces don't have. internal GlobalShaderVariablesUploader uploader; internal TextureHandle target; }; @@ -781,7 +787,7 @@ internal override void InitRenderGraphFrame(RenderGraph renderGraph) cmd.SetGlobalVector(SSAOUtils.ShaderConstants._AmbientOcclusionParam, Vector4.zero); cmd.SetGlobalVector(ScreenSpaceReflectionPass.ShaderConstants._ReflectionParam, Vector4.zero); - data.shaderData.Get().PushDefaultToGlobal(cmd); + data.shaderData.GetGlobal().PushDefault(cmd); // The shadow passes are not recorded when shadows are disabled, so set them here instead. data.shadowPassGroup.mainLightShadowmapPass.ApplyEmptyShadowmapGlobals(cmd); @@ -812,6 +818,7 @@ static void InitGlobalKeywords(IBaseCommandBuffer cmd, UniversalCameraData camer cmd.SetKeyword(ShaderGlobalKeywords.SoftShadowsLow, false); cmd.SetKeyword(ShaderGlobalKeywords.SoftShadowsMedium, false); cmd.SetKeyword(ShaderGlobalKeywords.SoftShadowsHigh, false); + cmd.SetKeyword(ShaderGlobalKeywords.ShadowsPCSS, false); cmd.SetKeyword(ShaderGlobalKeywords.MixedLightingSubtractive, false); cmd.SetKeyword(ShaderGlobalKeywords.LightmapShadowMixing, false); cmd.SetKeyword(ShaderGlobalKeywords.ShadowsShadowMask, false); @@ -849,9 +856,7 @@ void SetupRenderGraphCameraProperties(RenderGraph renderGraph, in TextureHandle SetupCameraProperties(context, data.cameraData, isTargetFlipped); - // Push the base vars again, some were re-written by cmd.SetupCameraProperties() above. Base group - // only: the native call cannot touch the 3D vars, their names are URP-specific, and we don't want to call setGlobals with all default 3D vars again for nothing. - data.uploader.PushDefaultToGlobal(context.cmd, GlobalShaderVariablesGroup.Base); + data.uploader.PushAfterCameraSetup(context.cmd); }); } } @@ -905,13 +910,16 @@ internal override void OnRecordRenderGraph(RenderGraph renderGraph, ScriptableRe // * Similar reasoning as for drawShadowPasses - GBuffer is public frame data so custom passes that don't // respect opaqueLayerMask can draw to it (e.g. DecalGBufferRenderPass or custom gbuffer passes). drawDeferredLightingPass = cameraCullingMask != 0, + + // depthTextureProducedByPrepass: + // * The prepass produces the camera depth texture directly instead of it being copied from the depth attachment. + // If the prepass is not drawn, depth texture is cleared. + depthTextureProducedByPrepass = requirePrepassForTextures && !usesDeferredLighting && !useDepthPriming, }; // Only use a depth format when we do a prepass directly to the cameraDepthTexture, or if R32F color format is not supported. If we do depth priming (ie, prepass to the activeCameraDepth), we don't do a prepass to the texture. Instead, we do a copy from the primed attachment. - // The prepass must also actually execute (drawPrepass); if it's skipped due to empty layer masks, the cameraDepthTexture is never written by the prepass. - bool prepassToCameraDepthTexture = renderStages.drawPrepass && requirePrepassForTextures && !usesDeferredLighting && !useDepthPriming; - bool depthTextureIsDepthFormat = prepassToCameraDepthTexture || !PlatformAutoDetect.hasRenderToR32F; - bool requireCopyFromDepth = renderPassInputs.requiresDepthTexture && !prepassToCameraDepthTexture; + bool depthTextureIsDepthFormat = renderStages.depthTextureProducedByPrepass || !PlatformAutoDetect.hasRenderToR32F; + bool requireCopyFromDepth = renderPassInputs.requiresDepthTexture && !renderStages.depthTextureProducedByPrepass; // We configure this for the first camera of the stack and overlay camera will reuse create color/depth var // to pick the correct target, as if there is an intermediate texture, overlay cam should use them @@ -919,7 +927,7 @@ internal override void OnRecordRenderGraph(RenderGraph renderGraph, ScriptableRe s_RequiresIntermediateAttachments = RequiresIntermediateAttachments(cameraData, in renderPassInputs, requireCopyFromDepth, applyPostProcessing, m_DrawOverlayUIPass.RequiresComposition()); // Report this camera's real back buffer MSAA need to the pipeline. - ReportRealBackbufferMSAA(cameraData, s_RequiresIntermediateAttachments); + ReportDisplayTargetMSAA(cameraData, s_RequiresIntermediateAttachments); CreateRenderGraphCameraRenderTargets(renderGraph, isCameraTargetOffscreenDepth, s_RequiresIntermediateAttachments, depthTextureIsDepthFormat); m_ExposurePass.RecordRenderGraph(renderGraph, frameData); @@ -961,6 +969,8 @@ internal override void OnRecordRenderGraph(RenderGraph renderGraph, ScriptableRe OnAfterRendering(renderGraph, applyPostProcessing); EndRenderGraphXRRendering(renderGraph); + + m_ForwardLights.UploadRenderGraphClusteringData(renderGraph); } /// @@ -984,6 +994,10 @@ public override void OnEndRenderGraphFrame() internal override void OnFinishRenderGraphRendering(CommandBuffer cmd) { + // No-op after a normal frame; frees what an aborted recording or execution left behind. + if (usesClusterLightLoop) + m_ForwardLights.DisposeClusteringData(); + if (usesDeferredLighting) m_DeferredPass.OnCameraCleanup(cmd); @@ -1156,7 +1170,7 @@ private void RecordCustomPassesWithDepthCopyAndMotion(RenderGraph renderGraph, U // During a partial prepass, we only render forward opaque objects that aren't rendered into the gbuffer. // This produces a set of partial depth & normal buffers that must be completed by the gbuffer pass later in the frame. // This allows us to produce complete depth & normals data before lighting takes place, but it isn't valid when custom - // passes require this data before the gbuffer pass finishes. + // passes require this data before the gbuffer pass finishes (see CalculateDepthCopySchedule). private static bool AllowPartialDepthNormalsPrepass(bool isDeferred, RenderPassInputSummary renderPassInputSummary, bool useDepthPriming) { bool requiresDepthAfterGbuffer = RenderPassEvent.AfterRenderingGbuffer <= renderPassInputSummary.requiresDepthTextureEarliestEvent; @@ -1218,7 +1232,7 @@ static private DepthCopySchedule CalculateDepthCopySchedule(RenderPassEvent earl return schedule; } - private DepthCopySchedule CalculateDepthCopySchedules(UniversalCameraData cameraData, in RenderPassInputSummary renderPassInputs, bool isDeferred, bool requiresDepthPrepass, bool hasFullPrepass) + private static DepthCopySchedule CalculateDepthCopySchedules(in RenderPassInputSummary renderPassInputs, bool depthTextureProducedByPrepass) { // Assume the depth texture is unused and no copy is needed until we determine otherwise DepthCopySchedule depth = DepthCopySchedule.None; @@ -1226,23 +1240,14 @@ private DepthCopySchedule CalculateDepthCopySchedules(UniversalCameraData camera // If the depth texture is read during the frame, determine when the copy should occur if (renderPassInputs.requiresDepthTexture) { - //The prepass will render directly to the depthTexture when not using depth priming. Therefore we don't need a copy in that case. - bool depthTextureRequiresCopy = isDeferred || (!requiresDepthPrepass || useDepthPriming); - - if (depthTextureRequiresCopy) + if (depthTextureProducedByPrepass) { - // A depth read before the GBuffer is served by a copy right after the prepass, so the prepass has - // to be a full one. A missing prepass (e.g. an empty camera culling mask) is not a bug: depth - // simply isn't available before the GBuffer in that case. - Debug.Assert(renderPassInputs.requiresDepthTextureEarliestEvent >= RenderPassEvent.AfterRenderingGbuffer - || !requiresDepthPrepass - || hasFullPrepass, "Doing a partial prepass when the full depth data is needed before 'AfterRenderingGBuffer'"); - - depth = CalculateDepthCopySchedule(renderPassInputs.requiresDepthTextureEarliestEvent); + // The prepass will render directly to the depthTexture when not using depth priming. Therefore we don't need a copy in that case. + depth = DepthCopySchedule.DuringPrepass; } else { - depth = DepthCopySchedule.DuringPrepass; + depth = CalculateDepthCopySchedule(renderPassInputs.requiresDepthTextureEarliestEvent); } } return depth; @@ -1279,15 +1284,10 @@ private void OnMainRendering(RenderGraph renderGraph, ScriptableRenderContext co RecordCustomRenderGraphPasses(renderGraph, RenderPassEvent.BeforeRenderingPrePasses); - bool isDepthOnlyPrepass = renderStages.drawPrepass && !renderPassInputs.requiresNormalsTexture; bool isDepthNormalPrepass = renderStages.drawPrepass && renderPassInputs.requiresNormalsTexture; - // The depth prepass is considered "full" (renders the entire scene, not a partial subset), when we either: - // - Have a depth only prepass (URP always renders the full scene in depth only mode) - // - Have a depth normals prepass that does not allow the partial prepass optimization - bool hasFullPrepass = isDepthOnlyPrepass || (isDepthNormalPrepass && !AllowPartialDepthNormalsPrepass(usesDeferredLighting, renderPassInputs, useDepthPriming)); - - var depthCopySchedule = CalculateDepthCopySchedules(cameraData, renderPassInputs, usesDeferredLighting, renderStages.drawPrepass, hasFullPrepass); + bool hasPartialPrepass = isDepthNormalPrepass && AllowPartialDepthNormalsPrepass(usesDeferredLighting, renderPassInputs, useDepthPriming); + var depthCopySchedule = CalculateDepthCopySchedules(renderPassInputs, renderStages.depthTextureProducedByPrepass); // Decide if & when to use GPU Occlusion Culling. // In deferred, do it during gbuffer laydown unless we are forced to do a *full* prepass by a render pass. @@ -1345,7 +1345,7 @@ private void OnMainRendering(RenderGraph renderGraph, ScriptableRenderContext co // There's no special copy logic for the camera normals texture, so we can set the global as long as we're not performing a partial prepass. // In the case of a partial prepass, the global will be set later by the gbuffer pass once it completes the data in the texture. - bool setGlobalTextures = isLastPass && hasFullPrepass; + bool setGlobalTextures = isLastPass && !hasPartialPrepass; if (isDepthNormalPrepass) { @@ -1356,7 +1356,7 @@ private void OnMainRendering(RenderGraph renderGraph, ScriptableRenderContext co { SetupRenderGraphCameraProperties(renderGraph, depthTarget); } - DepthNormalPrepassRender(renderGraph, renderPassInputs, depthTarget, batchLayerMask, setGlobalDepth, setGlobalTextures, !hasFullPrepass); + DepthNormalPrepassRender(renderGraph, renderPassInputs, depthTarget, batchLayerMask, setGlobalDepth, setGlobalTextures, hasPartialPrepass); // Restore camera properties for the rest of the render graph execution. if (resourceData.isActiveTargetBackBuffer) { @@ -1376,6 +1376,14 @@ private void OnMainRendering(RenderGraph renderGraph, ScriptableRenderContext co } } } + else + { + // When a required prepass is skipped due to not rendering any geometry, clear & publish the textures it would have produced. + TextureHandle cameraDepthTexture = renderStages.depthTextureProducedByPrepass ? resourceData.cameraDepthTexture : TextureHandle.nullHandle; + TextureHandle cameraNormalsTexture = renderPassInputs.requiresNormalsTexture && !usesDeferredLighting ? resourceData.cameraNormalsTexture : TextureHandle.nullHandle; + TextureHandle renderingLayersTexture = !usesDeferredLighting && m_RenderingLayerProvidesByDepthNormalPass ? resourceData.renderingLayersTexture : TextureHandle.nullHandle; + PublishPrepassGlobalTexturesPass.Render(renderGraph, cameraDepthTexture, cameraNormalsTexture, renderingLayersTexture); + } // After the prepass completes, we should copy depth if necessary and also render motion vectors. (they're expected to be available whenever depth is) // In the case where depth is rendered as part of the prepass and no copy is necessary, we still need to render motion vectors here to ensure they're available @@ -1397,7 +1405,8 @@ private void OnMainRendering(RenderGraph renderGraph, ScriptableRenderContext co m_DeferredLights.ResolveMixedLightingMode(lightData); // Once the mixed lighting mode has been discovered, we know how many MRTs we need for the gbuffer. // Subtractive mixed lighting requires shadowMask output, which is actually used to store unity_ProbesOcclusion values. - m_DeferredLights.CreateGbufferTextures(renderGraph, resourceData, cameraData, isDepthNormalPrepass); + // Render into the camera normals texture whenever normals are required, so it's produced even if the prepass is skipped. + m_DeferredLights.CreateGbufferTextures(renderGraph, resourceData, cameraData, renderPassInputs.requiresNormalsTexture); m_ValidationHandler.OnBeforeGBuffers(renderGraph, resourceData); @@ -1419,7 +1428,8 @@ private void OnMainRendering(RenderGraph renderGraph, ScriptableRenderContext co // When we have a partial depth normals prepass, we must wait until the gbuffer pass to set global textures. // In this case, the incoming global texture data is incomplete and the gbuffer pass is required to complete it. - bool setGlobalTextures = isDepthNormalPrepass && !hasFullPrepass; + // When the prepass is skipped, the gbuffer pass is the only producer of these textures. + bool setGlobalTextures = hasPartialPrepass || (!renderStages.drawPrepass && renderPassInputs.requiresNormalsTexture); #if ENABLE_VR && ENABLE_XR_MODULE // Draw the inset depth occluder only once before the first GBuffer sub-pass. // The near-plane depth values it writes persist into subsequent sub-passes because depth is never cleared or invalidated between them @@ -1494,7 +1504,6 @@ private void OnMainRendering(RenderGraph renderGraph, ScriptableRenderContext co resourceData.activeDepthTexture, resourceData.mainShadowsTexture, resourceData.additionalShadowsTexture, - m_RenderingLayersMaskSize, batchLayerMask); } else @@ -1657,7 +1666,7 @@ private void OnAfterRendering(RenderGraph renderGraph, bool applyPostProcessing) IUpscaler activeUpscaler = postProcessingData.activeUpscaler; bool requiresFinalPostUpscale = cameraData.resolvedUpscalerHash == UniversalRenderPipeline.k_UpscalerHash_FSR1 || (activeUpscaler != null && !activeUpscaler.isTemporal && !postProcessingData.activeUpscalerIsEmbedded); - + // When FXAA or scaling is active, we must perform an additional pass at the end of the frame for the following reasons: // 1. FXAA expects to be the last shader running on the image before it's presented to the screen. Since users are allowed // to add additional render passes after post processing occurs, we can't run FXAA until all of those passes complete as well. @@ -1914,8 +1923,8 @@ static bool IsDepthPrimingEnabledRenderGraph(UniversalCameraData cameraData, in if (renderPassInputs.requiresDepthTexture && !CanCopyDepth(cameraData)) return false; - // Depth Priming causes rendering errors with WebGL and WebGPU on Apple Arm64 GPUs. - bool isNotWebGL = !IsWebGL(); + // Depth Priming causes rendering errors with WebGL2 on Apple Arm64 GPUs. + bool isNotWebGL = !(IsWebGL() && IsGLDevice()); bool depthPrimingRequested = (depthPrimingRecommended && depthPrimingMode == DepthPrimingMode.Auto) || depthPrimingMode == DepthPrimingMode.Forced; bool isNotMSAA = cameraData.cameraTargetDescriptor.msaaSamples == 1; @@ -2193,7 +2202,6 @@ void DepthNormalPrepassRender(RenderGraph renderGraph, RenderPassInputSummary re if (m_RenderingLayerProvidesByDepthNormalPass) { m_DepthNormalPrepass.enableRenderingLayers = true; - m_DepthNormalPrepass.renderingLayersMaskSize = m_RenderingLayersMaskSize; } else { @@ -2278,4 +2286,44 @@ internal static void Render(RenderGraph graph, TextureHandle colorHandle, Textur } } + // Only publishes the textures that a prepass would normally publish, in the case where the actual prepass is not executed. + // The textures are bound as attachments so they are all cleared through load actions in a single render pass. + static class PublishPrepassGlobalTexturesPass + { + const string k_PassName = "Publish Prepass Global Textures"; + static readonly ProfilingSampler s_ProfilingSampler = new ProfilingSampler(k_PassName); + + private class PassData { } + + internal static void Render(RenderGraph graph, TextureHandle cameraDepthTexture, TextureHandle cameraNormalsTexture, TextureHandle renderingLayersTexture) + { + if (!cameraDepthTexture.IsValid() && !cameraNormalsTexture.IsValid() && !renderingLayersTexture.IsValid()) + return; + + using (var builder = graph.AddRasterRenderPass(k_PassName, out _, s_ProfilingSampler)) + { + int colorIndex = 0; + if (cameraDepthTexture.IsValid()) + { + builder.SetRenderAttachmentDepth(cameraDepthTexture, AccessFlags.Write); + builder.SetGlobalTextureAfterPass(cameraDepthTexture, DepthOnlyPass.s_CameraDepthTextureID); + } + if (cameraNormalsTexture.IsValid()) + { + builder.SetRenderAttachment(cameraNormalsTexture, colorIndex++, AccessFlags.Write); + builder.SetGlobalTextureAfterPass(cameraNormalsTexture, DepthNormalOnlyPass.s_CameraNormalsTextureID); + } + if (renderingLayersTexture.IsValid()) + { + builder.SetRenderAttachment(renderingLayersTexture, colorIndex++, AccessFlags.Write); + builder.SetGlobalTextureAfterPass(renderingLayersTexture, DepthNormalOnlyPass.s_CameraRenderingLayersTextureID); + } + + builder.AllowGlobalStateModification(true); + + builder.SetRenderFunc(static (PassData _, RasterGraphContext _) => { }); + } + } + } + } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/VFXGraph/Shaders/VFXLit.hlsl b/Packages/com.unity.render-pipelines.universal/Runtime/VFXGraph/Shaders/VFXLit.hlsl index 4275f311857..aaabcfc2738 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/VFXGraph/Shaders/VFXLit.hlsl +++ b/Packages/com.unity.render-pipelines.universal/Runtime/VFXGraph/Shaders/VFXLit.hlsl @@ -3,8 +3,6 @@ #error SHADERPASS must be defined (at) this point #endif -#include "Packages/com.unity.render-pipelines.universal/Shaders/Utils/SurfaceType.hlsl" - #if VFX_MATERIAL_TYPE_SIX_WAY_SMOKE #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/SixWayLighting.hlsl" #include "Packages/com.unity.visualeffectgraph/Shaders/SixWay/VFXSixWayCommon.hlsl" @@ -22,7 +20,7 @@ float3 VFXGetPositionRWS(VFX_VARYING_PS_INPUTS i) return VFXGetPositionRWS(posWS); } -InputData VFXGetInputData(const VFX_VARYING_PS_INPUTS i, const PositionInputs posInputs, float3 normalWS, bool frontFace, out float3 geometricNormalWS) +InputData VFXGetInputData(const VFX_VARYING_PS_INPUTS i, const PositionInputs posInputs, float3 normalWS, bool frontFace) { InputData inputData = (InputData)0; @@ -34,9 +32,9 @@ InputData VFXGetInputData(const VFX_VARYING_PS_INPUTS i, const PositionInputs po #if USE_DOUBLE_SIDED geometricNormalSign = frontFace ? 1.0f : -1.0f; #endif - geometricNormalWS = geometricNormalSign * normalize(i.VFX_VARYING_NORMAL); + inputData.geometricNormalWS = geometricNormalSign * normalize(i.VFX_VARYING_NORMAL); #else - geometricNormalWS = normalWS; + inputData.geometricNormalWS = normalWS; #endif inputData.viewDirectionWS = GetWorldSpaceNormalizeViewDir(inputData.positionWS); inputData.positionCS = i.VFX_VARYING_POSCS; @@ -47,11 +45,17 @@ InputData VFXGetInputData(const VFX_VARYING_PS_INPUTS i, const PositionInputs po inputData.tangentToWorld = half3x3(i.VFX_VARYING_TANGENT.xyz, bitangent.xyz, signNormal * i.VFX_VARYING_NORMAL.xyz); #endif +#if IS_OPAQUE_PARTICLE + bool isSurfaceTypeTransparent = false; +#else + bool isSurfaceTypeTransparent = true; +#endif + //When there is only one cascaded, this shadowCoord can be computed at vertex stage //#if USE_VERTEX_SHADOW_COORD_INTERPOLATOR // inputData.shadowCoord = inputData.shadowCoord; if (MainLightShadowsAvailable()) - inputData.shadowCoord = TransformWorldToShadowCoord(inputData.positionWS, IsSurfaceTypeTransparent(), geometricNormalWS); + inputData.shadowCoord = TransformWorldToShadowCoord(inputData.positionWS, isSurfaceTypeTransparent, inputData.geometricNormalWS); else inputData.shadowCoord = float4(0, 0, 0, 0); diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/VFXGraph/Shaders/VFXLitPixelOutput.hlsl b/Packages/com.unity.render-pipelines.universal/Runtime/VFXGraph/Shaders/VFXLitPixelOutput.hlsl index 98877f40200..dd285289374 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/VFXGraph/Shaders/VFXLitPixelOutput.hlsl +++ b/Packages/com.unity.render-pipelines.universal/Runtime/VFXGraph/Shaders/VFXLitPixelOutput.hlsl @@ -9,15 +9,15 @@ #if (SHADERPASS == SHADERPASS_FORWARD) -float4 VFXCalcPixelOutputForward(const VFX_VARYING_PS_INPUTS i, SurfaceData surfaceData, InputData inputData, float3 geometricNormalWS) +float4 VFXCalcPixelOutputForward(const VFX_VARYING_PS_INPUTS i, SurfaceData surfaceData, InputData inputData) { #if VFX_MATERIAL_TYPE_SIX_WAY_SMOKE - URP_LIGHT_ACCUM4 color = UniversalFragmentSixWay(inputData, surfaceData, geometricNormalWS); + URP_LIGHT_ACCUM4 color = UniversalFragmentSixWay(inputData, surfaceData); #else #if defined(_DBUFFER) && !defined(_SURFACE_TYPE_TRANSPARENT) ApplyDecalToSurfaceData(i.VFX_VARYING_POSCS, surfaceData, inputData); #endif - URP_LIGHT_ACCUM4 color = UniversalFragmentPBR(inputData, surfaceData, geometricNormalWS); + URP_LIGHT_ACCUM4 color = UniversalFragmentPBR(inputData, surfaceData); #endif color.rgb = ClampExposed(inputData.preExposureMultiplier * BlendDistanceFog(color.rgb, i.VFX_VARYING_POSCS)); @@ -42,10 +42,9 @@ float4 VFXGetPixelOutputForward(const VFX_VARYING_PS_INPUTS i, float3 normalWS, { SurfaceData surfaceData; InputData inputData; - float3 geometricNormalWS; - VFXGetURPLitData(surfaceData, inputData, i, normalWS, uvData, frontFace, (uint2)0, geometricNormalWS); - return VFXCalcPixelOutputForward(i, surfaceData, inputData, geometricNormalWS); + VFXGetURPLitData(surfaceData, inputData, i, normalWS, uvData, frontFace, (uint2)0); + return VFXCalcPixelOutputForward(i, surfaceData, inputData); } #else @@ -57,10 +56,9 @@ float4 VFXGetPixelOutputForwardShaderGraph(const VFX_VARYING_PS_INPUTS i, Surfac PositionInputs posInput = GetPositionInput(posSS.xy, _ScreenSize.zw, posSS.z, posSS.w, posRWS, (uint2)0); VFXUVData uvData = (VFXUVData)0; - float3 geometricNormalWS; - InputData inputData = VFXGetInputData(i, posInput, normalWS, frontFace, geometricNormalWS); + InputData inputData = VFXGetInputData(i, posInput, normalWS, frontFace); - return VFXCalcPixelOutputForward(i, surfaceData, inputData, geometricNormalWS); + return VFXCalcPixelOutputForward(i, surfaceData, inputData); } #endif @@ -71,8 +69,7 @@ void VFXComputePixelOutputToGBuffer(const VFX_VARYING_PS_INPUTS i, const float3 { SurfaceData surfaceData; InputData inputData; - float3 unusedGeometricNormalWS; - VFXGetURPLitData(surfaceData, inputData, i, normalWS, uvData, true, (uint2)0, unusedGeometricNormalWS); + VFXGetURPLitData(surfaceData, inputData, i, normalWS, uvData, true, (uint2)0); BRDFData brdfData; InitializeBRDFData(surfaceData.albedo, surfaceData.metallic, surfaceData.specular, surfaceData.smoothness, surfaceData.alpha, brdfData); @@ -96,8 +93,7 @@ void VFXComputePixelOutputToGBufferShaderGraph(const VFX_VARYING_PS_INPUTS i, Su PositionInputs posInput = GetPositionInput(posSS.xy, _ScreenSize.zw, posSS.z, posSS.w, posRWS, (uint2)0); VFXUVData uvData = (VFXUVData)0; - float3 unusedGeometricNormalWS; - InputData inputData = VFXGetInputData(i, posInput, normalWS, true, unusedGeometricNormalWS); + InputData inputData = VFXGetInputData(i, posInput, normalWS, true); BRDFData brdfData; InitializeBRDFData(surfaceData.albedo, surfaceData.metallic, surfaceData.specular, surfaceData.smoothness, surfaceData.alpha, brdfData); diff --git a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/BRDF.hlsl b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/BRDF.hlsl index 29395cb71ec..76419c1dcbe 100644 --- a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/BRDF.hlsl +++ b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/BRDF.hlsl @@ -152,7 +152,7 @@ half3 EnvironmentBRDFSpecular(BRDFData brdfData, half fresnelTerm) return half3(surfaceReduction * lerp(brdfData.specular, brdfData.grazingTerm, fresnelTerm)); } -URP_LIGHT_ACCUM3 EnvironmentBRDF(BRDFData brdfData, URP_LIGHT_ACCUM3 indirectDiffuse, half3 indirectSpecular, half fresnelTerm) +URP_LIGHT_ACCUM3 EnvironmentBRDF(BRDFData brdfData, URP_LIGHT_ACCUM3 indirectDiffuse, URP_LIGHT_ACCUM3 indirectSpecular, half fresnelTerm) { URP_LIGHT_ACCUM3 c = indirectDiffuse * brdfData.diffuse; c += indirectSpecular * EnvironmentBRDFSpecular(brdfData, fresnelTerm); @@ -160,7 +160,7 @@ URP_LIGHT_ACCUM3 EnvironmentBRDF(BRDFData brdfData, URP_LIGHT_ACCUM3 indirectDif } // Environment BRDF without diffuse for clear coat -half3 EnvironmentBRDFClearCoat(BRDFData brdfData, half clearCoatMask, half3 indirectSpecular, half fresnelTerm) +URP_LIGHT_ACCUM3 EnvironmentBRDFClearCoat(BRDFData brdfData, half clearCoatMask, URP_LIGHT_ACCUM3 indirectSpecular, half fresnelTerm) { return indirectSpecular * EnvironmentBRDFSpecular(brdfData, fresnelTerm) * clearCoatMask; } diff --git a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/ComputeScreenSpaceReflection.hlsl b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/ComputeScreenSpaceReflection.hlsl index 2d41ccb7b90..53de00ab260 100644 --- a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/ComputeScreenSpaceReflection.hlsl +++ b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/ComputeScreenSpaceReflection.hlsl @@ -6,6 +6,7 @@ #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/ShaderVariablesFunctions.hlsl" #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/DeclareDepthTexture.hlsl" #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/DeclareNormalsTexture.hlsl" +#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Debug.hlsl" #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/FoveatedRendering.hlsl" #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/ImageBasedLighting.hlsl" #include "Packages/com.unity.render-pipelines.core/Runtime/Utilities/Blit.hlsl" @@ -357,15 +358,16 @@ bool TraceScreenSpaceRayHiZ( // 'distFloor' can be smaller than the current distance 't'. // We can also safely ignore 'distBase'. - // If we hit the floor, it's always safe to jump there. - // If we are at (mipLevel != 0) and we are below the floor, we should not move. - t = hitFloor ? distFloor : (((mipLevel != 0) && belowFloor) ? t : distWall); + // If we are at (mipLevel != 0) and we are below the floor, we should not move, + // as jumping to the floor could skip intersections with finer cells. + // Otherwise, if we hit the floor, it's safe to jump there. + t = ((mipLevel != 0) && belowFloor) ? t : (hitFloor ? distFloor : distWall); rayPos.z = bounds.z; // Retain the depth of the potential intersection - // Warning: both rays towards the eye, and tracing behind objects has linear + // Warning: tracing behind objects has linear // rather than logarithmic complexity! This is due to the fact that we only store // the maximum value of depth, and not the min-max. - mipLevel += (hitFloor || belowFloor || rayTowardsEye) ? -1 : 1; + mipLevel += (hitFloor || belowFloor) ? -1 : 1; mipLevel = clamp(mipLevel, 0, maxMipLevel); // mipLevel = 0; @@ -722,4 +724,149 @@ float4 SSRTemporalFiltering(Varyings input) : SV_Target return lerp(current, history, blendFactor); } +// ------------------------------------------------------------------ +// Debug Visualization +// ------------------------------------------------------------------ +static const int SSR_DEBUG_VIEW_MODE_REFLECTIONS = 1; +static const int SSR_DEBUG_VIEW_MODE_RAW_REFLECTIONS = 2; +static const int SSR_DEBUG_VIEW_MODE_CONFIDENCE = 3; +static const int SSR_DEBUG_VIEW_MODE_RAW_CONFIDENCE = 4; +static const int SSR_DEBUG_VIEW_MODE_MIP_LEVEL = 5; +static const int SSR_DEBUG_VIEW_MODE_SMOOTHNESS = 6; +static const int SSR_DEBUG_VIEW_MODE_CONTACT_HARDENING_FACTOR = 7; +static const int SSR_DEBUG_VIEW_MODE_RAY_DISTANCE = 8; + +float4 _DebugParams; + +float3 GetSSRDebugHeatmapColor(float t) +{ + float3 r = saturate(t) * 2.1f - float3(1.8f, 1.14f, 0.3f); + return 1.0f - r * r; +} + +float3 GetSSRDebugSmoothnessColor(float perceptualSmoothness) +{ + float3 color = perceptualSmoothness; + if (perceptualSmoothness < GetMinimumSmoothness()) + color.r = 1; + return color; +} + +bool DrawSSRDebugLegend(float2 uv, uint maxValue, inout float3 color, out float barValue) +{ + const float2 pixelSize = max(1, round(_ScreenSize.y / 1080)) * _ScreenSize.zw; + const float2 barMin = float2(0.02, 18 * pixelSize.y); + const float2 barSize = float2(0.96, 16 * pixelSize.y); + const float2 barCoord = (uv - barMin) / barSize; + barValue = barCoord.x; + if (uv.y > barMin.y + barSize.y + 8 * pixelSize.y) + return false; + if (all(barCoord >= 0) && all(barCoord <= 1)) + return true; + + const uint labelCount = min(maxValue, 8); + const uint labelValue = round(round(saturate(barCoord.x) * labelCount) * maxValue / labelCount); + const float labelX = barMin.x + barSize.x * labelValue / maxValue; + const int2 labelPixel = int2((uv.x - labelX) / pixelSize.x + 8, uv.y / pixelSize.y); + + color *= 0.075; + if (barCoord.y < 0 && SampleDebugFontNumber2Digits(labelPixel, labelValue)) + color = 1; + return false; +} + +float4 SSRDebug(Varyings input) : SV_Target +{ + UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input); + + const float sourceLastMipIndex = _DebugParams.x; + const float rayDistanceRange = _DebugParams.y; + const int viewMode = _DebugParams.w; + const bool showSceneColor = _DebugParams.z > 0 && (viewMode == SSR_DEBUG_VIEW_MODE_REFLECTIONS || viewMode == SSR_DEBUG_VIEW_MODE_RAW_REFLECTIONS); + + const float2 uv = input.texcoord; + const float2 sceneColorUV = (uv - SampleMotionVector(uv)) * GetHistoryResolutionScale(); + const float3 sceneColor = SAMPLE_TEXTURE2D_X_LOD(_CameraColorTexture, sampler_LinearClamp, sceneColorUV, 0).rgb * showSceneColor; + + const float deviceDepth = SampleSceneDepth(uv).r; + const float3 positionWS = ComputeWorldSpacePosition(uv, deviceDepth, _CameraInverseViewProjections[unity_eyeIndex]); + + const float perceptualSmoothness = SampleSmoothness(uv); + const float perceptualRoughness = PerceptualSmoothnessToPerceptualRoughness(perceptualSmoothness); + const float smoothnessFade = smoothstep(_ScreenSpaceReflectionParam.y, _ScreenSpaceReflectionParam.z, perceptualSmoothness); + const bool isTraced = perceptualSmoothness >= GetMinimumSmoothness(); + const bool isReflective = smoothnessFade > 1e-3; + + const float lastMipIndex = min(GetSSRTextureLastValidMipIndex(), sourceLastMipIndex); + const float mipLevel = min(GetSSRMipLevelFromPerceptualRoughness(positionWS, perceptualRoughness, uv), lastMipIndex); + const float4 reflColor = SAMPLE_TEXTURE2D_X_LOD(_BlitTexture, sampler_TrilinearClamp, uv, mipLevel); + const float4 rawReflColor = SAMPLE_TEXTURE2D_X_LOD(_BlitTexture, sampler_TrilinearClamp, uv, 0) * isTraced; + + float3 output = 0; + float coverage = 0; + float legendValue = 0; + if (viewMode == SSR_DEBUG_VIEW_MODE_REFLECTIONS) + { + output = reflColor.rgb * smoothnessFade; + coverage = reflColor.a * smoothnessFade; + } + else if (viewMode == SSR_DEBUG_VIEW_MODE_RAW_REFLECTIONS) + { + output = rawReflColor.rgb; + coverage = rawReflColor.a; + } + else if (viewMode == SSR_DEBUG_VIEW_MODE_CONFIDENCE) + { + output = reflColor.a * smoothnessFade; + + if (DrawSSRDebugLegend(uv, 1, output, legendValue)) + output = legendValue; + } + else if (viewMode == SSR_DEBUG_VIEW_MODE_RAW_CONFIDENCE) + { + output = rawReflColor.a; + + if (DrawSSRDebugLegend(uv, 1, output, legendValue)) + output = legendValue; + } + else if (viewMode == SSR_DEBUG_VIEW_MODE_MIP_LEVEL) + { + output = GetSSRDebugHeatmapColor(mipLevel * rcp(max(lastMipIndex, 1))) * isReflective; + + if (DrawSSRDebugLegend(uv, lastMipIndex, output, legendValue)) + output = GetSSRDebugHeatmapColor(legendValue); + } + else if (viewMode == SSR_DEBUG_VIEW_MODE_SMOOTHNESS) + { + output = GetSSRDebugSmoothnessColor(perceptualSmoothness); + + if (DrawSSRDebugLegend(uv, 1, output, legendValue)) + output = GetSSRDebugSmoothnessColor(legendValue); + } + else if (viewMode == SSR_DEBUG_VIEW_MODE_CONTACT_HARDENING_FACTOR) + { + const float roughnessBlurRadius = GetSSRBlurriness() * tan(GetSSRBlurConeHalfAngle(perceptualRoughness)); + float contactFactor = 1.0; + if (roughnessBlurRadius > FLT_EPS) + contactFactor = GetSSRBlurRadiusFromPerceptualRoughness(positionWS, perceptualRoughness, uv) / roughnessBlurRadius; + output = GetSSRDebugHeatmapColor(contactFactor) * isReflective; + + if (DrawSSRDebugLegend(uv, 1, output, legendValue)) + output = GetSSRDebugHeatmapColor(legendValue); + } + else if (viewMode == SSR_DEBUG_VIEW_MODE_RAY_DISTANCE) + { + const float4 rayDistancesAndValidity = SAMPLE_TEXTURE2D_X_LOD(_ScreenSpaceReflectionRayDistanceTexture, sampler_PointClamp, uv, 0); + if (rayDistancesAndValidity.w > 0) + output = GetSSRDebugHeatmapColor(1); + else if (rayDistancesAndValidity.z > 0) + output = GetSSRDebugHeatmapColor(rayDistancesAndValidity.x / rayDistanceRange); + + if (DrawSSRDebugLegend(uv, round(rayDistanceRange), output, legendValue)) + output = GetSSRDebugHeatmapColor(legendValue); + } + + return float4(output + sceneColor * (1 - coverage), 1); +} + #endif //UNIVERSAL_SSR_INCLUDED diff --git a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Debug/Debugging3D.hlsl b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Debug/Debugging3D.hlsl index c4b50df28fb..8f9a1a7277c 100644 --- a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Debug/Debugging3D.hlsl +++ b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Debug/Debugging3D.hlsl @@ -15,6 +15,7 @@ #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Shadows.hlsl" #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/SurfaceData.hlsl" #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/DeclareExposureTexture.hlsl" +#include "Packages/com.unity.render-pipelines.universal/Runtime/Debug/ShadowCachingDebugState.cs.hlsl" #define TERRAIN_STREAM_INFO float4(0.0f, 0.0f, float(6 | (4 << 4)), 0.0f) // 0-15 are reserved for per-texture codes (use "6" to indicate terrain); per-material code "4" signifies "warnings/issues" #define SETUP_DEBUG_TEXTURE_DATA(inputData, uv) SetupDebugDataTexture(inputData, TRANSFORM_TEX(uv.xy, unity_MipmapStreaming_DebugTex), unity_MipmapStreaming_DebugTex_TexelSize, unity_MipmapStreaming_DebugTex_MipInfo, unity_MipmapStreaming_DebugTex_StreamInfo, unity_MipmapStreaming_DebugTex) @@ -251,6 +252,32 @@ half3 CalculateDebugShadowCascadeColor(in InputData inputData) } } +static const half3 kDebugColorOkabeItoOrange = half3(0.791, 0.347, 0.000); +static const half3 kDebugColorOkabeItoSkyBlue = half3(0.093, 0.456, 0.815); +static const half3 kDebugColorOkabeItoBlue = half3(0.000, 0.168, 0.445); +static const half3 kDebugColorOkabeItoVermillion = half3(0.665, 0.112, 0.000); + +half3 GetDebugShadowCachingStateColor(int state) +{ + switch (state) + { + case SHADOWCACHINGDEBUGSTATE_CACHED: return kDebugColorOkabeItoOrange; + case SHADOWCACHINGDEBUGSTATE_RECENTLY_REFRESHED: return kDebugColorOkabeItoSkyBlue; + case SHADOWCACHINGDEBUGSTATE_LIVE: return kDebugColorOkabeItoBlue; + case SHADOWCACHINGDEBUGSTATE_STALE: return kDebugColorOkabeItoVermillion; + default: return kDebugColorBlack.rgb; + } +} + +void ApplyDebugShadowCachingForceState(int forceState, in InputData inputData, inout SurfaceData surfaceData) +{ + if (forceState == SHADOWCACHINGDEBUGSTATE_NONE || !MainLightShadowsAvailable()) + return; + + if (GetMainLightShadowFade(inputData.positionWS) < 1.0) + surfaceData.albedo = GetDebugShadowCachingStateColor(forceState); +} + half4 CalculateDebugLightingComplexityColor(in InputData inputData, in SurfaceData surfaceData) { #if USE_CLUSTER_LIGHT_LOOP @@ -337,6 +364,8 @@ bool CanDebugOverrideOutputColor(inout InputData inputData, inout SurfaceData su } } + ApplyDebugShadowCachingForceState(_DebugShadowCachingForceState, inputData, surfaceData); + // Update the BRDF data following any changes to the input/surface above... InitializeBRDFData(surfaceData, brdfData); @@ -388,6 +417,8 @@ bool CanDebugOverrideOutputColor(inout InputData inputData, inout SurfaceData su } } + ApplyDebugShadowCachingForceState(_DebugShadowCachingForceState, inputData, surfaceData); + half4 overrideColor = half4(0, 0, 0, 1); bool overridden = CalculateColorForDebug(inputData, surfaceData, overrideColor); debugColor = overrideColor; diff --git a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Debug/DebuggingCommon.hlsl b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Debug/DebuggingCommon.hlsl index 1f88686b9a3..9876d913c70 100644 --- a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Debug/DebuggingCommon.hlsl +++ b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Debug/DebuggingCommon.hlsl @@ -29,6 +29,7 @@ int _DebugValidationMode; // Lighting settings... int _DebugLightingMode; int _DebugLightingFeatureFlags; +int _DebugShadowCachingForceState; half _DebugValidateAlbedoMinLuminance = 0.01; half _DebugValidateAlbedoMaxLuminance = 0.90; diff --git a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/DistanceFog.hlsl b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/DistanceFog.hlsl index dd7557eedaa..3f8ba942eb9 100644 --- a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/DistanceFog.hlsl +++ b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/DistanceFog.hlsl @@ -171,7 +171,14 @@ float3 BlendDistanceFogFromEyeDepth(float3 color, float linearEyeDepth) return BlendDistanceFogColorFromEyeDepth(color, linearEyeDepth, unity_FogColor.rgb); } -URP_LIGHT_ACCUM3 BlendDistanceFogExposed(half3 color, float4 positionCS, float preExposureMultiplier) +// Blends 'color' with URP's active fog color, scaled by 'preExposureMultiplier'. +// Blending parameters are derived from fragment coordinates (SV_Position). +half3 BlendDistanceFogExposed(half3 color, float4 positionCS, float preExposureMultiplier) +{ + return BlendDistanceFogColor(color, positionCS, half3(unity_FogColor.rgb * preExposureMultiplier)); +} + +float3 BlendDistanceFogExposed(float3 color, float4 positionCS, float preExposureMultiplier) { return BlendDistanceFogColor(color, positionCS, unity_FogColor.rgb * preExposureMultiplier); } diff --git a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/GlobalIllumination.deprecated.hlsl b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/GlobalIllumination.deprecated.hlsl index b6f666cdf6a..c6922f144b4 100644 --- a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/GlobalIllumination.deprecated.hlsl +++ b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/GlobalIllumination.deprecated.hlsl @@ -16,8 +16,8 @@ URP_LIGHT_ACCUM3 GlobalIllumination(BRDFData brdfData, BRDFData brdfDataClearCoa URP_LIGHT_ACCUM3 GlobalIllumination(BRDFData brdfData, BRDFData brdfDataClearCoat, float clearCoatMask, URP_LIGHT_ACCUM3 bakedGI, half occlusion, half3 normalWS, half3 viewDirectionWS, bool clearCoatEnabled, bool environmentReflections); -half3 GlossyEnvironmentReflection(half3 reflectVector, float3 positionWS, half perceptualRoughness, half occlusion, float2 normalizedScreenSpaceUV, bool environmentReflections); -half3 GlossyEnvironmentReflection(half3 reflectVector, half perceptualRoughness, half occlusion, bool environmentReflections); +URP_LIGHT_ACCUM3 GlossyEnvironmentReflection(half3 reflectVector, float3 positionWS, half perceptualRoughness, half occlusion, float2 normalizedScreenSpaceUV, bool environmentReflections); +URP_LIGHT_ACCUM3 GlossyEnvironmentReflection(half3 reflectVector, half perceptualRoughness, half occlusion, bool environmentReflections); #if !defined(_CLEARCOAT_KEYWORD_DECLARED) #if !defined(_CLEARCOAT) diff --git a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/GlobalIllumination.hlsl b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/GlobalIllumination.hlsl index c3dc3aa1bb0..602e6f49207 100644 --- a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/GlobalIllumination.hlsl +++ b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/GlobalIllumination.hlsl @@ -379,15 +379,23 @@ float CalculateProbeWeight(float3 positionWS, float4 probeBoxMin, float4 probeBo return saturate(min(weightDir.x, min(weightDir.y, weightDir.z))); } +// Per-object probes carry their capture exposure (EV) in the decode bias (z). +// 2^EV leaves fp16 range past 15 EV, so it is evaluated and applied in float. +URP_LIGHT_ACCUM3 DecodeExposedProbe(half4 encodedIrradiance, real4 decodeInstructions) +{ + float exposureMultiplier = SelectProbeExposureMultiplier(exp2((float)decodeInstructions.z)); + return exposureMultiplier * DecodeHDREnvironment(encodedIrradiance, decodeInstructions); +} + half CalculateProbeVolumeSqrMagnitude(float4 probeBoxMin, float4 probeBoxMax) { half3 maxToMin = half3(probeBoxMax.xyz - probeBoxMin.xyz); return dot(maxToMin, maxToMin); } -half3 CalculateIrradianceFromReflectionProbes(half3 reflectVector, float3 positionWS, half perceptualRoughness, float2 normalizedScreenSpaceUV) +URP_LIGHT_ACCUM3 CalculateIrradianceFromReflectionProbes(half3 reflectVector, float3 positionWS, half perceptualRoughness, float2 normalizedScreenSpaceUV) { - half3 irradiance = half3(0.0h, 0.0h, 0.0h); + URP_LIGHT_ACCUM3 irradiance = URP_LIGHT_ACCUM3(0.0h, 0.0h, 0.0h); half mip = PerceptualRoughnessToMipmapLevel(perceptualRoughness); #if USE_CLUSTER_LIGHT_LOOP && CLUSTER_HAS_REFLECTION_PROBES @@ -435,7 +443,7 @@ half3 CalculateIrradianceFromReflectionProbes(half3 reflectVector, float3 positi float4 scaleOffset0 = urp_ReflProbes_MipScaleOffset[probeIndex * 7 + (uint)mip0]; float4 scaleOffset1 = urp_ReflProbes_MipScaleOffset[probeIndex * 7 + (uint)mip1]; - float preExposure = urp_ReflProbes_ExposureMultipliers[probeIndex].x; + float preExposure = SelectProbeExposureMultiplier(urp_ReflProbes_ExposureMultipliers[probeIndex].x); half3 irradiance0 = half4(SAMPLE_TEXTURE2D_LOD(urp_ReflProbes_Atlas, sampler_LinearClamp, uv * scaleOffset0.xy + scaleOffset0.zw, 0.0)).rgb; half3 irradiance1 = half4(SAMPLE_TEXTURE2D_LOD(urp_ReflProbes_Atlas, sampler_LinearClamp, uv * scaleOffset1.xy + scaleOffset1.zw, 0.0)).rgb; irradiance += preExposure * weight * lerp(irradiance0, irradiance1, mipBlend); @@ -501,7 +509,7 @@ half3 CalculateIrradianceFromReflectionProbes(half3 reflectVector, float3 positi half4 encodedIrradiance = half4(SAMPLE_TEXTURECUBE_LOD(unity_SpecCube0, samplerunity_SpecCube0, reflectVector0, mip)); - irradiance += weightProbe0 * SelectProbeExposureMultiplier(unity_SpecCube0_Exposure.x) * DecodeHDREnvironment(encodedIrradiance, unity_SpecCube0_HDR); + irradiance += weightProbe0 * DecodeExposedProbe(encodedIrradiance, unity_SpecCube0_HDR); } // Sample the second reflection probe @@ -517,7 +525,7 @@ half3 CalculateIrradianceFromReflectionProbes(half3 reflectVector, float3 positi } half4 encodedIrradiance = half4(SAMPLE_TEXTURECUBE_LOD(unity_SpecCube1, samplerunity_SpecCube1, reflectVector1, mip)); - irradiance += weightProbe1 * SelectProbeExposureMultiplier(unity_SpecCube1_Exposure.x) * DecodeHDREnvironment(encodedIrradiance, unity_SpecCube1_HDR); + irradiance += weightProbe1 * DecodeExposedProbe(encodedIrradiance, unity_SpecCube1_HDR); } #endif @@ -532,14 +540,14 @@ half3 CalculateIrradianceFromReflectionProbes(half3 reflectVector, float3 positi return irradiance; } -half3 GlossyEnvironmentReflection(half3 reflectVector, float3 positionWS, half perceptualRoughness, half occlusion, float2 normalizedScreenSpaceUV, bool useEnvironmentReflections) +URP_LIGHT_ACCUM3 GlossyEnvironmentReflection(half3 reflectVector, float3 positionWS, half perceptualRoughness, half occlusion, float2 normalizedScreenSpaceUV, bool useEnvironmentReflections) { - half3 irradiance = half3(0, 0, 0); + URP_LIGHT_ACCUM3 irradiance = 0; #if defined(_SCREENSPACEREFLECTIONS_OFF) - half4 ssrColor = 0; + URP_LIGHT_ACCUM4 ssrColor = 0; #else - half4 ssrColor = GetScreenSpaceReflection(normalizedScreenSpaceUV, positionWS, perceptualRoughness); + URP_LIGHT_ACCUM4 ssrColor = GetScreenSpaceReflection(normalizedScreenSpaceUV, positionWS, perceptualRoughness); // The SSR texture is resolved from the pre-exposed camera color; undo that, as lighting inputs are un-exposed. ssrColor.rgb *= GetInvPreExposureMultiplier(); #endif @@ -580,7 +588,7 @@ half3 GlossyEnvironmentReflection(half3 reflectVector, float3 positionWS, half p half mip = PerceptualRoughnessToMipmapLevel(perceptualRoughness); half4 encodedIrradiance = half4(SAMPLE_TEXTURECUBE_LOD(unity_SpecCube0, samplerunity_SpecCube0, reflectVector, mip)); - irradiance = SelectProbeExposureMultiplier(unity_SpecCube0_Exposure.x) * DecodeHDREnvironment(encodedIrradiance, unity_SpecCube0_HDR); + irradiance = DecodeExposedProbe(encodedIrradiance, unity_SpecCube0_HDR); } } @@ -590,22 +598,22 @@ half3 GlossyEnvironmentReflection(half3 reflectVector, float3 positionWS, half p } #if !USE_CLUSTER_LIGHT_LOOP -half3 GlossyEnvironmentReflection(half3 reflectVector, float3 positionWS, half perceptualRoughness, half occlusion, bool useEnvironmentReflections) +URP_LIGHT_ACCUM3 GlossyEnvironmentReflection(half3 reflectVector, float3 positionWS, half perceptualRoughness, half occlusion, bool useEnvironmentReflections) { return GlossyEnvironmentReflection(reflectVector, positionWS, perceptualRoughness, occlusion, float2(0.0f, 0.0f), useEnvironmentReflections); } #endif -half3 GlossyEnvironmentReflection(half3 reflectVector, half perceptualRoughness, half occlusion, bool useEnvironmentReflections) +URP_LIGHT_ACCUM3 GlossyEnvironmentReflection(half3 reflectVector, half perceptualRoughness, half occlusion, bool useEnvironmentReflections) { - half3 irradiance = _GlossyEnvironmentColor.rgb; + URP_LIGHT_ACCUM3 irradiance = _GlossyEnvironmentColor.rgb; if (useEnvironmentReflections) { half mip = PerceptualRoughnessToMipmapLevel(perceptualRoughness); half4 encodedIrradiance = half4(SAMPLE_TEXTURECUBE_LOD(unity_SpecCube0, samplerunity_SpecCube0, reflectVector, mip)); - irradiance = SelectProbeExposureMultiplier(unity_SpecCube0_Exposure.x) * DecodeHDREnvironment(encodedIrradiance, unity_SpecCube0_HDR); + irradiance = DecodeExposedProbe(encodedIrradiance, unity_SpecCube0_HDR); } return irradiance * occlusion; @@ -627,8 +635,8 @@ URP_LIGHT_ACCUM3 SubtractDirectMainLightFromLightmap(Light mainLight, half3 norm // We only subtract the main direction light. This is accounted in the contribution term below. half shadowStrength = GetMainLightShadowStrength(); half contributionTerm = saturate(dot(mainLight.direction, normalWS)); - half3 lambert = mainLight.color * contributionTerm; - half3 estimatedLightContributionMaskedByInverseOfShadow = lambert * (1.0 - mainLight.shadowAttenuation); + URP_LIGHT_ACCUM3 lambert = mainLight.color * contributionTerm; + URP_LIGHT_ACCUM3 estimatedLightContributionMaskedByInverseOfShadow = lambert * (1.0 - mainLight.shadowAttenuation); URP_LIGHT_ACCUM3 subtractedLightmap = bakedGI - estimatedLightContributionMaskedByInverseOfShadow; // 2) Allows user to define overall ambient of the scene and control situation when realtime shadow becomes too dark. @@ -659,7 +667,7 @@ URP_LIGHT_ACCUM3 GlobalIllumination(BRDFData brdfData, BRDFData brdfDataClearCoa half fresnelTerm = Pow4(1.0 - NoV); URP_LIGHT_ACCUM3 indirectDiffuse = bakedGI; - half3 indirectSpecular = GlossyEnvironmentReflection(reflectVector, positionWS, brdfData.perceptualRoughness, 1.0h, normalizedScreenSpaceUV, useEnvironmentReflections); + URP_LIGHT_ACCUM3 indirectSpecular = GlossyEnvironmentReflection(reflectVector, positionWS, brdfData.perceptualRoughness, 1.0h, normalizedScreenSpaceUV, useEnvironmentReflections); URP_LIGHT_ACCUM3 color = EnvironmentBRDF(brdfData, indirectDiffuse, indirectSpecular, fresnelTerm); @@ -670,9 +678,9 @@ URP_LIGHT_ACCUM3 GlobalIllumination(BRDFData brdfData, BRDFData brdfDataClearCoa if (useClearCoat) { - half3 coatIndirectSpecular = GlossyEnvironmentReflection(reflectVector, positionWS, brdfDataClearCoat.perceptualRoughness, 1.0h, normalizedScreenSpaceUV, useEnvironmentReflections); + URP_LIGHT_ACCUM3 coatIndirectSpecular = GlossyEnvironmentReflection(reflectVector, positionWS, brdfDataClearCoat.perceptualRoughness, 1.0h, normalizedScreenSpaceUV, useEnvironmentReflections); // TODO: "grazing term" causes problems on full roughness - half3 coatColor = EnvironmentBRDFClearCoat(brdfDataClearCoat, clearCoatMask, coatIndirectSpecular, fresnelTerm); + URP_LIGHT_ACCUM3 coatColor = EnvironmentBRDFClearCoat(brdfDataClearCoat, clearCoatMask, coatIndirectSpecular, fresnelTerm); // Blend with base layer using khronos glTF recommended way using NoV // Smooth surface & "ambiguous" lighting @@ -703,15 +711,15 @@ URP_LIGHT_ACCUM3 GlobalIllumination(BRDFData brdfData, BRDFData brdfDataClearCoa half fresnelTerm = Pow4(1.0 - NoV); URP_LIGHT_ACCUM3 indirectDiffuse = bakedGI; - half3 indirectSpecular = GlossyEnvironmentReflection(reflectVector, brdfData.perceptualRoughness, half(1.0), useEnvironmentReflections); + URP_LIGHT_ACCUM3 indirectSpecular = GlossyEnvironmentReflection(reflectVector, brdfData.perceptualRoughness, half(1.0), useEnvironmentReflections); URP_LIGHT_ACCUM3 color = EnvironmentBRDF(brdfData, indirectDiffuse, indirectSpecular, fresnelTerm); if (useClearCoat) { - half3 coatIndirectSpecular = GlossyEnvironmentReflection(reflectVector, brdfDataClearCoat.perceptualRoughness, half(1.0), useEnvironmentReflections); + URP_LIGHT_ACCUM3 coatIndirectSpecular = GlossyEnvironmentReflection(reflectVector, brdfDataClearCoat.perceptualRoughness, half(1.0), useEnvironmentReflections); // TODO: "grazing term" causes problems on full roughness - half3 coatColor = EnvironmentBRDFClearCoat(brdfDataClearCoat, clearCoatMask, coatIndirectSpecular, fresnelTerm); + URP_LIGHT_ACCUM3 coatColor = EnvironmentBRDFClearCoat(brdfDataClearCoat, clearCoatMask, coatIndirectSpecular, fresnelTerm); // Blend with base layer using khronos glTF recommended way using NoV // Smooth surface & "ambiguous" lighting diff --git a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/GlobalShaderVariables.hlsl b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/GlobalShaderVariables.hlsl index 95d4169c5fe..e18eb238729 100644 --- a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/GlobalShaderVariables.hlsl +++ b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/GlobalShaderVariables.hlsl @@ -3,10 +3,28 @@ #define MAX_SHADOW_CASCADES 4 +// URP fills its constant buffers from C# everywhere but GLES3 outside WebGL, like RenderingUtils.usePersistentConstantBuffer. +#if !defined(SHADER_API_GLES3) || defined(UNITY_PLATFORM_WEBGL) +#define URP_PERSISTENT_CONSTANT_BUFFERS_ACTIVE +#endif + +// OpenGL Core alone. Some platforms also define SHADER_API_GLCORE next to their own SHADER_API_* define, so testing +// SHADER_API_GLCORE alone would catch them. +#if defined(SHADER_API_GLCORE) && !defined(SHADER_API_SWITCH) && !defined(SHADER_API_SWITCH2) +#define URP_SHADER_API_GLCORE +#endif + // This CB layout is directly matching GlobalShaderVariables.cs, make sure to keep the two up to date -// URP_GLOBAL_CONSTANT_BUFFER is a shader constant define driven by the Project Settings > Graphics > URP > Rendering Capabilities > Use Persistent Constant Buffers -// Only available in Editor Developer mode for now, still wip -#if defined(URP_GLOBAL_CONSTANT_BUFFER) +// Declared on every API but GLES3 outside WebGL, and OpenGL Core, where the constant buffers of DOTS instancing can +// leave no slot for it; the condition must match UniversalRenderPipeline.IsGlobalConstantBufferSupported(). +// Use Persistent Global Constant Buffer only chooses who fills it. +#if defined(URP_PERSISTENT_CONSTANT_BUFFERS_ACTIVE) && !defined(URP_SHADER_API_GLCORE) +#define URP_GLOBAL_CONSTANT_BUFFER_ACTIVE +#endif + +// The members are ordered by access, see guideline 5 in GlobalShaderVariables.cs: the ones lit fragment shaders read +// sit together, from _GlossyEnvironmentColor to _AdditionalShadowmapSize, followed by the main light shadow matrices. +#if defined(URP_GLOBAL_CONSTANT_BUFFER_ACTIVE) CBUFFER_START(GlobalShaderVariables) #endif // (t/20, t, t*2, t*3) @@ -37,73 +55,72 @@ CBUFFER_START(GlobalShaderVariables) // z = x/far // w = 1/far float4 _ZBufferParams; - // x = orthographic camera's width - // y = orthographic camera's height - // z = unused - // w = 1.0 if camera is ortho, 0.0 if perspective - float4 unity_OrthoParams; // { w / RTHandle.maxWidth, h / RTHandle.maxHeight } : xy = currFrame, zw = prevFrame float4 _RTHandleScale; - float4 _ScaledScreenParams; // {w, h, 1/w, 1/h} float4 _ScreenSize; float4 _ScreenSizeOverride; float4 _ScreenCoordScaleBias; - // Ambient gradient, filled from RenderSettings. -#if defined(URP_GLOBAL_CONSTANT_BUFFER) + // Ambient gradient, filled from RenderSettings, then the environment color. +#if defined(URP_GLOBAL_CONSTANT_BUFFER_ACTIVE) float4 unity_AmbientSky; float4 unity_AmbientEquator; float4 unity_AmbientGround; + float4 _GlossyEnvironmentColor; #else half4 unity_AmbientSky; half4 unity_AmbientEquator; half4 unity_AmbientGround; + half4 _GlossyEnvironmentColor; #endif + // x = orthographic camera's width + // y = orthographic camera's height + // z = unused + // w = 1.0 if camera is ortho, 0.0 if perspective + float4 unity_OrthoParams; + float4 _ScaledScreenParams; // x = Mip Bias // y = 2.0 ^ [Mip Bias] float2 _GlobalMipBias; float _DitheringTextureInvSize; float _URPPadding1; // Environment -#if defined(URP_GLOBAL_CONSTANT_BUFFER) - float4 _GlossyEnvironmentColor; +#if defined(URP_GLOBAL_CONSTANT_BUFFER_ACTIVE) float4 _SubtractiveShadowColor; float4 _GlossyEnvironmentCubeMap_HDR; #else - half4 _GlossyEnvironmentColor; half4 _SubtractiveShadowColor; half4 _GlossyEnvironmentCubeMap_HDR; #endif // === Variables only present in 3D renderer start here === // Main Light - float4x4 _MainLightWorldToLight; float4 _MainLightPosition; // In Forward+, .a stores whether the main light is using subtractive mixed mode. -#if defined(URP_GLOBAL_CONSTANT_BUFFER) +#if defined(URP_GLOBAL_CONSTANT_BUFFER_ACTIVE) float4 _MainLightColor; float4 _MainLightOcclusionProbes; #else half4 _MainLightColor; half4 _MainLightOcclusionProbes; #endif + // The scalars lit shaders read. The four of them pack into a single 16 byte row next to the main light, keep them + // together. + uint _MainLightLayerMask; + uint _RenderingLayerMaxInt; + uint _EnableProbeVolumes; + float _MainLightCookieTextureFormat; // Forward+ Parameters. Declared unconditionally, unlike the URP_FP_* accessors in Input.hlsl that stay behind // USE_CLUSTER_LIGHT_LOOP: a constant buffer member cannot be conditional or the offsets stop matching C#. float4 _FPParams0; float4 _FPParams1; float4 _FPParams2; - // Motion Vectors, non jittered. Declared unconditionally so the offsets stay fixed. - float4x4 _NonJitteredViewProjMatrix; - float4x4 _PrevViewProjMatrix; // Additional Lights. The arrays themselves stay loose uniforms, only the count lives here. -#if defined(URP_GLOBAL_CONSTANT_BUFFER) +#if defined(URP_GLOBAL_CONSTANT_BUFFER_ACTIVE) float4 _AdditionalLightsCount; // x holds the count #else half4 _AdditionalLightsCount; // x holds the count #endif - // Main Light Shadows. Sized MAX_SHADOW_CASCADES + 1, spelled out because that define lives in Shadows.hlsl which is - // included later. The last cascade is initialized with a no-op matrix, always transforming the shadow coord to - // half3(0, 0, NEAR_PLANE), which avoids branching since ComputeCascadeIndex can return MAX_SHADOW_CASCADES. - float4x4 _MainLightWorldToShadow[MAX_SHADOW_CASCADES + 1]; + // Main Light Shadows float4 _CascadeShadowSplitSpheres0; float4 _CascadeShadowSplitSpheres1; float4 _CascadeShadowSplitSpheres2; @@ -112,24 +129,34 @@ CBUFFER_START(GlobalShaderVariables) float4 _MainLightShadowOffset0; // xy: offset0, zw: offset1 float4 _MainLightShadowOffset1; // xy: offset2, zw: offset3 float4 _MainLightShadowmapSize; // xy: 1/width and 1/height, zw: width and height + // Main Light Shadows, PCSS. The slots of a cascade that was not rendered are zeroed, which reads as no shadow. + float4 _MainLightPCSSParams0[MAX_SHADOW_CASCADES + 1]; // (x: depth2RadialScale, y: radial2DepthScale, z: maxSampleZDistance, w: maxPCSSOffset) + float4 _MainLightPCSSParams1[MAX_SHADOW_CASCADES + 1]; // (x: minFilterSizeTexels, y: minFilterRadial2DepthScale, z: blockerRadial2DepthScale, w: blockerClumpSampleExponent) + float4 _MainLightPCSSAtlas[MAX_SHADOW_CASCADES + 1]; // (xy: atlas tile offset in UV, zw: atlas tile scale in UV) + float4 _MainLightPCSSScalars; // (x: tile texel size = 1/tileResolution, y: blockerSampleCount, z: filterSampleCount, w: temporal frame index) // Additional Lights Shadows float4 _AdditionalShadowOffset0; // xy: offset0, zw: offset1 float4 _AdditionalShadowOffset1; // xy: offset2, zw: offset3 float4 _AdditionalShadowmapSize; // xy: 1/width and 1/height, zw: width and height - // Misc. The four scalars below pack into a single 16 byte row, keep them together. - float _MainLightCookieTextureFormat; - float _AdditionalLightsCookieAtlasTextureFormat; - uint _RenderingLayerMaxInt; - uint _EnableProbeVolumes; - // Kept last on purpose: these scalars share a single 16 byte row, so the next 3D fields we add can consume the + // Main Light Shadows matrices. Sized MAX_SHADOW_CASCADES + 1, spelled out because that define lives in Shadows.hlsl + // which is included later. The last cascade is initialized with a no-op matrix, always transforming the shadow coord + // to half3(0, 0, NEAR_PLANE), which avoids branching since ComputeCascadeIndex can return MAX_SHADOW_CASCADES. + // The rows above add up to a multiple of 64 bytes, so each cascade matrix fills one cache line. + float4x4 _MainLightWorldToShadow[MAX_SHADOW_CASCADES + 1]; + // Main Light cookie + float4x4 _MainLightWorldToLight; + // Motion Vectors, non jittered. Declared unconditionally so the offsets stay fixed. + float4x4 _NonJitteredViewProjMatrix; + float4x4 _PrevViewProjMatrix; + // Kept last on purpose: these scalars share a single 16 byte row, so the next 3D scalars we add can consume the // remaining padding slots instead of needing padding of their own. - uint _MainLightLayerMask; + float _AdditionalLightsCookieAtlasTextureFormat; uint _URPPadding2; uint _URPPadding3; uint _URPPadding4; // === Variables only present in 2D renderer start here === // float4 _URPDummy2D; -#if defined(URP_GLOBAL_CONSTANT_BUFFER) +#if defined(URP_GLOBAL_CONSTANT_BUFFER_ACTIVE) CBUFFER_END #endif diff --git a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Input.hlsl b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Input.hlsl index a4095763851..6ec7562f8f6 100644 --- a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Input.hlsl +++ b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Input.hlsl @@ -42,6 +42,7 @@ struct InputData float3 positionWS; float4 positionCS; float3 normalWS; + float3 geometricNormalWS; half3 viewDirectionWS; float4 shadowCoord; half fogCoord; @@ -135,7 +136,7 @@ half4 _ScreenSpaceReflectionParam; #endif // GLES3 causes a performance regression in some devices when using CBUFFER. -#ifndef LIGHT_SHADOWS_NO_CBUFFER +#if defined(URP_PERSISTENT_CONSTANT_BUFFERS_ACTIVE) CBUFFER_START(AdditionalLights) #endif float4 _AdditionalLightsPosition[MAX_VISIBLE_LIGHTS]; @@ -144,7 +145,7 @@ float4 _AdditionalLightsColor[MAX_VISIBLE_LIGHTS]; float4 _AdditionalLightsAttenuation[MAX_VISIBLE_LIGHTS]; float4 _AdditionalLightsSpotDir[MAX_VISIBLE_LIGHTS]; float4 _AdditionalLightsOcclusionProbes[MAX_VISIBLE_LIGHTS]; -#ifndef LIGHT_SHADOWS_NO_CBUFFER +#if defined(URP_PERSISTENT_CONSTANT_BUFFERS_ACTIVE) CBUFFER_END #endif @@ -172,12 +173,11 @@ StructuredBuffer urp_Tiles; #endif TEXTURE2D(urp_ReflProbes_Atlas); -float urp_ReflProbes_Count; // 2023.3 Deprecated. This is for backwards compatibility. Remove in the future. #define samplerurp_ReflProbes_Atlas sampler_LinearClamp -#ifndef LIGHT_SHADOWS_NO_CBUFFER +#if defined(URP_PERSISTENT_CONSTANT_BUFFERS_ACTIVE) CBUFFER_START(urp_ReflectionProbeBuffer) #endif float4 urp_ReflProbes_BoxMax[MAX_REFLECTION_PROBES]; // w contains the blend distance @@ -186,7 +186,7 @@ float4 urp_ReflProbes_ProbePosition[MAX_REFLECTION_PROBES]; // w is positive f float4 urp_ReflProbes_MipScaleOffset[MAX_REFLECTION_PROBES * 7]; float4 urp_ReflProbes_Rotation[MAX_REFLECTION_PROBES]; float4 urp_ReflProbes_ExposureMultipliers[MAX_REFLECTION_PROBES]; -#ifndef LIGHT_SHADOWS_NO_CBUFFER +#if defined(URP_PERSISTENT_CONSTANT_BUFFERS_ACTIVE) CBUFFER_END #endif diff --git a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Light.hlsl b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Light.hlsl index 238581d6eee..448382ae85c 100644 --- a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Light.hlsl +++ b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Light.hlsl @@ -1,11 +1,12 @@ #ifndef UNIVERSAL_LIGHT_INCLUDED #define UNIVERSAL_LIGHT_INCLUDED +#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/ExposureFunctions.hlsl" // Abstraction over Light shading data. struct Light { half3 direction; - half3 color; + URP_LIGHT_ACCUM3 color; float distanceAttenuation; // full-float precision required on some platforms half shadowAttenuation; uint layerMask; diff --git a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/LightCookie/LightCookieInput.hlsl b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/LightCookie/LightCookieInput.hlsl index 05cd5201058..dce59ea39f1 100644 --- a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/LightCookie/LightCookieInput.hlsl +++ b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/LightCookie/LightCookieInput.hlsl @@ -11,14 +11,8 @@ TEXTURE2D(_AdditionalLightsCookieAtlasTexture); // Samplers SAMPLER(sampler_MainLightCookieTexture); -// Persistent constant buffer everywhere except GLES3, which falls back to field-wise SetGlobalXArray. WebGL2 -// reports as GLES3. Must match RenderingUtils.usePersistentConstantBuffer: if the two disagree, the field-wise -// uploads never run and the shader reads whatever is in the bound buffer. -#if !defined(SHADER_API_GLES3) - #define URP_LIGHT_COOKIE_PERSISTENT_CBUFFER -#endif - -#if defined(URP_LIGHT_COOKIE_PERSISTENT_CBUFFER) +// Persistent layout where URP fills its constant buffers from C#, field-wise SetGlobalXArray on GLES3 outside WebGL. +#if defined(URP_PERSISTENT_CONSTANT_BUFFERS_ACTIVE) CBUFFER_START(LightCookies) float4x4 _AdditionalLightsWorldToLights[MAX_VISIBLE_LIGHTS]; float4 _AdditionalLightsCookieAtlasUVRects[MAX_VISIBLE_LIGHTS]; @@ -26,18 +20,12 @@ CBUFFER_START(LightCookies) float4 _AdditionalLightsCookieEnableBits[(MAX_VISIBLE_LIGHTS + 31) / 32]; // yzw are padding CBUFFER_END #else - // Field-wise layout, GLES3 only: a transient CBUFFER on WebGL2, plain loose uniforms elsewhere, since - // CBUFFER causes a performance regression on some GLES3 devices. - #ifndef LIGHT_SHADOWS_NO_CBUFFER - CBUFFER_START(LightCookies) - #endif - float4x4 _AdditionalLightsWorldToLights[MAX_VISIBLE_LIGHTS]; - float4 _AdditionalLightsCookieAtlasUVRects[MAX_VISIBLE_LIGHTS]; - float _AdditionalLightsLightTypes[MAX_VISIBLE_LIGHTS]; - float _AdditionalLightsCookieEnableBits[(MAX_VISIBLE_LIGHTS + 31) / 32]; - #ifndef LIGHT_SHADOWS_NO_CBUFFER - CBUFFER_END - #endif + // Field-wise layout, GLES3 outside WebGL only: plain loose uniforms, since CBUFFER causes a performance + // regression on some GLES3 devices. + float4x4 _AdditionalLightsWorldToLights[MAX_VISIBLE_LIGHTS]; + float4 _AdditionalLightsCookieAtlasUVRects[MAX_VISIBLE_LIGHTS]; + float _AdditionalLightsLightTypes[MAX_VISIBLE_LIGHTS]; + float _AdditionalLightsCookieEnableBits[(MAX_VISIBLE_LIGHTS + 31) / 32]; #endif @@ -55,7 +43,7 @@ float4 GetLightCookieAtlasUVRect(int lightIndex) int GetLightCookieLightType(int lightIndex) { -#if defined(URP_LIGHT_COOKIE_PERSISTENT_CBUFFER) +#if defined(URP_PERSISTENT_CONSTANT_BUFFERS_ACTIVE) return _AdditionalLightsLightTypes[lightIndex].x; #else return _AdditionalLightsLightTypes[lightIndex]; @@ -112,7 +100,7 @@ bool IsLightCookieEnabled(int lightBufferIndex) uint elemIndex = ((uint)lightBufferIndex) >> 5; uint bitOffset = (uint)lightBufferIndex & ((1 << 5) - 1); -#if defined(URP_LIGHT_COOKIE_PERSISTENT_CBUFFER) +#if defined(URP_PERSISTENT_CONSTANT_BUFFERS_ACTIVE) uint elem = asuint(_AdditionalLightsCookieEnableBits[elemIndex].x); #else uint elem = asuint(_AdditionalLightsCookieEnableBits[elemIndex]); diff --git a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.deprecated.hlsl b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.deprecated.hlsl index cc89e871e50..2cc5ab71777 100644 --- a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.deprecated.hlsl +++ b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.deprecated.hlsl @@ -12,15 +12,15 @@ // Deprecated keyword-reading wrappers, kept for external back-compat. // New code passes the keyword state as parameters (Lighting.hlsl). -half3 LightingPhysicallyBased(BRDFData brdfData, BRDFData brdfDataClearCoat, - half3 lightColor, half3 lightDirectionWS, float lightAttenuation, +URP_LIGHT_ACCUM3 LightingPhysicallyBased(BRDFData brdfData, BRDFData brdfDataClearCoat, + URP_LIGHT_ACCUM3 lightColor, half3 lightDirectionWS, float lightAttenuation, half3 normalWS, half3 viewDirectionWS, half clearCoatMask, bool specularHighlights, bool clearCoatEnabled); -half3 LightingPhysicallyBased(BRDFData brdfData, BRDFData brdfDataClearCoat, Light light, half3 normalWS, half3 viewDirectionWS, half clearCoatMask, bool specularHighlights, bool clearCoatEnabled); -half3 LightingPhysicallyBased(BRDFData brdfData, Light light, half3 normalWS, half3 viewDirectionWS, bool specularHighlights, bool clearCoatEnabled); -half3 CalculateBlinnPhong(Light light, InputData inputData, SurfaceData surfaceData, bool specularEnabled, bool alphaPremultiplyEnabled); -URP_LIGHT_ACCUM4 UniversalFragmentPBR(InputData inputData, SurfaceData surfaceData, bool specularSetup, bool specularHighlights, bool alphaPremultiplyEnabled, bool clearCoatEnabled, bool receiveShadows, bool surfaceTypeTransparent, bool environmentReflections, float3 geometricNormalWS = float3(0.0, 0.0, 0.0)); -URP_LIGHT_ACCUM4 UniversalFragmentBlinnPhong(InputData inputData, SurfaceData surfaceData, bool specularEnabled, bool alphaPremultiplyEnabled, bool receiveShadows, bool surfaceTypeTransparent, float3 geometricNormalWS = float3(0.0, 0.0, 0.0)); +URP_LIGHT_ACCUM3 LightingPhysicallyBased(BRDFData brdfData, BRDFData brdfDataClearCoat, Light light, half3 normalWS, half3 viewDirectionWS, half clearCoatMask, bool specularHighlights, bool clearCoatEnabled); +URP_LIGHT_ACCUM3 LightingPhysicallyBased(BRDFData brdfData, Light light, half3 normalWS, half3 viewDirectionWS, bool specularHighlights, bool clearCoatEnabled); +URP_LIGHT_ACCUM3 CalculateBlinnPhong(Light light, InputData inputData, SurfaceData surfaceData, bool specularEnabled, bool alphaPremultiplyEnabled); +URP_LIGHT_ACCUM4 UniversalFragmentPBR(InputData inputData, SurfaceData surfaceData, bool specularSetup, bool specularHighlights, bool alphaPremultiplyEnabled, bool clearCoatEnabled, bool receiveShadows, bool surfaceTypeTransparent, bool environmentReflections); +URP_LIGHT_ACCUM4 UniversalFragmentBlinnPhong(InputData inputData, SurfaceData surfaceData, bool specularEnabled, bool alphaPremultiplyEnabled, bool receiveShadows, bool surfaceTypeTransparent); URP_LIGHT_ACCUM4 UniversalFragmentBakedLit(InputData inputData, SurfaceData surfaceData, bool surfaceTypeTransparent); #if !defined(_ALPHAPREMULTIPLY_ON_KEYWORD_DECLARED) @@ -180,14 +180,14 @@ half3 CalculateBlinnPhong(Light light, InputData inputData, SurfaceData surfaceD } // Deprecated. Use UniversalFragmentPBR(inputData, surfaceData, specularSetup, specularHighlights, alphaPremultiplyEnabled, clearCoatEnabled, receiveShadows, surfaceTypeTransparent, environmentReflections). -URP_LIGHT_ACCUM4 UniversalFragmentPBR(InputData inputData, SurfaceData surfaceData, float3 geometricNormalWS = float3(0.0, 0.0, 0.0)) +URP_LIGHT_ACCUM4 UniversalFragmentPBR(InputData inputData, SurfaceData surfaceData) { - return UniversalFragmentPBR(inputData, surfaceData, _SPECULAR_SETUP, !_SPECULARHIGHLIGHTS_OFF, _ALPHAPREMULTIPLY_ON, _CLEARCOAT || _CLEARCOATMAP, !_RECEIVE_SHADOWS_OFF, _SURFACE_TYPE_TRANSPARENT, !_ENVIRONMENTREFLECTIONS_OFF, geometricNormalWS); + return UniversalFragmentPBR(inputData, surfaceData, _SPECULAR_SETUP, !_SPECULARHIGHLIGHTS_OFF, _ALPHAPREMULTIPLY_ON, _CLEARCOAT || _CLEARCOATMAP, !_RECEIVE_SHADOWS_OFF, _SURFACE_TYPE_TRANSPARENT, !_ENVIRONMENTREFLECTIONS_OFF); } // Deprecated: Use the version which takes "SurfaceData" instead of passing all of these arguments... URP_LIGHT_ACCUM4 UniversalFragmentPBR(InputData inputData, half3 albedo, half metallic, half3 specular, - half smoothness, half occlusion, half3 emission, half alpha, float3 geometricNormalWS = float3(0.0, 0.0, 0.0)) + half smoothness, half occlusion, half3 emission, half alpha) { SurfaceData surfaceData; @@ -202,17 +202,17 @@ URP_LIGHT_ACCUM4 UniversalFragmentPBR(InputData inputData, half3 albedo, half me surfaceData.clearCoatMask = 0; surfaceData.clearCoatSmoothness = 1; - return UniversalFragmentPBR(inputData, surfaceData, _SPECULAR_SETUP, !_SPECULARHIGHLIGHTS_OFF, _ALPHAPREMULTIPLY_ON, _CLEARCOAT || _CLEARCOATMAP, !_RECEIVE_SHADOWS_OFF, _SURFACE_TYPE_TRANSPARENT, !_ENVIRONMENTREFLECTIONS_OFF, geometricNormalWS); + return UniversalFragmentPBR(inputData, surfaceData, _SPECULAR_SETUP, !_SPECULARHIGHLIGHTS_OFF, _ALPHAPREMULTIPLY_ON, _CLEARCOAT || _CLEARCOATMAP, !_RECEIVE_SHADOWS_OFF, _SURFACE_TYPE_TRANSPARENT, !_ENVIRONMENTREFLECTIONS_OFF); } // Deprecated. Use UniversalFragmentBlinnPhong(inputData, surfaceData, specularEnabled, alphaPremultiplyEnabled, receiveShadows, surfaceTypeTransparent). -URP_LIGHT_ACCUM4 UniversalFragmentBlinnPhong(InputData inputData, SurfaceData surfaceData, float3 geometricNormalWS = float3(0.0, 0.0, 0.0)) +URP_LIGHT_ACCUM4 UniversalFragmentBlinnPhong(InputData inputData, SurfaceData surfaceData) { - return UniversalFragmentBlinnPhong(inputData, surfaceData, _SPECGLOSSMAP || _SPECULAR_COLOR, _ALPHAPREMULTIPLY_ON, !_RECEIVE_SHADOWS_OFF, _SURFACE_TYPE_TRANSPARENT, geometricNormalWS); + return UniversalFragmentBlinnPhong(inputData, surfaceData, _SPECGLOSSMAP || _SPECULAR_COLOR, _ALPHAPREMULTIPLY_ON, !_RECEIVE_SHADOWS_OFF, _SURFACE_TYPE_TRANSPARENT); } // Deprecated: Use the version which takes "SurfaceData" instead of passing all of these arguments... -URP_LIGHT_ACCUM4 UniversalFragmentBlinnPhong(InputData inputData, half3 diffuse, half4 specularGloss, half smoothness, half3 emission, half alpha, half3 normalTS, float3 geometricNormalWS = float3(0.0, 0.0, 0.0)) +URP_LIGHT_ACCUM4 UniversalFragmentBlinnPhong(InputData inputData, half3 diffuse, half4 specularGloss, half smoothness, half3 emission, half alpha, half3 normalTS) { SurfaceData surfaceData; @@ -227,7 +227,7 @@ URP_LIGHT_ACCUM4 UniversalFragmentBlinnPhong(InputData inputData, half3 diffuse, surfaceData.clearCoatSmoothness = 1; surfaceData.normalTS = normalTS; - return UniversalFragmentBlinnPhong(inputData, surfaceData, _SPECGLOSSMAP || _SPECULAR_COLOR, _ALPHAPREMULTIPLY_ON, !_RECEIVE_SHADOWS_OFF, _SURFACE_TYPE_TRANSPARENT, geometricNormalWS); + return UniversalFragmentBlinnPhong(inputData, surfaceData, _SPECGLOSSMAP || _SPECULAR_COLOR, _ALPHAPREMULTIPLY_ON, !_RECEIVE_SHADOWS_OFF, _SURFACE_TYPE_TRANSPARENT); } // Deprecated. Use UniversalFragmentBakedLit(inputData, surfaceData, surfaceTypeTransparent). diff --git a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl index b94c81351a1..6f34cf6470a 100644 --- a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl +++ b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl @@ -27,22 +27,22 @@ bool LightLayersAvailable() bool IsMatchingLightLayer(Light light, uint renderingLayers) { - bool isMatching = true; + uint matchBits = 1u; if (_LIGHT_LAYERS) - isMatching = IsMatchingLightLayer(light.layerMask, renderingLayers); - return isMatching; + matchBits = light.layerMask & renderingLayers; + return matchBits != 0u; } /////////////////////////////////////////////////////////////////////////////// // Lighting Functions // /////////////////////////////////////////////////////////////////////////////// -half3 LightingLambert(half3 lightColor, half3 lightDir, half3 normal) +URP_LIGHT_ACCUM3 LightingLambert(URP_LIGHT_ACCUM3 lightColor, half3 lightDir, half3 normal) { half NdotL = saturate(dot(normal, lightDir)); return lightColor * NdotL; } -half3 LightingSpecular(half3 lightColor, half3 lightDir, half3 normal, half3 viewDir, half4 specular, half smoothness) +URP_LIGHT_ACCUM3 LightingSpecular(URP_LIGHT_ACCUM3 lightColor, half3 lightDir, half3 normal, half3 viewDir, half4 specular, half smoothness) { float3 halfVec = SafeNormalize(float3(lightDir) + float3(viewDir)); half NdotH = half(saturate(dot(normal, halfVec))); @@ -52,8 +52,8 @@ half3 LightingSpecular(half3 lightColor, half3 lightDir, half3 normal, half3 vie return lightColor * specularReflection; } -half3 LightingPhysicallyBased(BRDFData brdfData, BRDFData brdfDataClearCoat, - half3 lightColor, half3 lightDirectionWS, float lightAttenuation, +URP_LIGHT_ACCUM3 LightingPhysicallyBased(BRDFData brdfData, BRDFData brdfDataClearCoat, + URP_LIGHT_ACCUM3 lightColor, half3 lightDirectionWS, float lightAttenuation, half3 normalWS, half3 viewDirectionWS, half clearCoatMask, bool useSpecularHighlights, bool useClearCoat) { @@ -67,9 +67,9 @@ half3 LightingPhysicallyBased(BRDFData brdfData, BRDFData brdfDataClearCoat, [branch] if (NdotL > 0.0) { - half3 radiance = lightColor * (lightAttenuation * saturate(NdotL)); + URP_LIGHT_ACCUM3 radiance = lightColor * (lightAttenuation * saturate(NdotL)); #else - half3 radiance = lightColor * (lightAttenuation * NdotL); + URP_LIGHT_ACCUM3 radiance = lightColor * (lightAttenuation * NdotL); #endif half3 brdf = brdfData.diffuse; [branch] @@ -101,12 +101,13 @@ half3 LightingPhysicallyBased(BRDFData brdfData, BRDFData brdfDataClearCoat, return 0.0; } -half3 LightingPhysicallyBased(BRDFData brdfData, BRDFData brdfDataClearCoat, Light light, half3 normalWS, half3 viewDirectionWS, half clearCoatMask, bool useSpecularHighlights, bool useClearCoat) + +URP_LIGHT_ACCUM3 LightingPhysicallyBased(BRDFData brdfData, BRDFData brdfDataClearCoat, Light light, half3 normalWS, half3 viewDirectionWS, half clearCoatMask, bool useSpecularHighlights, bool useClearCoat) { return LightingPhysicallyBased(brdfData, brdfDataClearCoat, light.color, light.direction, light.distanceAttenuation * light.shadowAttenuation, normalWS, viewDirectionWS, clearCoatMask, useSpecularHighlights, useClearCoat); } -half3 LightingPhysicallyBased(BRDFData brdfData, Light light, half3 normalWS, half3 viewDirectionWS, bool useSpecularHighlights, bool useClearCoat) +URP_LIGHT_ACCUM3 LightingPhysicallyBased(BRDFData brdfData, Light light, half3 normalWS, half3 viewDirectionWS, bool useSpecularHighlights, bool useClearCoat) { const BRDFData noClearCoat = CreateEmptyBRDFData(); return LightingPhysicallyBased(brdfData, noClearCoat, light, normalWS, viewDirectionWS, 0.0, useSpecularHighlights, useClearCoat); @@ -129,7 +130,7 @@ URP_LIGHT_ACCUM3 VertexLighting(float3 positionWS, half3 normalWS) if(light.distanceAttenuation > 0.0) #endif { - half3 lightColor = light.color * light.distanceAttenuation; + URP_LIGHT_ACCUM3 lightColor = light.color * light.distanceAttenuation; vertexLightColor += LightingLambert(lightColor, light.direction, normalWS); } } @@ -220,12 +221,12 @@ LightingData CreateLightingData(InputData inputData, SurfaceData surfaceData) } // useSpecularHighlights: the material provides a specular color (_SPECGLOSSMAP or _SPECULAR_COLOR). -half3 CalculateBlinnPhong(Light light, InputData inputData, SurfaceData surfaceData, bool useSpecularHighlights, bool useAlphaPremultiply) +URP_LIGHT_ACCUM3 CalculateBlinnPhong(Light light, InputData inputData, SurfaceData surfaceData, bool useSpecularHighlights, bool useAlphaPremultiply) { - half3 attenuatedLightColor = light.color * (light.distanceAttenuation * light.shadowAttenuation); - half3 lightDiffuseColor = LightingLambert(attenuatedLightColor, light.direction, inputData.normalWS); + URP_LIGHT_ACCUM3 attenuatedLightColor = light.color * (light.distanceAttenuation * light.shadowAttenuation); + URP_LIGHT_ACCUM3 lightDiffuseColor = LightingLambert(attenuatedLightColor, light.direction, inputData.normalWS); - half3 lightSpecularColor = half3(0,0,0); + URP_LIGHT_ACCUM3 lightSpecularColor = half3(0,0,0); if (useSpecularHighlights) { half smoothness = exp2(10 * surfaceData.smoothness + 1); @@ -246,11 +247,11 @@ half3 CalculateBlinnPhong(Light light, InputData inputData, SurfaceData surfaceD //////////////////////////////////////////////////////////////////////////////// /// PBR lighting... //////////////////////////////////////////////////////////////////////////////// -URP_LIGHT_ACCUM4 UniversalFragmentPBR(InputData inputData, SurfaceData surfaceData, bool isSpecularSetup, bool useSpecularHighlights, bool useAlphaPremultiply, bool useClearCoat, bool receiveShadows, bool isSurfaceTypeTransparent, bool useEnvironmentReflections, float3 geometricNormalWS) +URP_LIGHT_ACCUM4 UniversalFragmentPBR(InputData inputData, SurfaceData surfaceData, bool isSpecularSetup, bool useSpecularHighlights, bool useAlphaPremultiply, bool useClearCoat, bool receiveShadows, bool isSurfaceTypeTransparent, bool useEnvironmentReflections) { BRDFData brdfData = InitializeBRDFData(surfaceData, isSpecularSetup, useAlphaPremultiply); - #if defined(DEBUG_DISPLAY) +#if defined(DEBUG_DISPLAY) float4 debugColor; if (CanDebugOverrideOutputColor(inputData, surfaceData, brdfData, debugColor)) @@ -303,7 +304,7 @@ URP_LIGHT_ACCUM4 UniversalFragmentPBR(InputData inputData, SurfaceData surfaceDa { CLUSTER_LIGHT_LOOP_SUBTRACTIVE_LIGHT_CHECK - Light light = GetAdditionalLight(lightIndex, inputData, shadowMask, aoFactor, receiveShadows, isSurfaceTypeTransparent, geometricNormalWS); + Light light = GetAdditionalLight(lightIndex, inputData, shadowMask, aoFactor, receiveShadows, isSurfaceTypeTransparent); if (IsMatchingLightLayer(light, meshRenderingLayers)) { @@ -315,7 +316,7 @@ URP_LIGHT_ACCUM4 UniversalFragmentPBR(InputData inputData, SurfaceData surfaceDa #endif LIGHT_LOOP_BEGIN(pixelLightCount) - Light light = GetAdditionalLight(lightIndex, inputData, shadowMask, aoFactor, receiveShadows, isSurfaceTypeTransparent, geometricNormalWS); + Light light = GetAdditionalLight(lightIndex, inputData, shadowMask, aoFactor, receiveShadows, isSurfaceTypeTransparent); if (IsMatchingLightLayer(light, meshRenderingLayers)) { @@ -344,7 +345,7 @@ URP_LIGHT_ACCUM4 UniversalFragmentPBR(InputData inputData, SurfaceData surfaceDa //////////////////////////////////////////////////////////////////////////////// /// Phong lighting... //////////////////////////////////////////////////////////////////////////////// -URP_LIGHT_ACCUM4 UniversalFragmentBlinnPhong(InputData inputData, SurfaceData surfaceData, bool useSpecularHighlights, bool useAlphaPremultiply, bool receiveShadows, bool isSurfaceTypeTransparent, float3 geometricNormalWS) +URP_LIGHT_ACCUM4 UniversalFragmentBlinnPhong(InputData inputData, SurfaceData surfaceData, bool useSpecularHighlights, bool useAlphaPremultiply, bool receiveShadows, bool isSurfaceTypeTransparent) { #if defined(DEBUG_DISPLAY) float4 debugColor; @@ -379,7 +380,7 @@ URP_LIGHT_ACCUM4 UniversalFragmentBlinnPhong(InputData inputData, SurfaceData su { CLUSTER_LIGHT_LOOP_SUBTRACTIVE_LIGHT_CHECK - Light light = GetAdditionalLight(lightIndex, inputData, shadowMask, aoFactor, receiveShadows, isSurfaceTypeTransparent, geometricNormalWS); + Light light = GetAdditionalLight(lightIndex, inputData, shadowMask, aoFactor, receiveShadows, isSurfaceTypeTransparent); if (IsMatchingLightLayer(light, meshRenderingLayers)) { @@ -389,7 +390,7 @@ URP_LIGHT_ACCUM4 UniversalFragmentBlinnPhong(InputData inputData, SurfaceData su #endif LIGHT_LOOP_BEGIN(pixelLightCount) - Light light = GetAdditionalLight(lightIndex, inputData, shadowMask, aoFactor, receiveShadows, isSurfaceTypeTransparent, geometricNormalWS); + Light light = GetAdditionalLight(lightIndex, inputData, shadowMask, aoFactor, receiveShadows, isSurfaceTypeTransparent); if (IsMatchingLightLayer(light, meshRenderingLayers)) { @@ -431,7 +432,7 @@ URP_LIGHT_ACCUM4 UniversalFragmentBakedLit(InputData inputData, SurfaceData surf } // Fog is applied by the caller via BlendDistanceFog(color, positionCS). - return half4(CalculateLightingColor(lightingData, surfaceData.albedo), surfaceData.alpha); + return URP_LIGHT_ACCUM4(CalculateLightingColor(lightingData, surfaceData.albedo), surfaceData.alpha); } #endif diff --git a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/RealtimeLights.deprecated.hlsl b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/RealtimeLights.deprecated.hlsl index a46bc2c5b48..2e1d381885a 100644 --- a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/RealtimeLights.deprecated.hlsl +++ b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/RealtimeLights.deprecated.hlsl @@ -12,8 +12,8 @@ Light GetMainLight(float4 shadowCoord, bool receiveShadows, bool surfaceTypeTransparent); Light GetMainLight(float4 shadowCoord, float3 positionWS, half4 shadowMask, bool receiveShadows, bool surfaceTypeTransparent); Light GetMainLight(InputData inputData, half4 shadowMask, AmbientOcclusionFactor aoFactor, bool receiveShadows, bool surfaceTypeTransparent); -Light GetAdditionalLight(uint i, float3 positionWS, half4 shadowMask, bool receiveShadows, float3 normalWS = float3(0.0, 0.0, 0.0)); -Light GetAdditionalLight(uint i, InputData inputData, half4 shadowMask, AmbientOcclusionFactor aoFactor, bool receiveShadows, bool surfaceTypeTransparent, float3 geometricNormalWS = float3(0.0, 0.0, 0.0)); +Light GetAdditionalLight(uint i, float3 positionWS, half4 shadowMask, bool receiveShadows); +Light GetAdditionalLight(uint i, InputData inputData, half4 shadowMask, AmbientOcclusionFactor aoFactor, bool receiveShadows, bool surfaceTypeTransparent); #if !defined(_SURFACE_TYPE_TRANSPARENT_KEYWORD_DECLARED) #if !defined(_SURFACE_TYPE_TRANSPARENT) @@ -60,9 +60,9 @@ Light GetAdditionalLight(uint i, float3 positionWS, half4 shadowMask) } // Deprecated. Use GetAdditionalLight(i, inputData, shadowMask, aoFactor, receiveShadows, surfaceTypeTransparent). -Light GetAdditionalLight(uint i, InputData inputData, half4 shadowMask, AmbientOcclusionFactor aoFactor, float3 geometricNormalWS = float3(0.0, 0.0, 0.0)) +Light GetAdditionalLight(uint i, InputData inputData, half4 shadowMask, AmbientOcclusionFactor aoFactor) { - return GetAdditionalLight(i, inputData, shadowMask, aoFactor, !_RECEIVE_SHADOWS_OFF, _SURFACE_TYPE_TRANSPARENT, geometricNormalWS); + return GetAdditionalLight(i, inputData, shadowMask, aoFactor, !_RECEIVE_SHADOWS_OFF, _SURFACE_TYPE_TRANSPARENT); } // Prevents leaking the fallback keyword definitions to shaders that include this file. diff --git a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/RealtimeLights.hlsl b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/RealtimeLights.hlsl index 554f8fcbae6..376070b713e 100644 --- a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/RealtimeLights.hlsl +++ b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/RealtimeLights.hlsl @@ -161,7 +161,7 @@ Light GetAdditionalPerObjectLight(int perObjectLightIndex, float3 positionWS) { // Abstraction over Light input constants float4 lightPositionWS = _AdditionalLightsPosition[perObjectLightIndex]; - half3 color = _AdditionalLightsColor[perObjectLightIndex].rgb; + URP_LIGHT_ACCUM3 color = _AdditionalLightsColor[perObjectLightIndex].rgb; half4 distanceAndSpotAttenuation = _AdditionalLightsAttenuation[perObjectLightIndex]; half4 spotDirection = _AdditionalLightsSpotDir[perObjectLightIndex]; uint lightLayerMask = asuint(_AdditionalLightsLayerMasks[perObjectLightIndex]); @@ -255,9 +255,14 @@ Light GetAdditionalLight(uint i, float3 positionWS, half4 shadowMask, bool recei return GetAdditionalLight(i, positionWS, shadowMask, receiveShadows, normalWS, INVALID_SHADOW_SCREEN_POS, false); } -Light GetAdditionalLight(uint i, InputData inputData, half4 shadowMask, AmbientOcclusionFactor aoFactor, bool receiveShadows, bool isSurfaceTypeTransparent, float3 geometricNormalWS) +Light GetAdditionalLight(uint i, float3 positionWS, half4 shadowMask, bool receiveShadows) { - Light light = GetAdditionalLight(i, inputData.positionWS, shadowMask, receiveShadows, geometricNormalWS, inputData.positionCS.xy, true); + return GetAdditionalLight(i, positionWS, shadowMask, receiveShadows, float3(0.0, 0.0, 0.0)); +} + +Light GetAdditionalLight(uint i, InputData inputData, half4 shadowMask, AmbientOcclusionFactor aoFactor, bool receiveShadows, bool isSurfaceTypeTransparent) +{ + Light light = GetAdditionalLight(i, inputData.positionWS, shadowMask, receiveShadows, inputData.geometricNormalWS, inputData.positionCS.xy, true); if (!isSurfaceTypeTransparent && ScreenSpaceOcclusionAvailable() && IsLightingFeatureEnabled(DEBUGLIGHTINGFEATUREFLAGS_AMBIENT_OCCLUSION)) { diff --git a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/ShaderGraphFunctions.hlsl b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/ShaderGraphFunctions.hlsl index 1f690917deb..4d39fd69ed6 100644 --- a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/ShaderGraphFunctions.hlsl +++ b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/ShaderGraphFunctions.hlsl @@ -105,7 +105,8 @@ float3 shadergraph_LWReflectionProbe(float3 viewDir, float3 normalOS, float lod) #if USE_CLUSTER_LIGHT_LOOP return SAMPLE_TEXTURECUBE_LOD(_GlossyEnvironmentCubeMap, sampler_GlossyEnvironmentCubeMap, reflectVec, lod).rgb; #else - return DecodeHDREnvironment(SAMPLE_TEXTURECUBE_LOD(unity_SpecCube0, samplerunity_SpecCube0, reflectVec, lod), unity_SpecCube0_HDR); + // The probe's capture exposure (EV) is carried in the decode bias (z) + return SelectProbeExposureMultiplier(exp2((float)unity_SpecCube0_HDR.z)) * DecodeHDREnvironment(SAMPLE_TEXTURECUBE_LOD(unity_SpecCube0, samplerunity_SpecCube0, reflectVec, lod), unity_SpecCube0_HDR); #endif } diff --git a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/ShaderVariablesFunctions.hlsl b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/ShaderVariablesFunctions.hlsl index 8278d5ca702..b7dba015a07 100644 --- a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/ShaderVariablesFunctions.hlsl +++ b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/ShaderVariablesFunctions.hlsl @@ -388,15 +388,8 @@ float2 GetNormalizedScreenSpaceUV(float4 positionCS) // select4(data[i / 4], i % 4); uint Select4(uint4 v, uint i) { - // x = 0 = 00 - // y = 1 = 01 - // z = 2 = 10 - // w = 3 = 11 - uint mask0 = uint(int(i << 31) >> 31); - uint mask1 = uint(int(i << 30) >> 31); - return - (((v.w & mask0) | (v.z & ~mask0)) & mask1) | - (((v.y & mask0) | (v.x & ~mask0)) & ~mask1); + uint2 pair = (i & 2) ? v.zw : v.xy; + return (i & 1) ? pair.y : pair.x; } diff --git a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/ShadowSamplingData.hlsl b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/ShadowSamplingData.hlsl index b28e2ef89ba..968d51c99a8 100644 --- a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/ShadowSamplingData.hlsl +++ b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/ShadowSamplingData.hlsl @@ -7,6 +7,8 @@ struct ShadowSamplingData half4 shadowOffset1; float4 shadowmapSize; half softShadowQuality; + float softShadowKernelRadius; + float softShadowFrameIndex; }; #endif // UNIVERSAL_SHADOW_SAMPLING_DATA_INCLUDED diff --git a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Shadows.deprecated.hlsl b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Shadows.deprecated.hlsl index a5fbb6c275c..17b5132ac14 100644 --- a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Shadows.deprecated.hlsl +++ b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Shadows.deprecated.hlsl @@ -66,14 +66,14 @@ // Deprecated keyword-reading wrappers, kept for external back-compat. // New code passes the keyword state as parameters (Shadows.hlsl). -float4 TransformWorldToShadowCoord(float3 positionWS, bool surfaceTypeTransparent, float3 normalWS = float3(0.0, 0.0, 0.0)); +float4 TransformWorldToShadowCoord(float3 positionWS, bool surfaceTypeTransparent); half SampleMainLightRealtimeShadow(float4 shadowCoord, half4 shadowParams, ShadowSamplingData shadowSamplingData, bool surfaceTypeTransparent); half SampleMainLightRealtimeShadow(float4 shadowCoord, bool surfaceTypeTransparent); -half SampleAdditionalLightRealtimeShadow(int lightIndex, float3 positionWS, half3 lightDirection, half4 shadowParams, ShadowSamplingData shadowSamplingData, float3 normalWS = float3(0.0, 0.0, 0.0)); -half SampleAdditionalLightRealtimeShadow(int lightIndex, float3 positionWS, half3 lightDirection, float3 normalWS = float3(0.0, 0.0, 0.0)); +half SampleAdditionalLightRealtimeShadow(int lightIndex, float3 positionWS, half3 lightDirection, half4 shadowParams, ShadowSamplingData shadowSamplingData); +half SampleAdditionalLightRealtimeShadow(int lightIndex, float3 positionWS, half3 lightDirection); half MainLightShadow(float4 shadowCoord, float3 positionWS, half4 shadowMask, half4 occlusionProbeChannels, bool receiveShadows, bool surfaceTypeTransparent); -half AdditionalLightShadow(int lightIndex, float3 positionWS, half3 lightDirection, half4 shadowMask, half4 occlusionProbeChannels, bool receiveShadows, float3 normalWS = float3(0.0, 0.0, 0.0)); -float4 GetShadowCoord(VertexPositionInputs vertexInput, bool surfaceTypeTransparent, float3 normalWS = float3(0.0, 0.0, 0.0)); +half AdditionalLightShadow(int lightIndex, float3 positionWS, half3 lightDirection, half4 shadowMask, half4 occlusionProbeChannels, bool receiveShadows); +float4 GetShadowCoord(VertexPositionInputs vertexInput, bool surfaceTypeTransparent); bool AdditionalLightShadowsAvailable(); half4 GetAdditionalLightShadowParams(int lightIndex); diff --git a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Shadows.hlsl b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Shadows.hlsl index 07e2f0624e2..78998cdf425 100644 --- a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Shadows.hlsl +++ b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Shadows.hlsl @@ -84,21 +84,21 @@ #endif #endif -#if !defined(_MAIN_LIGHT_SHADOWS_SOFT_PCSS_KEYWORD_DECLARED) - #if !defined(_MAIN_LIGHT_SHADOWS_SOFT_PCSS) - static const bool _MAIN_LIGHT_SHADOWS_SOFT_PCSS = 0; - #elif DEFINED_NONZERO(_MAIN_LIGHT_SHADOWS_SOFT_PCSS) - #undef _MAIN_LIGHT_SHADOWS_SOFT_PCSS - #define _MAIN_LIGHT_SHADOWS_SOFT_PCSS 1 +#if !defined(_SHADOWS_PCSS_KEYWORD_DECLARED) + #if !defined(_SHADOWS_PCSS) + static const bool _SHADOWS_PCSS = 0; + #elif DEFINED_NONZERO(_SHADOWS_PCSS) + #undef _SHADOWS_PCSS + #define _SHADOWS_PCSS 1 #endif #endif -#if !defined(_ADDITIONAL_LIGHT_SHADOWS_SOFT_PCSS_KEYWORD_DECLARED) - #if !defined(_ADDITIONAL_LIGHT_SHADOWS_SOFT_PCSS) - static const bool _ADDITIONAL_LIGHT_SHADOWS_SOFT_PCSS = 0; - #elif DEFINED_NONZERO(_ADDITIONAL_LIGHT_SHADOWS_SOFT_PCSS) - #undef _ADDITIONAL_LIGHT_SHADOWS_SOFT_PCSS - #define _ADDITIONAL_LIGHT_SHADOWS_SOFT_PCSS 1 +#if !defined(_SHADOW_RECEIVER_NORMAL_BIAS_KEYWORD_DECLARED) + #if !defined(_SHADOW_RECEIVER_NORMAL_BIAS) + static const bool _SHADOW_RECEIVER_NORMAL_BIAS = 0; + #elif DEFINED_NONZERO(_SHADOW_RECEIVER_NORMAL_BIAS) + #undef _SHADOW_RECEIVER_NORMAL_BIAS + #define _SHADOW_RECEIVER_NORMAL_BIAS 1 #endif #endif @@ -175,14 +175,10 @@ bool SoftShadowsAvailable() return _SHADOWS_SOFT || _SHADOWS_SOFT_LOW || _SHADOWS_SOFT_MEDIUM || _SHADOWS_SOFT_HIGH; } -bool MainLightPCSSAvailable() +// PCSS is layered on the per-light soft shadows. Each light still picks its filter. +bool ShadowsPCSSAvailable() { - return _MAIN_LIGHT_SHADOWS_SOFT_PCSS; -} - -bool AdditionalLightPCSSAvailable() -{ - return _ADDITIONAL_LIGHT_SHADOWS_SOFT_PCSS; + return _SHADOWS_PCSS; } // Should match: UnityEngine.Rendering.Universal + 1 @@ -190,6 +186,7 @@ bool AdditionalLightPCSSAvailable() #define SOFT_SHADOW_QUALITY_LOW half(1) #define SOFT_SHADOW_QUALITY_MEDIUM half(2) #define SOFT_SHADOW_QUALITY_HIGH half(3) +#define SOFT_SHADOW_QUALITY_PCSS half(4) // Passed by entry points that have no screen position. Those paths never take the PCSS branch. #define INVALID_SHADOW_SCREEN_POS float2(-1.0, -1.0) @@ -272,13 +269,8 @@ SAMPLER_CMP(sampler_LinearClampCompare); float4 _MainLightShadowParams; // (x: shadowStrength, y: >= 1.0 if soft shadows, 0.0 otherwise, z: main light fade scale, w: main light fade bias) float4 _MainLightShadowReceiverNormalBias; // world-space receiver normal bias, one component per cascade (all zero in caster mode) -float4 _AdditionalShadowFadeParams; // x: additional light fade scale, y: additional light fade bias, z: 0.0, w: 0.0) - -// Main light PCSS. Loose uniforms until the C# side fills them, then they move into GlobalShaderVariables.hlsl. -float4 _MainLightPCSSParams0[MAX_SHADOW_CASCADES + 1]; // (x: depth2RadialScale, y: radial2DepthScale, z: maxSampleZDistance, w: maxPCSSOffset) -float4 _MainLightPCSSParams1[MAX_SHADOW_CASCADES + 1]; // (x: minFilterSizeTexels, y: minFilterRadial2DepthScale, z: blockerRadial2DepthScale, w: blockerClumpSampleExponent) -float4 _MainLightPCSSAtlas[MAX_SHADOW_CASCADES + 1]; // (xy: atlas tile offset in UV, zw: atlas tile scale in UV) -float4 _MainLightPCSSScalars; // (x: tile texel size = 1/tileResolution, y: blockerSampleCount, z: filterSampleCount, w: TAA frame index) +float2 _MainLightSoftShadowKernelParams; // (x: soft shadow kernel radius, y: TAA frame index) +float4 _AdditionalShadowFadeParams; // (x: additional light fade scale, y: additional light fade bias, z: PCSS temporal frame index, w: 0.0) // Point lights can use 6 shadow slices. Some mobile GPUs performance decrease drastically with uniform // blocks bigger than 8kb while others have a 64kb max uniform block size. This number ensures size of buffer @@ -286,19 +278,25 @@ float4 _MainLightPCSSScalars; // (x: tile texel si // devices where max number of uniforms per shader GL_MAX_FRAGMENT_UNIFORM_VECTORS is low (224) // GLES3 causes a performance regression in some devices when using CBUFFER. -#ifndef LIGHT_SHADOWS_NO_CBUFFER +#if defined(URP_PERSISTENT_CONSTANT_BUFFERS_ACTIVE) CBUFFER_START(AdditionalLightShadows) #endif float4x4 _AdditionalLightsWorldToShadow[MAX_VISIBLE_LIGHTS]; // Per-shadow-slice-data float4 _AdditionalShadowParams[MAX_VISIBLE_LIGHTS]; // Per-light data: (x: shadowStrength, y: softShadows, z: light type (Spot: 0, Point: 1), w: perLightFirstShadowSliceIndex) -float4 _AdditionalLightsPCSSParams[MAX_VISIBLE_LIGHTS]; // Per-light data: (x: softness, y: min filter radius, z: blocker sample count, w: filter sample count) -float4 _AdditionalLightsPCSSZParams[MAX_VISIBLE_LIGHTS]; // Per-light data: blocker depth linearization ((f-n)/n, 1.0, (f-n)/(n*f), 1/f) -float4 _AdditionalLightsPCSSAtlas[MAX_VISIBLE_LIGHTS]; // Per-shadow-slice-data: (xy: atlas tile offset in UV, zw: atlas tile scale in UV) float4 _AdditionalShadowReceiverNormalBias[(MAX_VISIBLE_LIGHTS + 3) / 4]; // Per-light world-space receiver normal bias, four lights packed per float4 (all zero in caster mode) -#ifndef LIGHT_SHADOWS_NO_CBUFFER +#if defined(URP_PERSISTENT_CONSTANT_BUFFERS_ACTIVE) CBUFFER_END #endif -float4 _AdditionalLightsPCSSScalars; // (xy: shadow atlas size in texels, z: TAA frame index, w: unused) + +// Kept out of AdditionalLightShadows so that only the PCSS variants reference it, and in a structured buffer so that it +// takes no constant buffer slot. MAX_VISIBLE_LIGHTS float4 of each, in this order: +// per-light params (x: softness, y: min filter radius, z: blocker sample count, w: filter sample count), +// per-light blocker depth linearization ((f-n)/n, 1.0, (f-n)/(n*f), 1/f), +// per-shadow-slice atlas rects (xy: atlas tile offset in UV, zw: atlas tile scale in UV). +// OpenGL has no PCSS (ShadowUtils.SupportsPCSS), and OpenGL ES fragment shaders may not read structured buffers. +#if !defined(SHADER_API_GLES3) && !defined(URP_SHADER_API_GLCORE) +StructuredBuffer _AdditionalLightsPCSSData; +#endif // x: depth bias, // y: normal bias, @@ -306,6 +304,8 @@ float4 _AdditionalLightsPCSSScalars; // (xy: shadow // w: unused float4 _ShadowBias; +float _ZClip; + half IsSpotLight() { return round(_ShadowBias.z) == 0.0 ? 1 : 0; @@ -334,6 +334,8 @@ ShadowSamplingData GetMainLightShadowSamplingData() // shadowmapSize is used in SampleShadowmapFiltered otherwise shadowSamplingData.shadowmapSize = _MainLightShadowmapSize; shadowSamplingData.softShadowQuality = half(_MainLightShadowParams.y); + shadowSamplingData.softShadowKernelRadius = _MainLightSoftShadowKernelParams.x; + shadowSamplingData.softShadowFrameIndex = _MainLightSoftShadowKernelParams.y; return shadowSamplingData; } @@ -419,56 +421,217 @@ half SampleScreenSpaceShadowmap(float4 shadowCoord) return attenuation; } -real SampleShadowmapFilteredLowQuality(TEXTURE2D_SHADOW_PARAM(ShadowMap, sampler_ShadowMap), float4 shadowCoord, ShadowSamplingData samplingData) +// Must match ShadowUtils.GetSoftShadowKernelRadius +#define SOFT_SHADOW_KERNEL_RADIUS_LOW 1.5 +#define SOFT_SHADOW_KERNEL_RADIUS_MEDIUM 2.5 +#define SOFT_SHADOW_KERNEL_RADIUS_HIGH 3.5 + +bool IsSoftShadowKernelNarrowed(float kernelRadius, float qualityKernelRadius) +{ + return kernelRadius > 0.0 && kernelRadius < qualityKernelRadius; +} + +bool IsSoftShadowKernelWidened(float kernelRadius, float qualityKernelRadius) +{ + return kernelRadius > qualityKernelRadius; +} + +// Bilinear fetches per axis of the quality's filter +int GetSoftShadowFetchCount(float qualityKernelRadius) { - // 4-tap hardware comparison - real4 attenuation4; - attenuation4.x = real(SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, shadowCoord.xyz + float3(samplingData.shadowOffset0.xy, 0))); - attenuation4.y = real(SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, shadowCoord.xyz + float3(samplingData.shadowOffset0.zw, 0))); - attenuation4.z = real(SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, shadowCoord.xyz + float3(samplingData.shadowOffset1.xy, 0))); - attenuation4.w = real(SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, shadowCoord.xyz + float3(samplingData.shadowOffset1.zw, 0))); - return dot(attenuation4, real(0.25)); + return (int)(qualityKernelRadius + 0.5); } -real SampleShadowmapFilteredMediumQuality(TEXTURE2D_SHADOW_PARAM(ShadowMap, sampler_ShadowMap), float4 shadowCoord, ShadowSamplingData samplingData) +// Uniform disk of PCF fetches, rotated per pixel. +real SampleShadowmapFilteredDisk(TEXTURE2D_SHADOW_PARAM(ShadowMap, sampler_ShadowMap), float4 shadowCoord, ShadowSamplingData samplingData, float kernelRadius, int fetchCount, float2 positionSS) { - float fetchesWeights[9]; - float2 fetchesUV[9]; - SampleShadow_ComputeSamples_Tent_Filter_5x5(float, samplingData.shadowmapSize, shadowCoord, fetchesWeights, fetchesUV); + int sampleCount = fetchCount * fetchCount; + float2 noiseCoord = all(positionSS >= 0.0) ? positionSS : shadowCoord.xy * samplingData.shadowmapSize.zw; + float rotationAngle = InterleavedGradientNoise(noiseCoord, (int)samplingData.softShadowFrameIndex) * TWO_PI; + float2 rotation = float2(sin(rotationAngle), cos(rotationAngle)); + + // 0.81649658 is sqrt(2/3): a uniform disk of this radius has the same variance per axis as a tent of radius 1, so the penumbra width carries over + float diskRadius = kernelRadius * 0.81649658; + float sampleCountInverse = rcp((float)sampleCount); + float sampleCountBias = 0.5 * sampleCountInverse; + + real attenuation = 0.0; + for (int i = 0; i < sampleCount; i++) + { + float2 offset = ComputeFibonacciSpiralDiskSample_Punctual(i, diskRadius, sampleCountInverse, sampleCountBias); + offset = float2(offset.x * rotation.y + offset.y * rotation.x, offset.x * -rotation.x + offset.y * rotation.y); + attenuation += real(SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(shadowCoord.xy + offset * samplingData.shadowmapSize.xy, shadowCoord.z))); + } + + return attenuation * real(sampleCountInverse); +} + +float SoftShadowTentIntegral(float x, float radiusRcp) +{ + // x in units of the radius + float t = clamp(x * radiusRcp, -1.0, 1.0); + + // Area of a unit-radius tent from -1 to t, which equals the area of the radius tent from -radius to x + return 0.5 + t * (1.0 - 0.5 * abs(t)); +} + +// Weights and texel offsets of the bilinear fetches along one axis for a tent of any radius +void GetSoftShadowTentFetches(int fetchCount, float offsetFromTentCenterToCenterOfFetches, float radiusRcp, out float4 fetchesWeights, out float4 fetchesOffsets) +{ + fetchesWeights = 0.0; + fetchesOffsets = 0.0; + + float pairStart = SoftShadowTentIntegral(-fetchCount - offsetFromTentCenterToCenterOfFetches, radiusRcp); + UNITY_UNROLL + for (int i = 0; i < fetchCount; i++) + { + float pairEdge = 2 * i - fetchCount; + float pairMiddle = SoftShadowTentIntegral(pairEdge + 1.0 - offsetFromTentCenterToCenterOfFetches, radiusRcp); + float pairEnd = SoftShadowTentIntegral(pairEdge + 2.0 - offsetFromTentCenterToCenterOfFetches, radiusRcp); + + // The difference of the integrals at a texel's edges is the tent's area over that texel, which is its weight + float firstTexelWeight = pairMiddle - pairStart; + float secondTexelWeight = pairEnd - pairMiddle; - return fetchesWeights[0] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[0].xy, shadowCoord.z)) - + fetchesWeights[1] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[1].xy, shadowCoord.z)) - + fetchesWeights[2] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[2].xy, shadowCoord.z)) - + fetchesWeights[3] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[3].xy, shadowCoord.z)) - + fetchesWeights[4] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[4].xy, shadowCoord.z)) - + fetchesWeights[5] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[5].xy, shadowCoord.z)) - + fetchesWeights[6] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[6].xy, shadowCoord.z)) - + fetchesWeights[7] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[7].xy, shadowCoord.z)) - + fetchesWeights[8] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[8].xy, shadowCoord.z)); + fetchesWeights[i] = firstTexelWeight + secondTexelWeight; + fetchesOffsets[i] = pairEdge + 0.5 + secondTexelWeight / max(fetchesWeights[i], 1e-6); + pairStart = pairEnd; + } } -real SampleShadowmapFilteredHighQuality(TEXTURE2D_SHADOW_PARAM(ShadowMap, sampler_ShadowMap), float4 shadowCoord, ShadowSamplingData samplingData) +// Tent PCF of any radius up to fetchCount - 0.5 texels, from fetchCount x fetchCount bilinear fetches. +void ComputeSoftShadowTentSamples(int fetchCount, float4 shadowMapTexelSize, float2 coord, float radius, out float fetchesWeights[16], out float2 fetchesUV[16]) { - float fetchesWeights[16]; - float2 fetchesUV[16]; - SampleShadow_ComputeSamples_Tent_Filter_7x7(float, samplingData.shadowmapSize, shadowCoord, fetchesWeights, fetchesUV); + UNITY_UNROLL for (int z = 0; z < 16; z++) { fetchesWeights[z] = 0.0; fetchesUV[z] = coord; } + + float2 tentCenterInTexelSpace = coord * shadowMapTexelSize.zw; + float2 centerOfFetchesInTexelSpace = floor(tentCenterInTexelSpace + 0.5); + float2 offsetFromTentCenterToCenterOfFetches = tentCenterInTexelSpace - centerOfFetchesInTexelSpace; - return fetchesWeights[0] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[0].xy, shadowCoord.z)) - + fetchesWeights[1] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[1].xy, shadowCoord.z)) - + fetchesWeights[2] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[2].xy, shadowCoord.z)) - + fetchesWeights[3] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[3].xy, shadowCoord.z)) - + fetchesWeights[4] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[4].xy, shadowCoord.z)) - + fetchesWeights[5] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[5].xy, shadowCoord.z)) - + fetchesWeights[6] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[6].xy, shadowCoord.z)) - + fetchesWeights[7] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[7].xy, shadowCoord.z)) - + fetchesWeights[8] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[8].xy, shadowCoord.z)) - + fetchesWeights[9] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[9].xy, shadowCoord.z)) - + fetchesWeights[10] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[10].xy, shadowCoord.z)) - + fetchesWeights[11] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[11].xy, shadowCoord.z)) - + fetchesWeights[12] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[12].xy, shadowCoord.z)) - + fetchesWeights[13] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[13].xy, shadowCoord.z)) - + fetchesWeights[14] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[14].xy, shadowCoord.z)) - + fetchesWeights[15] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[15].xy, shadowCoord.z)); + // Callers only take this path with a positive radius; the clamp avoids a division by zero in dead code + float radiusRcp = rcp(max(radius, FLT_MIN)); + float4 fetchesWeightsU, fetchesOffsetsU, fetchesWeightsV, fetchesOffsetsV; + GetSoftShadowTentFetches(fetchCount, offsetFromTentCenterToCenterOfFetches.x, radiusRcp, fetchesWeightsU, fetchesOffsetsU); + GetSoftShadowTentFetches(fetchCount, offsetFromTentCenterToCenterOfFetches.y, radiusRcp, fetchesWeightsV, fetchesOffsetsV); + + float2 bilinearFetchOrigin = centerOfFetchesInTexelSpace * shadowMapTexelSize.xy; + UNITY_UNROLL + for (int v = 0; v < fetchCount; v++) + { + UNITY_UNROLL + for (int u = 0; u < fetchCount; u++) + { + fetchesWeights[v * fetchCount + u] = fetchesWeightsU[u] * fetchesWeightsV[v]; + fetchesUV[v * fetchCount + u] = bilinearFetchOrigin + float2(fetchesOffsetsU[u], fetchesOffsetsV[v]) * shadowMapTexelSize.xy; + } + } +} + +real SampleShadowmapFilteredLowQuality(TEXTURE2D_SHADOW_PARAM(ShadowMap, sampler_ShadowMap), float4 shadowCoord, ShadowSamplingData samplingData, float2 positionSS = INVALID_SHADOW_SCREEN_POS) +{ + real attenuation; + UNITY_BRANCH + if (IsSoftShadowKernelWidened(samplingData.softShadowKernelRadius, SOFT_SHADOW_KERNEL_RADIUS_LOW)) + { + attenuation = SampleShadowmapFilteredDisk(TEXTURE2D_SHADOW_ARGS(ShadowMap, sampler_ShadowMap), shadowCoord, samplingData, samplingData.softShadowKernelRadius, GetSoftShadowFetchCount(SOFT_SHADOW_KERNEL_RADIUS_LOW), positionSS); + } + else if (IsSoftShadowKernelNarrowed(samplingData.softShadowKernelRadius, SOFT_SHADOW_KERNEL_RADIUS_LOW)) + { + float fetchesWeights[16]; + float2 fetchesUV[16]; + ComputeSoftShadowTentSamples(GetSoftShadowFetchCount(SOFT_SHADOW_KERNEL_RADIUS_LOW), samplingData.shadowmapSize, shadowCoord.xy, samplingData.softShadowKernelRadius, fetchesWeights, fetchesUV); + + attenuation = fetchesWeights[0] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[0].xy, shadowCoord.z)) + + fetchesWeights[1] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[1].xy, shadowCoord.z)) + + fetchesWeights[2] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[2].xy, shadowCoord.z)) + + fetchesWeights[3] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[3].xy, shadowCoord.z)); + } + else + { + // 4-tap hardware comparison + real4 attenuation4; + attenuation4.x = real(SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, shadowCoord.xyz + float3(samplingData.shadowOffset0.xy, 0))); + attenuation4.y = real(SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, shadowCoord.xyz + float3(samplingData.shadowOffset0.zw, 0))); + attenuation4.z = real(SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, shadowCoord.xyz + float3(samplingData.shadowOffset1.xy, 0))); + attenuation4.w = real(SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, shadowCoord.xyz + float3(samplingData.shadowOffset1.zw, 0))); + attenuation = dot(attenuation4, real(0.25)); + } + return attenuation; +} + +real SampleShadowmapFilteredMediumQuality(TEXTURE2D_SHADOW_PARAM(ShadowMap, sampler_ShadowMap), float4 shadowCoord, ShadowSamplingData samplingData, float2 positionSS = INVALID_SHADOW_SCREEN_POS) +{ + real attenuation; + UNITY_BRANCH + if (IsSoftShadowKernelWidened(samplingData.softShadowKernelRadius, SOFT_SHADOW_KERNEL_RADIUS_MEDIUM)) + { + attenuation = SampleShadowmapFilteredDisk(TEXTURE2D_SHADOW_ARGS(ShadowMap, sampler_ShadowMap), shadowCoord, samplingData, samplingData.softShadowKernelRadius, GetSoftShadowFetchCount(SOFT_SHADOW_KERNEL_RADIUS_MEDIUM), positionSS); + } + else + { + float fetchesWeights[16]; + float2 fetchesUV[16]; + if (IsSoftShadowKernelNarrowed(samplingData.softShadowKernelRadius, SOFT_SHADOW_KERNEL_RADIUS_MEDIUM)) + { + ComputeSoftShadowTentSamples(GetSoftShadowFetchCount(SOFT_SHADOW_KERNEL_RADIUS_MEDIUM), samplingData.shadowmapSize, shadowCoord.xy, samplingData.softShadowKernelRadius, fetchesWeights, fetchesUV); + } + else + { + SampleShadow_ComputeSamples_Tent_Filter_5x5(float, samplingData.shadowmapSize, shadowCoord, fetchesWeights, fetchesUV); + } + + attenuation = fetchesWeights[0] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[0].xy, shadowCoord.z)) + + fetchesWeights[1] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[1].xy, shadowCoord.z)) + + fetchesWeights[2] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[2].xy, shadowCoord.z)) + + fetchesWeights[3] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[3].xy, shadowCoord.z)) + + fetchesWeights[4] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[4].xy, shadowCoord.z)) + + fetchesWeights[5] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[5].xy, shadowCoord.z)) + + fetchesWeights[6] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[6].xy, shadowCoord.z)) + + fetchesWeights[7] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[7].xy, shadowCoord.z)) + + fetchesWeights[8] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[8].xy, shadowCoord.z)); + } + return attenuation; +} + +real SampleShadowmapFilteredHighQuality(TEXTURE2D_SHADOW_PARAM(ShadowMap, sampler_ShadowMap), float4 shadowCoord, ShadowSamplingData samplingData, float2 positionSS = INVALID_SHADOW_SCREEN_POS) +{ + real attenuation; + UNITY_BRANCH + if (IsSoftShadowKernelWidened(samplingData.softShadowKernelRadius, SOFT_SHADOW_KERNEL_RADIUS_HIGH)) + { + attenuation = SampleShadowmapFilteredDisk(TEXTURE2D_SHADOW_ARGS(ShadowMap, sampler_ShadowMap), shadowCoord, samplingData, samplingData.softShadowKernelRadius, GetSoftShadowFetchCount(SOFT_SHADOW_KERNEL_RADIUS_HIGH), positionSS); + } + else + { + float fetchesWeights[16]; + float2 fetchesUV[16]; + if (IsSoftShadowKernelNarrowed(samplingData.softShadowKernelRadius, SOFT_SHADOW_KERNEL_RADIUS_HIGH)) + { + ComputeSoftShadowTentSamples(GetSoftShadowFetchCount(SOFT_SHADOW_KERNEL_RADIUS_HIGH), samplingData.shadowmapSize, shadowCoord.xy, samplingData.softShadowKernelRadius, fetchesWeights, fetchesUV); + } + else + { + SampleShadow_ComputeSamples_Tent_Filter_7x7(float, samplingData.shadowmapSize, shadowCoord, fetchesWeights, fetchesUV); + } + + attenuation = fetchesWeights[0] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[0].xy, shadowCoord.z)) + + fetchesWeights[1] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[1].xy, shadowCoord.z)) + + fetchesWeights[2] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[2].xy, shadowCoord.z)) + + fetchesWeights[3] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[3].xy, shadowCoord.z)) + + fetchesWeights[4] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[4].xy, shadowCoord.z)) + + fetchesWeights[5] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[5].xy, shadowCoord.z)) + + fetchesWeights[6] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[6].xy, shadowCoord.z)) + + fetchesWeights[7] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[7].xy, shadowCoord.z)) + + fetchesWeights[8] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[8].xy, shadowCoord.z)) + + fetchesWeights[9] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[9].xy, shadowCoord.z)) + + fetchesWeights[10] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[10].xy, shadowCoord.z)) + + fetchesWeights[11] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[11].xy, shadowCoord.z)) + + fetchesWeights[12] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[12].xy, shadowCoord.z)) + + fetchesWeights[13] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[13].xy, shadowCoord.z)) + + fetchesWeights[14] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[14].xy, shadowCoord.z)) + + fetchesWeights[15] * SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(fetchesUV[15].xy, shadowCoord.z)); + } + return attenuation; } // Separable tent kernel, one axis: 4 fetch columns cover the 7x7 (HIGH) tent; the 5x5 (MEDIUM) tent uses three of @@ -489,59 +652,112 @@ void SampleShadow_TentAxis(float o, bool high, out float4 weights, out float4 of } // Soft filter for runtime-selected quality (per-light value, and dynamic-keyword builds). -half SampleShadowmapFilteredRuntimeQuality(TEXTURE2D_SHADOW_PARAM(ShadowMap, sampler_ShadowMap), float4 shadowCoord, ShadowSamplingData samplingData, half quality) +half SampleShadowmapFilteredRuntimeQuality(TEXTURE2D_SHADOW_PARAM(ShadowMap, sampler_ShadowMap), float4 shadowCoord, ShadowSamplingData samplingData, half quality, float2 positionSS = INVALID_SHADOW_SCREEN_POS) { half attenuation = 0.0; if (quality < SOFT_SHADOW_QUALITY_MEDIUM) { - attenuation = half(SampleShadowmapFilteredLowQuality(TEXTURE2D_SHADOW_ARGS(ShadowMap, sampler_ShadowMap), shadowCoord, samplingData)); + attenuation = half(SampleShadowmapFilteredLowQuality(TEXTURE2D_SHADOW_ARGS(ShadowMap, sampler_ShadowMap), shadowCoord, samplingData, positionSS)); } else { - float4 texelSize = samplingData.shadowmapSize; - float2 tentCenter = shadowCoord.xy * texelSize.zw; - float2 fetchCenter = floor(tentCenter + 0.5); - float2 o = tentCenter - fetchCenter; + float kernelRadius = samplingData.softShadowKernelRadius; + float qualityKernelRadius = quality >= SOFT_SHADOW_QUALITY_HIGH ? SOFT_SHADOW_KERNEL_RADIUS_HIGH : SOFT_SHADOW_KERNEL_RADIUS_MEDIUM; - float4 wU, wV, u, v; UNITY_BRANCH - if (quality >= SOFT_SHADOW_QUALITY_HIGH) + if (IsSoftShadowKernelWidened(kernelRadius, qualityKernelRadius)) { - SampleShadow_TentAxis(o.x, true, wU, u); - SampleShadow_TentAxis(o.y, true, wV, v); - wV *= 0.081632 * 0.081632; - u = fetchCenter.x * texelSize.x + u * texelSize.x; - v = fetchCenter.y * texelSize.y + v * texelSize.y; + attenuation = half(SampleShadowmapFilteredDisk(TEXTURE2D_SHADOW_ARGS(ShadowMap, sampler_ShadowMap), shadowCoord, samplingData, kernelRadius, GetSoftShadowFetchCount(qualityKernelRadius), positionSS)); } else { - SampleShadow_TentAxis(o.x, false, wU, u); - SampleShadow_TentAxis(o.y, false, wV, v); - wV *= 0.16 * 0.16; - u = fetchCenter.x * texelSize.x + u * texelSize.x; - v = fetchCenter.y * texelSize.y + v * texelSize.y; - } - half4 hwU = half4(wU); + float4 texelSize = samplingData.shadowmapSize; + float2 tentCenter = shadowCoord.xy * texelSize.zw; + float2 fetchCenter = floor(tentCenter + 0.5); + float2 o = tentCenter - fetchCenter; - UNITY_UNROLL for (int j = 0; j < 4; j++) - { - half4 s; - s.x = half(SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(u.x, v[j], shadowCoord.z))); - s.y = half(SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(u.y, v[j], shadowCoord.z))); - s.z = half(SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(u.z, v[j], shadowCoord.z))); - s.w = half(SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(u.w, v[j], shadowCoord.z))); - attenuation += half(wV[j]) * dot(s, hwU); + bool narrowed = IsSoftShadowKernelNarrowed(kernelRadius, qualityKernelRadius); + float radiusRcp = rcp(max(kernelRadius, FLT_MIN)); + + float4 wU, wV, u, v; + UNITY_BRANCH + if (quality >= SOFT_SHADOW_QUALITY_HIGH) + { + UNITY_BRANCH + if (narrowed) + { + GetSoftShadowTentFetches(GetSoftShadowFetchCount(SOFT_SHADOW_KERNEL_RADIUS_HIGH), o.x, radiusRcp, wU, u); + GetSoftShadowTentFetches(GetSoftShadowFetchCount(SOFT_SHADOW_KERNEL_RADIUS_HIGH), o.y, radiusRcp, wV, v); + } + else + { + SampleShadow_TentAxis(o.x, true, wU, u); + SampleShadow_TentAxis(o.y, true, wV, v); + wV *= 0.081632 * 0.081632; + } + + u = fetchCenter.x * texelSize.x + u * texelSize.x; + v = fetchCenter.y * texelSize.y + v * texelSize.y; + half4 hwU = half4(wU); + half4 hwV = half4(wV); + + UNITY_UNROLL for (int j = 0; j < 4; j++) + { + half4 s; + s.x = half(SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(u.x, v[j], shadowCoord.z))); + s.y = half(SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(u.y, v[j], shadowCoord.z))); + s.z = half(SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(u.z, v[j], shadowCoord.z))); + s.w = half(SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(u.w, v[j], shadowCoord.z))); + attenuation += hwV[j] * dot(s, hwU); + } + } + else + { + UNITY_BRANCH + if (narrowed) + { + GetSoftShadowTentFetches(GetSoftShadowFetchCount(SOFT_SHADOW_KERNEL_RADIUS_MEDIUM), o.x, radiusRcp, wU, u); + GetSoftShadowTentFetches(GetSoftShadowFetchCount(SOFT_SHADOW_KERNEL_RADIUS_MEDIUM), o.y, radiusRcp, wV, v); + + // The loop below reads the x, y and w columns of the 5x5 tent + wU = wU.xyzz; u = u.xyzz; + wV = wV.xyzz; v = v.xyzz; + } + else + { + SampleShadow_TentAxis(o.x, false, wU, u); + SampleShadow_TentAxis(o.y, false, wV, v); + wV *= 0.16 * 0.16; + } + + u = fetchCenter.x * texelSize.x + u * texelSize.x; + v = fetchCenter.y * texelSize.y + v * texelSize.y; + + half3 hwU = half3(wU.xyw); + half3 hwV = half3(wV.xyw); + float3 rowV = v.xyw; + + UNITY_UNROLL for (int j = 0; j < 3; j++) + { + half3 s; + s.x = half(SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(u.x, rowV[j], shadowCoord.z))); + s.y = half(SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(u.y, rowV[j], shadowCoord.z))); + s.z = half(SAMPLE_TEXTURE2D_SHADOW(ShadowMap, sampler_ShadowMap, float3(u.w, rowV[j], shadowCoord.z))); + attenuation += hwV[j] * dot(s, hwU); + } + } } } return attenuation; } -half SampleShadowmapFiltered(TEXTURE2D_SHADOW_PARAM(ShadowMap, sampler_ShadowMap), float4 shadowCoord, ShadowSamplingData samplingData) +half SampleShadowmapFiltered(TEXTURE2D_SHADOW_PARAM(ShadowMap, sampler_ShadowMap), float4 shadowCoord, ShadowSamplingData samplingData, float2 positionSS = INVALID_SHADOW_SCREEN_POS) { - return SampleShadowmapFilteredRuntimeQuality(TEXTURE2D_SHADOW_ARGS(ShadowMap, sampler_ShadowMap), shadowCoord, samplingData, samplingData.softShadowQuality); + return SampleShadowmapFilteredRuntimeQuality(TEXTURE2D_SHADOW_ARGS(ShadowMap, sampler_ShadowMap), shadowCoord, samplingData, samplingData.softShadowQuality, positionSS); } -real SampleShadowmap(TEXTURE2D_SHADOW_PARAM(ShadowMap, sampler_ShadowMap), float4 shadowCoord, ShadowSamplingData samplingData, half4 shadowParams, bool isPerspectiveProjection = true) +// positionSS rotates the disk filter of a widened soft shadow kernel +real SampleShadowmap(TEXTURE2D_SHADOW_PARAM(ShadowMap, sampler_ShadowMap), float4 shadowCoord, ShadowSamplingData samplingData, half4 shadowParams, bool isPerspectiveProjection = true, float2 positionSS = INVALID_SHADOW_SCREEN_POS) { // Compiler will optimize this branch away as long as isPerspectiveProjection is known at compile time if (isPerspectiveProjection) @@ -559,7 +775,7 @@ real SampleShadowmap(TEXTURE2D_SHADOW_PARAM(ShadowMap, sampler_ShadowMap), float if (quality > SOFT_SHADOW_QUALITY_OFF) { - attenuation = SampleShadowmapFilteredRuntimeQuality(TEXTURE2D_SHADOW_ARGS(ShadowMap, sampler_ShadowMap), shadowCoord, samplingData, quality); + attenuation = SampleShadowmapFilteredRuntimeQuality(TEXTURE2D_SHADOW_ARGS(ShadowMap, sampler_ShadowMap), shadowCoord, samplingData, quality, positionSS); } else { @@ -568,21 +784,21 @@ real SampleShadowmap(TEXTURE2D_SHADOW_PARAM(ShadowMap, sampler_ShadowMap), float #else if (_SHADOWS_SOFT_LOW) { - attenuation = SampleShadowmapFilteredLowQuality(TEXTURE2D_SHADOW_ARGS(ShadowMap, sampler_ShadowMap), shadowCoord, samplingData); + attenuation = SampleShadowmapFilteredLowQuality(TEXTURE2D_SHADOW_ARGS(ShadowMap, sampler_ShadowMap), shadowCoord, samplingData, positionSS); } else if (_SHADOWS_SOFT_MEDIUM) { - attenuation = SampleShadowmapFilteredMediumQuality(TEXTURE2D_SHADOW_ARGS(ShadowMap, sampler_ShadowMap), shadowCoord, samplingData); + attenuation = SampleShadowmapFilteredMediumQuality(TEXTURE2D_SHADOW_ARGS(ShadowMap, sampler_ShadowMap), shadowCoord, samplingData, positionSS); } else if (_SHADOWS_SOFT_HIGH) { - attenuation = SampleShadowmapFilteredHighQuality(TEXTURE2D_SHADOW_ARGS(ShadowMap, sampler_ShadowMap), shadowCoord, samplingData); + attenuation = SampleShadowmapFilteredHighQuality(TEXTURE2D_SHADOW_ARGS(ShadowMap, sampler_ShadowMap), shadowCoord, samplingData, positionSS); } else if (_SHADOWS_SOFT) { if (shadowParams.y > (half)SOFT_SHADOW_QUALITY_OFF) { - attenuation = SampleShadowmapFiltered(TEXTURE2D_SHADOW_ARGS(ShadowMap, sampler_ShadowMap), shadowCoord, samplingData); + attenuation = SampleShadowmapFiltered(TEXTURE2D_SHADOW_ARGS(ShadowMap, sampler_ShadowMap), shadowCoord, samplingData, positionSS); } else { @@ -643,13 +859,19 @@ float4 TransformWorldToShadowCoord(float3 positionWS, bool isSurfaceTypeTranspar half cascadeIndex = 0; if (_MAIN_LIGHT_SHADOWS_CASCADE) cascadeIndex = ComputeCascadeIndexAndWeights(positionWS, cascadeWeights); - positionWS += normalWS * GetMainLightShadowReceiverNormalBias(cascadeWeights); + if (_SHADOW_RECEIVER_NORMAL_BIAS) + positionWS += normalWS * GetMainLightShadowReceiverNormalBias(cascadeWeights); shadowCoord = float4(mul(_MainLightWorldToShadow[cascadeIndex], float4(positionWS, 1.0)).xyz, 1.0); } return shadowCoord; } +float4 TransformWorldToShadowCoord(float3 positionWS, bool isSurfaceTypeTransparent) +{ + return TransformWorldToShadowCoord(positionWS, isSurfaceTypeTransparent, float3(0.0, 0.0, 0.0)); +} + half SampleShadowmapPCSSDirectional(float4 shadowCoord, half cascadeIndex, float2 positionSS, half4 shadowParams) { int ci = (int)cascadeIndex; @@ -695,10 +917,10 @@ half SampleMainLightRealtimeShadow(float4 shadowCoord, half4 shadowParams, Shado else { UNITY_BRANCH - if (MainLightPCSSAvailable() && usePCSS) + if (ShadowsPCSSAvailable() && usePCSS && shadowParams.y == SOFT_SHADOW_QUALITY_PCSS) result = SampleShadowmapPCSSDirectional(shadowCoord, cascadeIndex, positionSS, shadowParams); else - result = SampleShadowmap(TEXTURE2D_ARGS(_MainLightShadowmapTexture, sampler_LinearClampCompare), shadowCoord, shadowSamplingData, shadowParams, false); + result = SampleShadowmap(TEXTURE2D_ARGS(_MainLightShadowmapTexture, sampler_LinearClampCompare), shadowCoord, shadowSamplingData, shadowParams, false, positionSS); } } @@ -715,13 +937,20 @@ half SampleMainLightRealtimeShadow(float4 shadowCoord, bool isSurfaceTypeTranspa return SampleMainLightRealtimeShadow(shadowCoord, GetMainLightShadowParams(), GetMainLightShadowSamplingData(), isSurfaceTypeTransparent); } +// positionSS seeds the PCSS sample rotation +half SampleMainLightRealtimeShadow(float4 shadowCoord, float3 positionWS, bool isSurfaceTypeTransparent, float2 positionSS) +{ + return SampleMainLightRealtimeShadow(shadowCoord, GetMainLightShadowParams(), GetMainLightShadowSamplingData(), isSurfaceTypeTransparent, GetMainLightCascadeIndex(positionWS), positionSS, true); +} + half SampleShadowmapPCSSPunctual(int lightIndex, int shadowSliceIndex, float4 shadowCoord, float2 positionSS, half4 shadowParams) { +#if !defined(SHADER_API_GLES3) && !defined(URP_SHADER_API_GLCORE) // Spot and point shadows use a perspective projection. shadowCoord.xyz /= shadowCoord.w; - float4 pcssParams = _AdditionalLightsPCSSParams[lightIndex]; - float4 atlas = _AdditionalLightsPCSSAtlas[shadowSliceIndex]; + float4 pcssParams = _AdditionalLightsPCSSData[lightIndex]; + float4 atlas = _AdditionalLightsPCSSData[2 * MAX_VISIBLE_LIGHTS + shadowSliceIndex]; // A slice with no rectangle was never rendered, for example a culled face of a point light. if (atlas.z <= 0.0) @@ -732,13 +961,16 @@ half SampleShadowmapPCSSPunctual(int lightIndex, int shadowSliceIndex, float4 sh atlas.zw, atlas.xy, pcssParams.x, pcssParams.y, (int)pcssParams.z, (int)pcssParams.w, - _AdditionalLightsPCSSZParams[lightIndex], _AdditionalLightsPCSSScalars.xy, - (uint)_AdditionalLightsPCSSScalars.z, 0.0, + _AdditionalLightsPCSSData[MAX_VISIBLE_LIGHTS + lightIndex], _AdditionalShadowmapSize.zw, + (uint)_AdditionalShadowFadeParams.z, 0.0, _AdditionalLightsShadowmapTexture, sampler_LinearClampCompare, sampler_PointClamp); attenuation = LerpWhiteTo(attenuation, shadowParams.x); return BEYOND_SHADOW_FAR(shadowCoord) ? half(1.0) : attenuation; +#else + return half(1.0); +#endif } // returns 0.0 if position is in light's shadow @@ -766,15 +998,16 @@ half SampleAdditionalLightRealtimeShadow(int lightIndex, float3 positionWS, half #endif // Read behind the slice-index guard above, so the bias data may stay stale while the shadowmap is empty - positionWS += normalWS * GetAdditionalLightShadowReceiverNormalBias(lightIndex); + if (_SHADOW_RECEIVER_NORMAL_BIAS) + positionWS += normalWS * GetAdditionalLightShadowReceiverNormalBias(lightIndex); float4 shadowCoord = mul(_AdditionalLightsWorldToShadow[shadowSliceIndex], float4(positionWS, 1.0)); UNITY_BRANCH - if (AdditionalLightPCSSAvailable() && usePCSS && shadowParams.y >= SOFT_SHADOW_QUALITY_HIGH) + if (ShadowsPCSSAvailable() && usePCSS && shadowParams.y == SOFT_SHADOW_QUALITY_PCSS) result = SampleShadowmapPCSSPunctual(lightIndex, shadowSliceIndex, shadowCoord, positionSS, shadowParams); else - result = SampleShadowmap(TEXTURE2D_ARGS(_AdditionalLightsShadowmapTexture, sampler_LinearClampCompare), shadowCoord, shadowSamplingData, shadowParams, true); + result = SampleShadowmap(TEXTURE2D_ARGS(_AdditionalLightsShadowmapTexture, sampler_LinearClampCompare), shadowCoord, shadowSamplingData, shadowParams, true, positionSS); } } @@ -786,6 +1019,11 @@ half SampleAdditionalLightRealtimeShadow(int lightIndex, float3 positionWS, half return SampleAdditionalLightRealtimeShadow(lightIndex, positionWS, lightDirection, shadowParams, shadowSamplingData, normalWS, INVALID_SHADOW_SCREEN_POS, false); } +half SampleAdditionalLightRealtimeShadow(int lightIndex, float3 positionWS, half3 lightDirection, half4 shadowParams, ShadowSamplingData shadowSamplingData) +{ + return SampleAdditionalLightRealtimeShadow(lightIndex, positionWS, lightDirection, shadowParams, shadowSamplingData, float3(0.0, 0.0, 0.0)); +} + half SampleAdditionalLightRealtimeShadow(int lightIndex, float3 positionWS, half3 lightDirection, float3 normalWS) { half result = half(1.0); @@ -794,19 +1032,14 @@ half SampleAdditionalLightRealtimeShadow(int lightIndex, float3 positionWS, half return result; } -float3 GetShadowFadeCameraPositionWS() +half SampleAdditionalLightRealtimeShadow(int lightIndex, float3 positionWS, half3 lightDirection) { -#if defined(USING_STEREO_MATRICES) - // Using unity_StereoWorldSpaceCameraPos[unity_StereoEyeIndex] directly trips a bug in FXC (X8000 or a stale index). - return unity_StereoEyeIndex == 0 ? unity_StereoWorldSpaceCameraPos[0] : unity_StereoWorldSpaceCameraPos[1]; -#else - return _WorldSpaceCameraPos; -#endif + return SampleAdditionalLightRealtimeShadow(lightIndex, positionWS, lightDirection, float3(0.0, 0.0, 0.0)); } half GetMainLightShadowFade(float3 positionWS) { - float3 camToPixel = positionWS - GetShadowFadeCameraPositionWS(); + float3 camToPixel = positionWS - _WorldSpaceCameraPos; float distanceCamToPixel2 = dot(camToPixel, camToPixel); float fade = saturate(distanceCamToPixel2 * float(_MainLightShadowParams.z) + float(_MainLightShadowParams.w)); @@ -818,7 +1051,7 @@ half GetAdditionalLightShadowFade(float3 positionWS) half shadowFade = half(1.0); if (AdditionalLightShadowsAvailable()) { - float3 camToPixel = positionWS - GetShadowFadeCameraPositionWS(); + float3 camToPixel = positionWS - _WorldSpaceCameraPos; float distanceCamToPixel2 = dot(camToPixel, camToPixel); float fade = saturate(distanceCamToPixel2 * float(_AdditionalShadowFadeParams.x) + float(_AdditionalShadowFadeParams.y)); @@ -913,6 +1146,16 @@ half AdditionalLightShadow(int lightIndex, float3 positionWS, half3 lightDirecti return AdditionalLightShadow(lightIndex, positionWS, lightDirection, shadowMask, occlusionProbeChannels, receiveShadows, normalWS, INVALID_SHADOW_SCREEN_POS, false); } +half AdditionalLightShadow(int lightIndex, float3 positionWS, half3 lightDirection, half4 shadowMask, half4 occlusionProbeChannels, bool receiveShadows, float3 normalWS, float2 positionSS) +{ + return AdditionalLightShadow(lightIndex, positionWS, lightDirection, shadowMask, occlusionProbeChannels, receiveShadows, normalWS, positionSS, true); +} + +half AdditionalLightShadow(int lightIndex, float3 positionWS, half3 lightDirection, half4 shadowMask, half4 occlusionProbeChannels, bool receiveShadows) +{ + return AdditionalLightShadow(lightIndex, positionWS, lightDirection, shadowMask, occlusionProbeChannels, receiveShadows, float3(0.0, 0.0, 0.0)); +} + float4 GetShadowCoord(VertexPositionInputs vertexInput, bool isSurfaceTypeTransparent, float3 normalWS) { float4 result = (float4)0; @@ -929,6 +1172,11 @@ float4 GetShadowCoord(VertexPositionInputs vertexInput, bool isSurfaceTypeTransp return result; } +float4 GetShadowCoord(VertexPositionInputs vertexInput, bool isSurfaceTypeTransparent) +{ + return GetShadowCoord(vertexInput, isSurfaceTypeTransparent, float3(0.0, 0.0, 0.0)); +} + float3 ApplyShadowBias(float3 positionWS, float3 normalWS, float3 lightDirection) { float invNdotL = 1.0 - saturate(dot(lightDirection, normalWS)); @@ -953,7 +1201,12 @@ float4 ApplyShadowClamping(float4 positionCS) // (see: Shadows.cpp::RenderShadowMaps() #L2161-L2162) // (see: Shadows.cpp::RenderShadowMaps() #L2086-L2102) // (see: Shadows.cpp::PrepareStateForShadowMap() #L1685-L1686) +#if defined(_SHADOW_CASTER_ZCLIP) + // Defined only by passes that also set ZClip [_ZClip]: pancaking is needed only while the rasterizer clips. + positionCS.z = lerp(positionCS.z, clamped, IsDirectionalLight() * _ZClip); +#else positionCS.z = lerp(positionCS.z, clamped, IsDirectionalLight()); +#endif return positionCS; } @@ -968,7 +1221,7 @@ float4 ApplyShadowClamping(float4 positionCS) // Deprecated: Use GetMainLightShadowFade or GetAdditionalLightShadowFade instead. float GetShadowFade(float3 positionWS) { - float3 camToPixel = positionWS - GetShadowFadeCameraPositionWS(); + float3 camToPixel = positionWS - _WorldSpaceCameraPos; float distanceCamToPixel2 = dot(camToPixel, camToPixel); float fade = saturate(distanceCamToPixel2 * float(_MainLightShadowParams.z) + float(_MainLightShadowParams.w)); diff --git a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/SixWayLighting.hlsl b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/SixWayLighting.hlsl index 98eeb5b8f94..f52e092bcf0 100644 --- a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/SixWayLighting.hlsl +++ b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/SixWayLighting.hlsl @@ -100,7 +100,7 @@ half3 ComputeGIColor(SixWaySurfaceData surfaceData) return giColor; } -half3 SixWayLightBlend(SixWaySurfaceData surfaceData, Light light, half3x3 tangentToWorld) +URP_LIGHT_ACCUM3 SixWayLightBlend(SixWaySurfaceData surfaceData, Light light, half3x3 tangentToWorld) { half3x3 localFrame = tangentToWorld; localFrame[2] *= -1; @@ -116,11 +116,11 @@ half3 SixWayLightBlend(SixWaySurfaceData surfaceData, Light light, half3x3 tang #endif half3 cbsdf_R = GetTransmissionWithAbsorption(transmission, half4(surfaceData.baseColor, surfaceData.alpha), surfaceData.absorptionRange, alphaPremultipled); - half3 radiance = light.color * light.distanceAttenuation * light.shadowAttenuation; + URP_LIGHT_ACCUM3 radiance = light.color * light.distanceAttenuation * light.shadowAttenuation; return PI * cbsdf_R * radiance; // *PI because URP doesn't multiply by the Lambert term in its Lit implementation } -URP_LIGHT_ACCUM4 UniversalFragmentSixWay(InputData inputData, SixWaySurfaceData surfaceData, float3 geometricNormalWS = float3(0.0, 0.0, 0.0)) +URP_LIGHT_ACCUM4 UniversalFragmentSixWay(InputData inputData, SixWaySurfaceData surfaceData) { if(surfaceData.alpha == 0) return half4(0,0,0,0); @@ -146,7 +146,7 @@ URP_LIGHT_ACCUM4 UniversalFragmentSixWay(InputData inputData, SixWaySurfaceData { CLUSTER_LIGHT_LOOP_SUBTRACTIVE_LIGHT_CHECK - Light light = GetAdditionalLight(lightIndex, inputData, shadowMask, aoFactor, geometricNormalWS); + Light light = GetAdditionalLight(lightIndex, inputData, shadowMask, aoFactor); if (IsMatchingLightLayer(light, meshRenderingLayers)) { @@ -156,7 +156,7 @@ URP_LIGHT_ACCUM4 UniversalFragmentSixWay(InputData inputData, SixWaySurfaceData #endif LIGHT_LOOP_BEGIN(pixelLightCount) - Light light = GetAdditionalLight(lightIndex, inputData, shadowMask, aoFactor, geometricNormalWS); + Light light = GetAdditionalLight(lightIndex, inputData, shadowMask, aoFactor); if (IsMatchingLightLayer(light, meshRenderingLayers)) { diff --git a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/UnityInput.hlsl b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/UnityInput.hlsl index 3eb272431fc..ed3d8396ca1 100644 --- a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/UnityInput.hlsl +++ b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/UnityInput.hlsl @@ -34,7 +34,12 @@ #define unity_CameraInvProjection unity_StereoCameraInvProjection[unity_StereoEyeIndex] #define unity_WorldToCamera unity_StereoMatrixV[unity_StereoEyeIndex] // Should be unity_StereoWorldToCamera but no use-case in XR pass #define unity_CameraToWorld unity_StereoMatrixInvV[unity_StereoEyeIndex] // Should be unity_StereoCameraToWorld but no use-case in XR pass +#if defined(UNITY_COMPILER_DXC) #define _WorldSpaceCameraPos unity_StereoWorldSpaceCameraPos[unity_StereoEyeIndex] +#else +// FXC can index this with a stale or uninitialized eye index when the read ends up inside a branch; blend instead of indexing. +#define _WorldSpaceCameraPos (unity_StereoWorldSpaceCameraPos[0] * (1.0 - (float)unity_StereoEyeIndex) + unity_StereoWorldSpaceCameraPos[1] * (float)unity_StereoEyeIndex) +#endif #endif #define UNITY_LIGHTMODEL_AMBIENT (glstate_lightmodel_ambient * 2) @@ -102,12 +107,10 @@ float4 unity_SpecCube0_BoxMax; // w contains the blend distance float4 unity_SpecCube0_BoxMin; // w contains the lerp value float4 unity_SpecCube0_ProbePosition; // w is set to 1 for box projection float4 unity_SpecCube0_Rotation; -float4 unity_SpecCube0_Exposure; // Only the x value is used float4 unity_SpecCube1_BoxMax; // w contains the blend distance float4 unity_SpecCube1_BoxMin; // w contains the sign of (SpecCube0.importance - SpecCube1.importance) float4 unity_SpecCube1_ProbePosition; // w is set to 1 for box projection float4 unity_SpecCube1_Rotation; -float4 unity_SpecCube1_Exposure; // Only the x value is used // Lightmap block feature float4 unity_LightmapST; @@ -163,6 +166,11 @@ uint unity_LightProbeUsagePropertyEntry; // static-const fallback at parse time and miss the per-instance override. #define IsLightProbeSamplingEnabled() (unity_LightProbeUsage != 0u) +// The probe capture exposure (EV) is carried in unity_SpecCubeN_HDR.z. These keep the exposure multiplier (2^EV in x) +// available to custom shaders under its previous name, without extra per-draw data. +#define unity_SpecCube0_Exposure float4(exp2((float)unity_SpecCube0_HDR.z), 0.0, 0.0, 0.0) +#define unity_SpecCube1_Exposure float4(exp2((float)unity_SpecCube1_HDR.z), 0.0, 0.0, 0.0) + #if defined(USING_STEREO_MATRICES) CBUFFER_START(UnityStereoViewBuffer) float4x4 unity_StereoMatrixP[2]; @@ -180,10 +188,14 @@ CBUFFER_END #endif #if defined(UNITY_STEREO_MULTIVIEW_ENABLED) && defined(SHADER_STAGE_VERTEX) +#if !defined(UNITY_DECLARE_MULTIVIEW) +#if defined(SHADER_API_VULKAN) && defined(UNITY_COMPILER_DXC) +#define UNITY_DECLARE_MULTIVIEW(number_of_views) UNITY_DECLARE_SPIRV_VIEW_INDEX(gl_ViewID) +#else // OVR_multiview // In order to convey this info over the DX compiler, we wrap it into a cbuffer. -#if !defined(UNITY_DECLARE_MULTIVIEW) #define UNITY_DECLARE_MULTIVIEW(number_of_views) CBUFFER_START(OVR_multiview) uint gl_ViewID; uint numViews_##number_of_views; CBUFFER_END +#endif #define UNITY_VIEWID gl_ViewID #endif #endif diff --git a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/UniversalDOTSInstancing.hlsl b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/UniversalDOTSInstancing.hlsl index b859a07599e..29184a8797d 100644 --- a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/UniversalDOTSInstancing.hlsl +++ b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/UniversalDOTSInstancing.hlsl @@ -55,12 +55,10 @@ static const float4 unity_SpecCube0_BoxMax = float4(1,1,1,1); static const float4 unity_SpecCube0_BoxMin = float4(0,0,0,0); static const float4 unity_SpecCube0_ProbePosition = float4(0,0,0,0); static const float4 unity_SpecCube0_Rotation = float4(0,0,0,0); -static const float4 unity_SpecCube0_Exposure = float4(1,0,0,0); static const float4 unity_SpecCube1_BoxMax = float4(1,1,1,1); static const float4 unity_SpecCube1_BoxMin = float4(0,0,0,0); static const float4 unity_SpecCube1_ProbePosition = float4(0,0,0,0); static const float4 unity_SpecCube1_Rotation = float4(0,0,0,0); -static const float4 unity_SpecCube1_Exposure = float4(1,0,0,0); static const float4 unity_SpecCube1_HDR = float4(0,0,0,0); // Set up by BRG picking/selection code diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/2D/Include/Core2D.hlsl b/Packages/com.unity.render-pipelines.universal/Shaders/2D/Include/Core2D.hlsl index b1d4271857e..16b14cf12ec 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/2D/Include/Core2D.hlsl +++ b/Packages/com.unity.render-pipelines.universal/Shaders/2D/Include/Core2D.hlsl @@ -141,23 +141,20 @@ float3 UnitySkinSprite(in float3 inputData, in uint4 blendIndices, in float4 ble #ifdef UNITY_INSTANCING_ENABLED UNITY_INSTANCING_BUFFER_START(PerDrawSprite) // Refer unity_SpriteProps in UnityInput.hlsl - UNITY_DEFINE_INSTANCED_PROP(float4, unity_SpritePropArray) + UNITY_DEFINE_INSTANCED_PROP(float4, unity_SpritePropsArray) // SpriteRenderer.Color while Non-Batched/Instanced. - UNITY_DEFINE_INSTANCED_PROP(float4, unity_SpriteRendererColorArray) + UNITY_DEFINE_INSTANCED_PROP(float4, unity_SpriteColorArray) // To support RSUV in Instanced code-path UNITY_DEFINE_INSTANCED_PROP(float, unity_RendererUserValueArray) UNITY_INSTANCING_BUFFER_END(PerDrawSprite) - #define unity_SpriteProp UNITY_ACCESS_INSTANCED_PROP(PerDrawSprite, unity_SpritePropArray) - #define unity_SpriteColor UNITY_ACCESS_INSTANCED_PROP(PerDrawSprite, unity_SpriteRendererColorArray) + #define unity_SpriteProps UNITY_ACCESS_INSTANCED_PROP(PerDrawSprite, unity_SpritePropsArray) + #define unity_SpriteColor UNITY_ACCESS_INSTANCED_PROP(PerDrawSprite, unity_SpriteColorArray) #define unity_RendererUserValue asuint(UNITY_ACCESS_INSTANCED_PROP(PerDrawSprite, unity_RendererUserValueArray).x) #endif // instancing void SetUpSpriteInstanceProperties() { -#if defined(UNITY_INSTANCING_ENABLED) && !defined(HAVE_VFX_MODIFICATION) - unity_SpriteProps = unity_SpriteProp; -#endif } #endif diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/2D/RenderAs2D-Flattening.shader b/Packages/com.unity.render-pipelines.universal/Shaders/2D/RenderAs2D-Flattening.shader index dfbdfce6907..ce43e6cf024 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/2D/RenderAs2D-Flattening.shader +++ b/Packages/com.unity.render-pipelines.universal/Shaders/2D/RenderAs2D-Flattening.shader @@ -4,10 +4,6 @@ Shader "2D/RenderAs2D-Flattening" { // Legacy properties. They're here so that materials using this shader can gracefully fallback to the legacy sprite shader. [HideInInspector] _Color("Tint", Color) = (1,1,1,1) - [HideInInspector] _RendererColor("RendererColor", Color) = (1,1,1,1) - [HideInInspector] _Flip("Flip", Vector) = (1,1,1,1) - [HideInInspector] _AlphaTex("External Alpha", 2D) = "white" {} - [HideInInspector] _EnableExternalAlpha("Enable External Alpha", Float) = 0 } SubShader diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/2D/RenderingLayerMask.shader b/Packages/com.unity.render-pipelines.universal/Shaders/2D/RenderingLayerMask.shader index f26b1e5a005..ea5e666ab86 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/2D/RenderingLayerMask.shader +++ b/Packages/com.unity.render-pipelines.universal/Shaders/2D/RenderingLayerMask.shader @@ -54,8 +54,8 @@ Shader "Hidden/2D/RenderingLayerMask" { UNITY_SETUP_INSTANCE_ID(input); SetUpSpriteInstanceProperties(); - input.positionOS = UnityFlipSprite(input.positionOS, unity_SpriteProps.xy); UNITY_SKINNED_VERTEX_COMPUTE(input); + input.positionOS = UnityFlipSprite(input.positionOS, unity_SpriteProps.xy); Varyings o = CommonUnlitVertex(input); o.color = input.color * _Color * unity_SpriteColor; diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/2D/Sprite-Lit-Default.shader b/Packages/com.unity.render-pipelines.universal/Shaders/2D/Sprite-Lit-Default.shader index bc3ddc12f87..3c1198cc270 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/2D/Sprite-Lit-Default.shader +++ b/Packages/com.unity.render-pipelines.universal/Shaders/2D/Sprite-Lit-Default.shader @@ -9,9 +9,6 @@ Shader "Universal Render Pipeline/2D/Sprite-Lit-Default" // Legacy properties. They're here so that materials using this shader can gracefully fallback to the legacy sprite shader. [HideInInspector] _Color("Tint", Color) = (1,1,1,1) - [HideInInspector] _RendererColor("RendererColor", Color) = (1,1,1,1) - [HideInInspector] _AlphaTex("External Alpha", 2D) = "white" {} - [HideInInspector] _EnableExternalAlpha("Enable External Alpha", Float) = 0 } SubShader @@ -63,8 +60,8 @@ Shader "Universal Render Pipeline/2D/Sprite-Lit-Default" { UNITY_SETUP_INSTANCE_ID(input); SetUpSpriteInstanceProperties(); - input.positionOS = UnityFlipSprite(input.positionOS, unity_SpriteProps.xy); UNITY_SKINNED_VERTEX_COMPUTE(input); + input.positionOS = UnityFlipSprite(input.positionOS, unity_SpriteProps.xy); Varyings o = CommonLitVertex(input); o.color = input.color * _Color * unity_SpriteColor; @@ -117,8 +114,8 @@ Shader "Universal Render Pipeline/2D/Sprite-Lit-Default" { UNITY_SETUP_INSTANCE_ID(input); SetUpSpriteInstanceProperties(); - input.positionOS = UnityFlipSprite(input.positionOS, unity_SpriteProps.xy); UNITY_SKINNED_VERTEX_COMPUTE(input); + input.positionOS = UnityFlipSprite(input.positionOS, unity_SpriteProps.xy); Varyings o = CommonNormalsVertex(input); o.color = input.color * _Color * unity_SpriteColor; @@ -174,8 +171,8 @@ Shader "Universal Render Pipeline/2D/Sprite-Lit-Default" { UNITY_SETUP_INSTANCE_ID(input); SetUpSpriteInstanceProperties(); - input.positionOS = UnityFlipSprite(input.positionOS, unity_SpriteProps.xy); UNITY_SKINNED_VERTEX_COMPUTE(input); + input.positionOS = UnityFlipSprite(input.positionOS, unity_SpriteProps.xy); Varyings o = CommonUnlitVertex(input); o.color = input.color *_Color * unity_SpriteColor; diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/2D/Sprite-Unlit-Default.shader b/Packages/com.unity.render-pipelines.universal/Shaders/2D/Sprite-Unlit-Default.shader index 9a7ad366cd5..260d8b6fbfe 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/2D/Sprite-Unlit-Default.shader +++ b/Packages/com.unity.render-pipelines.universal/Shaders/2D/Sprite-Unlit-Default.shader @@ -7,10 +7,6 @@ Shader "Universal Render Pipeline/2D/Sprite-Unlit-Default" // Legacy properties. They're here so that materials using this shader can gracefully fallback to the legacy sprite shader. [HideInInspector] _Color ("Tint", Color) = (1,1,1,1) - [HideInInspector] PixelSnap ("Pixel snap", Float) = 0 - [HideInInspector] _RendererColor ("RendererColor", Color) = (1,1,1,1) - [HideInInspector] _AlphaTex ("External Alpha", 2D) = "white" {} - [HideInInspector] _EnableExternalAlpha ("Enable External Alpha", Float) = 0 } SubShader @@ -57,11 +53,11 @@ Shader "Universal Render Pipeline/2D/Sprite-Unlit-Default" { UNITY_SETUP_INSTANCE_ID(input); SetUpSpriteInstanceProperties(); - input.positionOS = UnityFlipSprite(input.positionOS, unity_SpriteProps.xy); UNITY_SKINNED_VERTEX_COMPUTE(input); + input.positionOS = UnityFlipSprite(input.positionOS, unity_SpriteProps.xy); Varyings o = CommonUnlitVertex(input); - o.color = input.color *_Color * unity_SpriteColor; + o.color = input.color * _Color * unity_SpriteColor; return o; } diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/ComplexLit.shader b/Packages/com.unity.render-pipelines.universal/Shaders/ComplexLit.shader index 9442c157409..ec8632171a7 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/ComplexLit.shader +++ b/Packages/com.unity.render-pipelines.universal/Shaders/ComplexLit.shader @@ -38,6 +38,12 @@ Shader "Universal Render Pipeline/Complex Lit" [HDR] _EmissionColor("Color", Color) = (0,0,0) _EmissionMap("Emission", 2D) = "white" {} + [ToggleUI] _UseEmissionIntensity("Use Emission Intensity", Float) = 0.0 + // Used only to serialize the LDR and HDR emissive color in the material UI, + // in the shader only the _EmissionColor should be used + [HideInInspector] _EmissionColorLDR("Color LDR", Color) = (1,1,1,1) + _EmissionIntensity("Emission Intensity", Float) = 1.0 + _EmissionIntensityUnit("EmissionIntensity Unit", Int) = 0 // 0=Nits, 1=EV100 _DetailMask("Detail Mask", 2D) = "white" {} _DetailAlbedoMapScale("Scale", Range(0.0, 2.0)) = 1.0 @@ -143,6 +149,7 @@ Shader "Universal Render Pipeline/Complex Lit" #pragma multi_compile _ META_QUEST_LIGHTUNROLL #endif #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS #pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX #pragma multi_compile_fragment _ _ADDITIONAL_LIGHTS #pragma multi_compile _ _LIGHT_FALLOFF_QUADRATIC @@ -159,6 +166,7 @@ Shader "Universal Render Pipeline/Complex Lit" #pragma multi_compile_fragment _ _REFLECTION_PROBE_ATLAS #pragma multi_compile_fragment _ _SCREEN_SPACE_REFLECTION #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH + #pragma multi_compile_fragment _ _SHADOWS_PCSS #pragma multi_compile_fragment _ _SCREEN_SPACE_OCCLUSION #pragma multi_compile_fragment _ _SCREEN_SPACE_IRRADIANCE #pragma multi_compile_fragment _ _DBUFFER_MRT1 _DBUFFER_MRT2 _DBUFFER_MRT3 @@ -213,8 +221,10 @@ Shader "Universal Render Pipeline/Complex Lit" ZTest LEqual ColorMask 0 Cull[_Cull] + ZClip [_ZClip] HLSLPROGRAM + #define _SHADOW_CASTER_ZCLIP 1 #pragma target 2.0 // ------------------------------------- @@ -298,6 +308,7 @@ Shader "Universal Render Pipeline/Complex Lit" // ------------------------------------- // Universal Pipeline keywords #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS //#pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX _ADDITIONAL_LIGHTS //#pragma multi_compile _ _ADDITIONAL_LIGHT_SHADOWS #pragma multi_compile_fragment _ _REFLECTION_PROBE_BLENDING diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Lit.shader b/Packages/com.unity.render-pipelines.universal/Shaders/Lit.shader index b22ecdb190f..bc1d0379bf4 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/Lit.shader +++ b/Packages/com.unity.render-pipelines.universal/Shaders/Lit.shader @@ -35,6 +35,12 @@ Shader "Universal Render Pipeline/Lit" [HDR] _EmissionColor("Color", Color) = (0,0,0) _EmissionMap("Emission", 2D) = "white" {} + [ToggleUI] _UseEmissionIntensity("Use Emission Intensity", Float) = 0.0 + // Used only to serialize the LDR and HDR emissive color in the material UI, + // in the shader only the _EmissionColor should be used + [HideInInspector] _EmissionColorLDR("Color LDR", Color) = (1,1,1,1) + _EmissionIntensity("Emission Intensity", Float) = 1.0 + _EmissionIntensityUnit("EmissionIntensity Unit", Int) = 0 // 0=Nits, 1=EV100 _DetailMask("Detail Mask", 2D) = "white" {} _DetailAlbedoMapScale("Scale", Range(0.0, 2.0)) = 1.0 @@ -143,6 +149,7 @@ Shader "Universal Render Pipeline/Lit" #pragma multi_compile _ META_QUEST_LIGHTUNROLL #endif #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS #pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX #pragma multi_compile_fragment _ _ADDITIONAL_LIGHTS #pragma multi_compile _ _LIGHT_FALLOFF_QUADRATIC @@ -153,6 +160,7 @@ Shader "Universal Render Pipeline/Lit" #pragma multi_compile_fragment _ _REFLECTION_PROBE_ATLAS #pragma multi_compile_fragment _ _SCREEN_SPACE_REFLECTION #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH + #pragma multi_compile_fragment _ _SHADOWS_PCSS #pragma multi_compile_fragment _ _SCREEN_SPACE_OCCLUSION #pragma multi_compile_fragment _ _SCREEN_SPACE_IRRADIANCE #pragma multi_compile_fragment _ _DBUFFER_MRT1 _DBUFFER_MRT2 _DBUFFER_MRT3 @@ -211,8 +219,10 @@ Shader "Universal Render Pipeline/Lit" ZTest LEqual ColorMask 0 Cull[_Cull] + ZClip [_ZClip] HLSLPROGRAM + #define _SHADOW_CASTER_ZCLIP 1 #pragma target 2.0 // ------------------------------------- @@ -296,6 +306,7 @@ Shader "Universal Render Pipeline/Lit" // ------------------------------------- // Universal Pipeline keywords #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS //#pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX _ADDITIONAL_LIGHTS //#pragma multi_compile _ _ADDITIONAL_LIGHT_SHADOWS #pragma multi_compile_fragment _ _REFLECTION_PROBE_BLENDING diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/LitForwardPass.hlsl b/Packages/com.unity.render-pipelines.universal/Shaders/LitForwardPass.hlsl index 35e3423a13b..3235aceb53f 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/LitForwardPass.hlsl +++ b/Packages/com.unity.render-pipelines.universal/Shaders/LitForwardPass.hlsl @@ -112,6 +112,7 @@ void InitializeInputData(Varyings input, half3 normalTS, out InputData inputData #endif inputData.normalWS = NormalizeNormalPerPixel(inputData.normalWS, UseNormalMap()); + inputData.geometricNormalWS = input.normalWS.xyz; inputData.viewDirectionWS = viewDirWS; #if USE_VERTEX_SHADOW_COORD_INTERPOLATOR @@ -291,7 +292,7 @@ void LitPassFragment( URP_LIGHT_ACCUM4 color = UniversalFragmentPBR(inputData, surfaceData, IsSpecularSetup(), UseSpecularHighlights(), UseAlphaPremultiply(), - UseClearCoat() || UseClearCoatMap(), ReceiveShadows(), IsSurfaceTypeTransparent(), UseEnvironmentReflections(), input.normalWS.xyz); + UseClearCoat() || UseClearCoatMap(), ReceiveShadows(), IsSurfaceTypeTransparent(), UseEnvironmentReflections()); color.rgb = ClampExposed(inputData.preExposureMultiplier * BlendDistanceFog(color.rgb, input.positionCS)); #if defined(_TRANSPARENT_RECEIVE_FOG) if (IsSurfaceTypeTransparent()) diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree7.shader b/Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree7.shader index 890c555be35..0bea627f26b 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree7.shader +++ b/Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree7.shader @@ -39,11 +39,13 @@ Shader "Universal Render Pipeline/Nature/SpeedTree7" #pragma fragment SpeedTree7Frag #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS #pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX #pragma multi_compile_fragment _ _ADDITIONAL_LIGHTS #pragma multi_compile _ _LIGHT_FALLOFF_QUADRATIC #pragma multi_compile _ _ADDITIONAL_LIGHT_SHADOWS #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH + #pragma multi_compile_fragment _ _SHADOWS_PCSS #pragma multi_compile _ LOD_FADE_CROSSFADE #pragma multi_compile_fragment _ _SCREEN_SPACE_OCCLUSION #pragma multi_compile_fragment _ DEBUG_DISPLAY @@ -107,6 +109,7 @@ Shader "Universal Render Pipeline/Nature/SpeedTree7" Tags{"LightMode" = "ShadowCaster"} ColorMask 0 + ZClip [_ZClip] HLSLPROGRAM @@ -151,6 +154,7 @@ Shader "Universal Render Pipeline/Nature/SpeedTree7" #pragma fragment SpeedTree7Frag #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS //#pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX _ADDITIONAL_LIGHTS //#pragma multi_compile _ _ADDITIONAL_LIGHT_SHADOWS #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree7Billboard.shader b/Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree7Billboard.shader index 8f54b62a2dd..942d5052e94 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree7Billboard.shader +++ b/Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree7Billboard.shader @@ -34,11 +34,13 @@ Shader "Universal Render Pipeline/Nature/SpeedTree7 Billboard" #pragma fragment SpeedTree7Frag #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS #pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX #pragma multi_compile_fragment _ _ADDITIONAL_LIGHTS #pragma multi_compile _ _LIGHT_FALLOFF_QUADRATIC #pragma multi_compile _ _ADDITIONAL_LIGHT_SHADOWS #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH + #pragma multi_compile_fragment _ _SHADOWS_PCSS #pragma multi_compile_fragment _ _CLUSTER_LIGHT_LOOP #include_with_pragmas "Packages/com.unity.render-pipelines.core/ShaderLibrary/FoveatedRenderingKeywords.hlsl" #include_with_pragmas "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Fog.hlsl" @@ -70,6 +72,7 @@ Shader "Universal Render Pipeline/Nature/SpeedTree7 Billboard" Tags{"LightMode" = "ShadowCaster"} ColorMask 0 + ZClip [_ZClip] HLSLPROGRAM @@ -105,6 +108,7 @@ Shader "Universal Render Pipeline/Nature/SpeedTree7 Billboard" #pragma fragment SpeedTree7Frag #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS //#pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX _ADDITIONAL_LIGHTS //#pragma multi_compile _ _ADDITIONAL_LIGHT_SHADOWS #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH @@ -113,6 +117,7 @@ Shader "Universal Render Pipeline/Nature/SpeedTree7 Billboard" #pragma multi_compile _ _EXPOSURE #pragma multi_compile_fragment _ _GBUFFER_NORMALS_OCT #pragma multi_compile_fragment _ _RENDER_PASS_ENABLED + #include_with_pragmas "Packages/com.unity.render-pipelines.universal/ShaderLibrary/RenderingLayers.hlsl" #pragma shader_feature_local EFFECT_BUMP #pragma shader_feature_local EFFECT_HUE_VARIATION diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree7CommonPasses.hlsl b/Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree7CommonPasses.hlsl index 3adafc118c8..d6df139d481 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree7CommonPasses.hlsl +++ b/Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree7CommonPasses.hlsl @@ -117,6 +117,7 @@ void InitializeInputData(SpeedTreeVertexOutput input, half3 normalTS, out InputD inputData.viewDirectionWS = input.viewDirWS; #endif inputData.normalWS = NormalizeNormalPerPixel(inputData.normalWS, UseNormalMap()); + inputData.geometricNormalWS = input.normalWS.xyz; inputData.viewDirectionWS = SafeNormalize(inputData.viewDirectionWS); #if USE_VERTEX_SHADOW_COORD_INTERPOLATOR @@ -229,7 +230,7 @@ half4 SpeedTree7Frag(SpeedTreeVertexOutput input) : SV_Target #else URP_LIGHT_ACCUM4 color = UniversalFragmentBlinnPhong(inputData, surfaceData, UseSpecGlossMap() || UseSpecularColor(), UseAlphaPremultiply(), - ReceiveShadows(), IsSurfaceTypeTransparent(), input.normalWS.xyz); + ReceiveShadows(), IsSurfaceTypeTransparent()); color.rgb = ClampExposed(inputData.preExposureMultiplier * BlendDistanceFog(color.rgb, input.clipPos)); color.a = OutputAlpha(color.a, _Surface); return color; diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree8.shader b/Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree8.shader index 7c51746be13..3a65df3a06a 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree8.shader +++ b/Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree8.shader @@ -54,6 +54,7 @@ Shader "Universal Render Pipeline/Nature/SpeedTree8" #pragma fragment SpeedTree8Frag #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS #pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX #pragma multi_compile_fragment _ _ADDITIONAL_LIGHTS #pragma multi_compile _ _LIGHT_FALLOFF_QUADRATIC @@ -65,6 +66,7 @@ Shader "Universal Render Pipeline/Nature/SpeedTree8" #pragma multi_compile_fragment _ _REFLECTION_PROBE_ATLAS #pragma multi_compile_fragment _ _SCREEN_SPACE_REFLECTION #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH + #pragma multi_compile_fragment _ _SHADOWS_PCSS #pragma multi_compile _ LOD_FADE_CROSSFADE #pragma multi_compile_fragment _ _SCREEN_SPACE_OCCLUSION #pragma multi_compile_fragment _ _LIGHT_COOKIES @@ -143,6 +145,7 @@ Shader "Universal Render Pipeline/Nature/SpeedTree8" #pragma fragment SpeedTree8Frag #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS //#pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX _ADDITIONAL_LIGHTS //#pragma multi_compile _ _ADDITIONAL_LIGHT_SHADOWS #pragma multi_compile_fragment _ _REFLECTION_PROBE_BLENDING @@ -183,6 +186,7 @@ Shader "Universal Render Pipeline/Nature/SpeedTree8" Tags{"LightMode" = "ShadowCaster"} ColorMask 0 + ZClip [_ZClip] HLSLPROGRAM diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree8Passes.hlsl b/Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree8Passes.hlsl index c89e9186724..2b8f0cecd50 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree8Passes.hlsl +++ b/Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree8Passes.hlsl @@ -334,7 +334,7 @@ SpeedTreeVertexDepthOutput SpeedTree8VertDepth(SpeedTreeVertexInput input) return output; } -void InitializeInputData(SpeedTreeFragmentInput input, half3 normalTS, out InputData inputData, out float3 geometricNormalWS) +void InitializeInputData(SpeedTreeFragmentInput input, half3 normalTS, out InputData inputData) { inputData = (InputData)0; inputData.preExposureMultiplier = GetPreExposureMultiplier(); @@ -361,18 +361,18 @@ void InitializeInputData(SpeedTreeFragmentInput input, half3 normalTS, out Input #else half geometricNormalSign = 1.0h; #endif - geometricNormalWS = geometricNormalSign * input.interpolated.normalWS.xyz; + inputData.geometricNormalWS = geometricNormalSign * input.interpolated.normalWS.xyz; #if USE_VERTEX_SHADOW_COORD_INTERPOLATOR #ifdef EFFECT_BACKSIDE_NORMALS // The interpolated shadow coord biases along the front-face normal, which points the wrong way on back faces inputData.shadowCoord = (ShadowCoordInterpolatorAvailable() && geometricNormalSign > 0.0h) ? input.interpolated.shadowCoord - : TransformWorldToShadowCoord(inputData.positionWS, IsSurfaceTypeTransparent(), geometricNormalWS); + : TransformWorldToShadowCoord(inputData.positionWS, IsSurfaceTypeTransparent(), inputData.geometricNormalWS); #else - inputData.shadowCoord = ShadowCoordInterpolatorAvailable() ? input.interpolated.shadowCoord : TransformWorldToShadowCoord(inputData.positionWS, IsSurfaceTypeTransparent(), geometricNormalWS); + inputData.shadowCoord = ShadowCoordInterpolatorAvailable() ? input.interpolated.shadowCoord : TransformWorldToShadowCoord(inputData.positionWS, IsSurfaceTypeTransparent(), inputData.geometricNormalWS); #endif #else - inputData.shadowCoord = MainLightShadowsAvailable() ? TransformWorldToShadowCoord(inputData.positionWS, IsSurfaceTypeTransparent(), geometricNormalWS) : float4(0, 0, 0, 0); + inputData.shadowCoord = MainLightShadowsAvailable() ? TransformWorldToShadowCoord(inputData.positionWS, IsSurfaceTypeTransparent(), inputData.geometricNormalWS) : float4(0, 0, 0, 0); #endif inputData.vertexLighting = input.interpolated.fogFactorAndVertexLight.yzw; @@ -465,8 +465,7 @@ half4 SpeedTree8Frag(SpeedTreeFragmentInput input) : SV_Target #endif InputData inputData; - float3 geometricNormalWS; - InitializeInputData(input, normalTs, inputData, geometricNormalWS); + InitializeInputData(input, normalTs, inputData); SETUP_DEBUG_TEXTURE_DATA(inputData, input.interpolated.uv); #if defined(GBUFFER) || defined(EFFECT_SUBSURFACE) @@ -478,7 +477,7 @@ half4 SpeedTree8Frag(SpeedTreeFragmentInput input) : SV_Target half fSubsurfaceRough = 0.7 - smoothness * 0.5; half fSubsurface = D_GGX(clamp(-dot(mainLight.direction.xyz, inputData.viewDirectionWS.xyz), 0, 1), fSubsurfaceRough); - float4 shadowCoord = TransformWorldToShadowCoord(inputData.positionWS, IsSurfaceTypeTransparent(), geometricNormalWS); + float4 shadowCoord = TransformWorldToShadowCoord(inputData.positionWS, IsSurfaceTypeTransparent(), inputData.geometricNormalWS); half realtimeShadow = ReceiveShadows() ? SampleMainLightRealtimeShadow(shadowCoord, IsSurfaceTypeTransparent()) : half(1.0); float3 tintedSubsurface = tex2D(_SubsurfaceTex, uv).rgb * _SubsurfaceColor.rgb; float3 directSubsurface = tintedSubsurface.rgb * mainLight.color.rgb * fSubsurface * realtimeShadow; @@ -518,7 +517,7 @@ half4 SpeedTree8Frag(SpeedTreeFragmentInput input) : SV_Target URP_LIGHT_ACCUM4 color = UniversalFragmentPBR(inputData, surfaceData, IsSpecularSetup(), UseSpecularHighlights(), UseAlphaPremultiply(), - UseClearCoat() || UseClearCoatMap(), ReceiveShadows(), IsSurfaceTypeTransparent(), UseEnvironmentReflections(), geometricNormalWS); + UseClearCoat() || UseClearCoatMap(), ReceiveShadows(), IsSurfaceTypeTransparent(), UseEnvironmentReflections()); color.rgb = ClampExposed(inputData.preExposureMultiplier * BlendDistanceFog(color.rgb, input.interpolated.clipPos)); color.a = OutputAlpha(color.a, _Surface); diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesLit.shader b/Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesLit.shader index a0067370ce3..c70028ae973 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesLit.shader +++ b/Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesLit.shader @@ -16,6 +16,12 @@ Shader "Universal Render Pipeline/Particles/Lit" [HDR] _EmissionColor("Color", Color) = (0,0,0) _EmissionMap("Emission", 2D) = "white" {} + [ToggleUI] _UseEmissionIntensity("Use Emission Intensity", Float) = 0.0 + // Used only to serialize the LDR and HDR emissive color in the material UI, + // in the shader only the _EmissionColor should be used + [HideInInspector] _EmissionColorLDR("Color LDR", Color) = (1,1,1,1) + _EmissionIntensity("Emission Intensity", Float) = 1.0 + _EmissionIntensityUnit("EmissionIntensity Unit", Int) = 0 // 0=Nits, 1=EV100 [ToggleUI] _ReceiveShadows("Receive Shadows", Float) = 1.0 // ------------------------------------- @@ -130,6 +136,7 @@ Shader "Universal Render Pipeline/Particles/Lit" // ------------------------------------- // Universal Pipeline keywords #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS #pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX #pragma multi_compile_fragment _ _ADDITIONAL_LIGHTS #pragma multi_compile _ _LIGHT_FALLOFF_QUADRATIC @@ -139,6 +146,7 @@ Shader "Universal Render Pipeline/Particles/Lit" #pragma multi_compile_fragment _ _REFLECTION_PROBE_ATLAS #pragma multi_compile_fragment _ _SCREEN_SPACE_REFLECTION #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH + #pragma multi_compile_fragment _ _SHADOWS_PCSS #pragma multi_compile_fragment _ _SCREEN_SPACE_OCCLUSION #pragma multi_compile_fragment _ _DEPTH_AS_INPUT_ATTACHMENT _DEPTH_AS_INPUT_ATTACHMENT_MSAA #pragma multi_compile_fragment _ _LIGHT_COOKIES @@ -222,6 +230,7 @@ Shader "Universal Render Pipeline/Particles/Lit" // ------------------------------------- // Universal Pipeline keywords #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS //#pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX _ADDITIONAL_LIGHTS //#pragma multi_compile _ _ADDITIONAL_LIGHT_SHADOWS #pragma multi_compile_fragment _ _REFLECTION_PROBE_BLENDING @@ -309,8 +318,10 @@ Shader "Universal Render Pipeline/Particles/Lit" ZTest LEqual ColorMask 0 Cull[_Cull] + ZClip [_ZClip] HLSLPROGRAM + #define _SHADOW_CASTER_ZCLIP 1 #pragma target 2.0 // ------------------------------------- diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesLitForwardPass.hlsl b/Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesLitForwardPass.hlsl index 745e511d27d..5cae8e62e9a 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesLitForwardPass.hlsl +++ b/Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesLitForwardPass.hlsl @@ -38,6 +38,7 @@ void InitializeInputData(VaryingsParticle input, half3 normalTS, out InputData i #endif inputData.normalWS = NormalizeNormalPerPixel(inputData.normalWS, UseNormalMap()); + inputData.geometricNormalWS = input.normalWS.xyz; viewDirWS = SafeNormalize(viewDirWS); @@ -149,7 +150,7 @@ half4 ParticlesLitFragment(VaryingsParticle input) : SV_Target URP_LIGHT_ACCUM4 color = UniversalFragmentPBR(inputData, surfaceData, IsSpecularSetup(), UseSpecularHighlights(), UseAlphaPremultiply(), - UseClearCoat() || UseClearCoatMap(), ReceiveShadows(), IsSurfaceTypeTransparent(), UseEnvironmentReflections(), input.normalWS.xyz); + UseClearCoat() || UseClearCoatMap(), ReceiveShadows(), IsSurfaceTypeTransparent(), UseEnvironmentReflections()); color.rgb = ClampExposed(inputData.preExposureMultiplier * BlendDistanceFog(color.rgb, input.clipPos)); #if defined(_TRANSPARENT_RECEIVE_FOG) if (IsSurfaceTypeTransparent()) diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesSimpleLit.shader b/Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesSimpleLit.shader index eb3ac7fa665..6e94a94caac 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesSimpleLit.shader +++ b/Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesSimpleLit.shader @@ -20,6 +20,12 @@ Shader "Universal Render Pipeline/Particles/Simple Lit" [HDR] _EmissionColor("Color", Color) = (0,0,0) _EmissionMap("Emission", 2D) = "white" {} + [ToggleUI] _UseEmissionIntensity("Use Emission Intensity", Float) = 0.0 + // Used only to serialize the LDR and HDR emissive color in the material UI, + // in the shader only the _EmissionColor should be used + [HideInInspector] _EmissionColorLDR("Color LDR", Color) = (1,1,1,1) + _EmissionIntensity("Emission Intensity", Float) = 1.0 + _EmissionIntensityUnit("EmissionIntensity Unit", Int) = 0 // 0=Nits, 1=EV100 _SmoothnessSource("Smoothness Source", Float) = 0.0 _SpecularHighlights("Specular Highlights", Float) = 1.0 @@ -135,11 +141,13 @@ Shader "Universal Render Pipeline/Particles/Simple Lit" // ------------------------------------- // Universal Pipeline keywords #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS #pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX #pragma multi_compile_fragment _ _ADDITIONAL_LIGHTS #pragma multi_compile _ _LIGHT_FALLOFF_QUADRATIC #pragma multi_compile_fragment _ _ADDITIONAL_LIGHT_SHADOWS #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH + #pragma multi_compile_fragment _ _SHADOWS_PCSS #pragma multi_compile_fragment _ _SCREEN_SPACE_OCCLUSION #pragma multi_compile_fragment _ _DEPTH_AS_INPUT_ATTACHMENT _DEPTH_AS_INPUT_ATTACHMENT_MSAA #pragma multi_compile_fragment _ _LIGHT_COOKIES @@ -228,6 +236,7 @@ Shader "Universal Render Pipeline/Particles/Simple Lit" // ------------------------------------- // Universal Pipeline keywords #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS //#pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX _ADDITIONAL_LIGHTS //#pragma multi_compile_fragment _ _ADDITIONAL_LIGHT_SHADOWS #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH @@ -316,8 +325,10 @@ Shader "Universal Render Pipeline/Particles/Simple Lit" ZTest LEqual ColorMask 0 Cull[_Cull] + ZClip [_ZClip] HLSLPROGRAM + #define _SHADOW_CASTER_ZCLIP 1 #pragma target 2.0 // ------------------------------------- diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesSimpleLitForwardPass.hlsl b/Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesSimpleLitForwardPass.hlsl index cdbaaaed499..4769fd3806d 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesSimpleLitForwardPass.hlsl +++ b/Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesSimpleLitForwardPass.hlsl @@ -39,6 +39,7 @@ void InitializeInputData(VaryingsParticle input, half3 normalTS, out InputData i #endif inputData.normalWS = NormalizeNormalPerPixel(inputData.normalWS, UseNormalMap()); + inputData.geometricNormalWS = input.normalWS.xyz; viewDirWS = SafeNormalize(viewDirWS); @@ -161,7 +162,7 @@ half4 ParticlesLitFragment(VaryingsParticle input) : SV_Target InputData inputData; InitializeInputData(input, normalTS, inputData); - URP_LIGHT_ACCUM4 color = UniversalFragmentBlinnPhong(inputData, diffuse, specularGloss, specularGloss.a, emission, alpha, normalTS, input.normalWS.xyz); + URP_LIGHT_ACCUM4 color = UniversalFragmentBlinnPhong(inputData, diffuse, specularGloss, specularGloss.a, emission, alpha, normalTS); color.rgb = ClampExposed(inputData.preExposureMultiplier * BlendDistanceFog(color.rgb, input.clipPos)); #if defined(_TRANSPARENT_RECEIVE_FOG) diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesUnlit.shader b/Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesUnlit.shader index e6cada52cb0..4c9a3d71e06 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesUnlit.shader +++ b/Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesUnlit.shader @@ -8,6 +8,12 @@ Shader "Universal Render Pipeline/Particles/Unlit" _BumpMap("Normal Map", 2D) = "bump" {} [HDR] _EmissionColor("Color", Color) = (0,0,0) _EmissionMap("Emission", 2D) = "white" {} + [ToggleUI] _UseEmissionIntensity("Use Emission Intensity", Float) = 0.0 + // Used only to serialize the LDR and HDR emissive color in the material UI, + // in the shader only the _EmissionColor should be used + [HideInInspector] _EmissionColorLDR("Color LDR", Color) = (1,1,1,1) + _EmissionIntensity("Emission Intensity", Float) = 1.0 + _EmissionIntensityUnit("EmissionIntensity Unit", Int) = 0 // 0=Nits, 1=EV100 // ------------------------------------- // Particle specific @@ -187,8 +193,10 @@ Shader "Universal Render Pipeline/Particles/Unlit" ZTest LEqual ColorMask 0 Cull[_Cull] + ZClip [_ZClip] HLSLPROGRAM + #define _SHADOW_CASTER_ZCLIP 1 #pragma target 2.0 // ------------------------------------- diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/SimpleLit.shader b/Packages/com.unity.render-pipelines.universal/Shaders/SimpleLit.shader index ee955f8b7d3..7bdb922d245 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/SimpleLit.shader +++ b/Packages/com.unity.render-pipelines.universal/Shaders/SimpleLit.shader @@ -22,6 +22,12 @@ Shader "Universal Render Pipeline/Simple Lit" [HDR] _EmissionColor("Emission Color", Color) = (0,0,0) [NoScaleOffset]_EmissionMap("Emission Map", 2D) = "white" {} + [ToggleUI] _UseEmissionIntensity("Use Emission Intensity", Float) = 0.0 + // Used only to serialize the LDR and HDR emissive color in the material UI, + // in the shader only the _EmissionColor should be used + [HideInInspector] _EmissionColorLDR("Color LDR", Color) = (1,1,1,1) + _EmissionIntensity("Emission Intensity", Float) = 1.0 + _EmissionIntensityUnit("EmissionIntensity Unit", Int) = 0 // 0=Nits, 1=EV100 // Blending state _Surface("__surface", Float) = 0.0 @@ -107,6 +113,7 @@ Shader "Universal Render Pipeline/Simple Lit" #pragma multi_compile _ META_QUEST_LIGHTUNROLL #endif #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS #pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX #pragma multi_compile_fragment _ _ADDITIONAL_LIGHTS #pragma multi_compile _ _LIGHT_FALLOFF_QUADRATIC @@ -122,6 +129,7 @@ Shader "Universal Render Pipeline/Simple Lit" #endif #pragma multi_compile_fragment _ _ADDITIONAL_LIGHT_SHADOWS #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH + #pragma multi_compile_fragment _ _SHADOWS_PCSS #pragma multi_compile_fragment _ _SCREEN_SPACE_OCCLUSION #pragma multi_compile_fragment _ _SCREEN_SPACE_IRRADIANCE #pragma multi_compile_fragment _ _DBUFFER_MRT1 _DBUFFER_MRT2 _DBUFFER_MRT3 @@ -176,8 +184,10 @@ Shader "Universal Render Pipeline/Simple Lit" ZTest LEqual ColorMask 0 Cull[_Cull] + ZClip [_ZClip] HLSLPROGRAM + #define _SHADOW_CASTER_ZCLIP 1 #pragma target 2.0 // ------------------------------------- @@ -248,6 +258,7 @@ Shader "Universal Render Pipeline/Simple Lit" // ------------------------------------- // Universal Pipeline keywords #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS //#pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX _ADDITIONAL_LIGHTS //#pragma multi_compile _ _ADDITIONAL_LIGHT_SHADOWS #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/SimpleLitForwardPass.hlsl b/Packages/com.unity.render-pipelines.universal/Shaders/SimpleLitForwardPass.hlsl index 1d1e84fd746..105e0204a95 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/SimpleLitForwardPass.hlsl +++ b/Packages/com.unity.render-pipelines.universal/Shaders/SimpleLitForwardPass.hlsl @@ -96,6 +96,7 @@ void InitializeInputData(Varyings input, half3 normalTS, out InputData inputData #endif inputData.normalWS = NormalizeNormalPerPixel(inputData.normalWS, UseNormalMap()); + inputData.geometricNormalWS = input.normalWS.xyz; viewDirWS = SafeNormalize(viewDirWS); inputData.viewDirectionWS = viewDirWS; @@ -249,7 +250,7 @@ void LitPassFragmentSimple( URP_LIGHT_ACCUM4 color = UniversalFragmentBlinnPhong(inputData, surfaceData, UseSpecGlossMap() || UseSpecularColor(), UseAlphaPremultiply(), - ReceiveShadows(), IsSurfaceTypeTransparent(), input.normalWS.xyz); + ReceiveShadows(), IsSurfaceTypeTransparent()); color.rgb = ClampExposed(inputData.preExposureMultiplier * BlendDistanceFog(color.rgb, input.positionCS)); #if defined(_TRANSPARENT_RECEIVE_FOG) if (IsSurfaceTypeTransparent()) diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainDetailLit.shader b/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainDetailLit.shader index 4b64b01c446..6f55f7b2203 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainDetailLit.shader +++ b/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainDetailLit.shader @@ -21,6 +21,7 @@ Shader "Hidden/TerrainEngine/Details/UniversalPipeline/Vertexlit" // ------------------------------------- // Universal Pipeline keywords #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS #pragma multi_compile_vertex _ _ADDITIONAL_LIGHTS_VERTEX _ADDITIONAL_LIGHTS #pragma multi_compile _ _LIGHT_FALLOFF_QUADRATIC #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH @@ -70,6 +71,7 @@ Shader "Hidden/TerrainEngine/Details/UniversalPipeline/Vertexlit" // ------------------------------------- // Universal Pipeline keywords #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS #pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX //_ADDITIONAL_LIGHTS //#pragma multi_compile _ _ADDITIONAL_LIGHT_SHADOWS #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH @@ -84,10 +86,12 @@ Shader "Hidden/TerrainEngine/Details/UniversalPipeline/Vertexlit" #include_with_pragmas "Packages/com.unity.render-pipelines.universal/ShaderLibrary/ProbeVolumeVariants.hlsl" #pragma multi_compile_fragment _ _GBUFFER_NORMALS_OCT #pragma multi_compile_fragment _ _RENDER_PASS_ENABLED + #include_with_pragmas "Packages/com.unity.render-pipelines.universal/ShaderLibrary/RenderingLayers.hlsl" #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/GBufferOutput.hlsl" + #include_with_pragmas "Packages/com.unity.render-pipelines.universal/ShaderLibrary/GBufferOutputFormat.hlsl" #include "Packages/com.unity.render-pipelines.universal/Shaders/Utils/SurfaceType.hlsl" #include "Packages/com.unity.render-pipelines.universal/Shaders/Utils/ReceiveShadows.hlsl" @@ -166,14 +170,14 @@ Shader "Hidden/TerrainEngine/Details/UniversalPipeline/Vertexlit" #endif Light mainLight = GetMainLight(); - half3 attenuatedLightColor = mainLight.color * mainLight.distanceAttenuation; + URP_LIGHT_ACCUM3 attenuatedLightColor = mainLight.color * mainLight.distanceAttenuation; URP_LIGHT_ACCUM3 diffuseColor = LightingLambert(attenuatedLightColor, mainLight.direction, output.NormalWS); #ifdef _ADDITIONAL_LIGHTS int pixelLightCount = GetAdditionalLightsCount(); for (int i = 0; i < pixelLightCount; ++i) { Light light = GetAdditionalLight(i, vertexInput.positionWS); - half3 attenuatedLightColor = light.color * light.distanceAttenuation; + URP_LIGHT_ACCUM3 attenuatedLightColor = light.color * light.distanceAttenuation; diffuseColor += LightingLambert(attenuatedLightColor, light.direction, output.NormalWS); } #endif diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainDetailLitPasses.hlsl b/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainDetailLitPasses.hlsl index b8d39091df4..88afa8d342f 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainDetailLitPasses.hlsl +++ b/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainDetailLitPasses.hlsl @@ -174,8 +174,8 @@ Varyings TerrainLitVertex(Attributes input) } #endif Light mainLight = GetMainLight(); - half3 attenuatedLightColor = mainLight.color * mainLight.distanceAttenuation; - URP_LIGHT_ACCUM3 diffuseColor = half3(0, 0, 0); + URP_LIGHT_ACCUM3 attenuatedLightColor = mainLight.color * mainLight.distanceAttenuation; + URP_LIGHT_ACCUM3 diffuseColor = URP_LIGHT_ACCUM3(0, 0, 0); if (IsLightingFeatureEnabled(DEBUGLIGHTINGFEATUREFLAGS_MAIN_LIGHT)) { @@ -190,7 +190,7 @@ Varyings TerrainLitVertex(Attributes input) for (int i = 0; i < pixelLightCount; ++i) { Light light = GetAdditionalLight(i, vertexInput.positionWS); - half3 attenuatedLightColor = light.color * light.distanceAttenuation; + URP_LIGHT_ACCUM3 attenuatedLightColor = light.color * light.distanceAttenuation; diffuseColor += LightingLambert(attenuatedLightColor, light.direction, NormalWS); } } diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLit.shader b/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLit.shader index fb4e0429c11..3339f09ec71 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLit.shader +++ b/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLit.shader @@ -66,6 +66,7 @@ Shader "Universal Render Pipeline/Terrain/Lit" // ------------------------------------- // Universal Pipeline keywords #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS #pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX #pragma multi_compile_fragment _ _ADDITIONAL_LIGHTS #pragma multi_compile _ _LIGHT_FALLOFF_QUADRATIC @@ -84,6 +85,7 @@ Shader "Universal Render Pipeline/Terrain/Lit" #pragma multi_compile_fragment _ _REFLECTION_PROBE_ATLAS #pragma multi_compile_fragment _ _SCREEN_SPACE_REFLECTION #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH + #pragma multi_compile_fragment _ _SHADOWS_PCSS #pragma multi_compile_fragment _ _SCREEN_SPACE_OCCLUSION #pragma multi_compile_fragment _ _SCREEN_SPACE_IRRADIANCE #pragma multi_compile_fragment _ _DBUFFER_MRT1 _DBUFFER_MRT2 _DBUFFER_MRT3 @@ -127,8 +129,10 @@ Shader "Universal Render Pipeline/Terrain/Lit" ZWrite On ColorMask 0 + ZClip [_ZClip] HLSLPROGRAM + #define _SHADOW_CASTER_ZCLIP 1 #pragma target 2.0 #pragma vertex ShadowPassVertex @@ -169,6 +173,7 @@ Shader "Universal Render Pipeline/Terrain/Lit" // ------------------------------------- // Universal Pipeline keywords #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS //#pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX _ADDITIONAL_LIGHTS //#pragma multi_compile _ _ADDITIONAL_LIGHT_SHADOWS #pragma multi_compile_fragment _ _REFLECTION_PROBE_BLENDING diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitAdd.shader b/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitAdd.shader index 09087bfe700..119030567d9 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitAdd.shader +++ b/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitAdd.shader @@ -61,6 +61,7 @@ Shader "Hidden/Universal Render Pipeline/Terrain/Lit (Add Pass)" // ------------------------------------- // Universal Pipeline keywords #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS #pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX #pragma multi_compile_fragment _ _ADDITIONAL_LIGHTS #pragma multi_compile _ _LIGHT_FALLOFF_QUADRATIC @@ -78,6 +79,7 @@ Shader "Hidden/Universal Render Pipeline/Terrain/Lit (Add Pass)" #pragma multi_compile_fragment _ _REFLECTION_PROBE_ATLAS #pragma multi_compile_fragment _ _SCREEN_SPACE_REFLECTION #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH + #pragma multi_compile_fragment _ _SHADOWS_PCSS #pragma multi_compile_fragment _ _SCREEN_SPACE_OCCLUSION #pragma multi_compile_fragment _ _LIGHT_COOKIES #pragma multi_compile_fragment _ _VOLUMETRIC_FOG @@ -145,6 +147,7 @@ Shader "Hidden/Universal Render Pipeline/Terrain/Lit (Add Pass)" // ------------------------------------- // Universal Pipeline keywords #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS #pragma multi_compile_fragment _ _REFLECTION_PROBE_BLENDING #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH #pragma multi_compile_fragment _ _CLUSTER_LIGHT_LOOP diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitBase.shader b/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitBase.shader index 0c61453b218..3e02ce2f4ea 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitBase.shader +++ b/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitBase.shader @@ -39,6 +39,7 @@ Shader "Hidden/Universal Render Pipeline/Terrain/Lit (Base Pass)" // ------------------------------------- // Universal Pipeline keywords #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS #pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX #pragma multi_compile_fragment _ _ADDITIONAL_LIGHTS #pragma multi_compile _ _LIGHT_FALLOFF_QUADRATIC @@ -56,6 +57,7 @@ Shader "Hidden/Universal Render Pipeline/Terrain/Lit (Base Pass)" #pragma multi_compile_fragment _ _REFLECTION_PROBE_ATLAS #pragma multi_compile_fragment _ _SCREEN_SPACE_REFLECTION #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH + #pragma multi_compile_fragment _ _SHADOWS_PCSS #pragma multi_compile_fragment _ _SCREEN_SPACE_OCCLUSION #pragma multi_compile_fragment _ _LIGHT_COOKIES #pragma multi_compile_fragment _ _VOLUMETRIC_FOG @@ -98,8 +100,10 @@ Shader "Hidden/Universal Render Pipeline/Terrain/Lit (Base Pass)" ZWrite On ColorMask 0 + ZClip [_ZClip] HLSLPROGRAM + #define _SHADOW_CASTER_ZCLIP 1 #pragma target 2.0 #pragma multi_compile_instancing @@ -135,6 +139,7 @@ Shader "Hidden/Universal Render Pipeline/Terrain/Lit (Base Pass)" // ------------------------------------- // Universal Pipeline keywords #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS //#pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX _ADDITIONAL_LIGHTS //#pragma multi_compile _ _ADDITIONAL_LIGHT_SHADOWS #pragma multi_compile_fragment _ _REFLECTION_PROBE_BLENDING diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitPasses.hlsl b/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitPasses.hlsl index a55afd769d1..57827ad6a05 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitPasses.hlsl +++ b/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitPasses.hlsl @@ -60,7 +60,7 @@ struct Varyings UNITY_VERTEX_OUTPUT_STEREO }; -void InitializeInputData(Varyings IN, half3 normalTS, out InputData inputData, out half3 geometricNormalWS) +void InitializeInputData(Varyings IN, half3 normalTS, out InputData inputData) { inputData = (InputData)0; inputData.preExposureMultiplier = GetPreExposureMultiplier(); @@ -71,7 +71,7 @@ void InitializeInputData(Varyings IN, half3 normalTS, out InputData inputData, o inputData.normalWS = IN.normal.xyz; half3 viewDirWS = GetWorldSpaceNormalizeViewDir(IN.positionWS); half3 SH = 0; - geometricNormalWS = IN.normal.xyz; + half3 geometricNormalWS = IN.normal.xyz; #if defined(REQUIRES_WORLD_SPACE_TANGENT_INTERPOLATOR) if (UseNormalMap()) @@ -99,6 +99,7 @@ void InitializeInputData(Varyings IN, half3 normalTS, out InputData inputData, o #endif inputData.normalWS = NormalizeNormalPerPixel(inputData.normalWS, UseNormalMap()); + inputData.geometricNormalWS = geometricNormalWS; inputData.viewDirectionWS = viewDirWS; #if USE_VERTEX_SHADOW_COORD_INTERPOLATOR @@ -468,8 +469,7 @@ void SplatmapFragment( #endif InputData inputData; - half3 geometricNormalWS; - InitializeInputData(IN, normalTS, inputData, geometricNormalWS); + InitializeInputData(IN, normalTS, inputData); SetupTerrainDebugTextureData(inputData, IN.uvMainAndLM.xy); #if defined(_DBUFFER) @@ -510,7 +510,7 @@ void SplatmapFragment( return PackGBuffersBRDFData(brdfData, inputData, smoothness, ClampExposed(inputData.preExposureMultiplier * color.rgb), occlusion, ReceiveShadows(), IsSpecularSetup(), UseSpecularHighlights()); #else - URP_LIGHT_ACCUM4 color = UniversalFragmentPBR(inputData, albedo, metallic, /* specular */ half3(0.0h, 0.0h, 0.0h), smoothness, occlusion, /* emission */ half3(0, 0, 0), alpha, geometricNormalWS); + URP_LIGHT_ACCUM4 color = UniversalFragmentPBR(inputData, albedo, metallic, /* specular */ half3(0.0h, 0.0h, 0.0h), smoothness, occlusion, /* emission */ half3(0, 0, 0), alpha); SplatmapFinalColor(color, IN.clipPos); @@ -561,12 +561,7 @@ VaryingsLean ShadowPassVertex(AttributesLean v) #endif float4 clipPos = TransformWorldToHClip(ApplyShadowBias(positionWS, normalWS, lightDirectionWS)); - -#if UNITY_REVERSED_Z - clipPos.z = min(clipPos.z, UNITY_NEAR_CLIP_VALUE); -#else - clipPos.z = max(clipPos.z, UNITY_NEAR_CLIP_VALUE); -#endif + clipPos = ApplyShadowClamping(clipPos); o.clipPos = clipPos; diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/WavingGrass.shader b/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/WavingGrass.shader index 77db6096f79..2244b81225e 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/WavingGrass.shader +++ b/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/WavingGrass.shader @@ -29,6 +29,7 @@ Shader "Hidden/TerrainEngine/Details/UniversalPipeline/WavingDoublePass" // ------------------------------------- // Universal Pipeline keywords #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS #pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX #pragma multi_compile_fragment _ _ADDITIONAL_LIGHTS #pragma multi_compile _ _LIGHT_FALLOFF_QUADRATIC @@ -44,6 +45,7 @@ Shader "Hidden/TerrainEngine/Details/UniversalPipeline/WavingDoublePass" #endif #pragma multi_compile_fragment _ _ADDITIONAL_LIGHT_SHADOWS #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH + #pragma multi_compile_fragment _ _SHADOWS_PCSS #pragma multi_compile_fragment _ _SCREEN_SPACE_OCCLUSION #pragma multi_compile_fragment _ _SCREEN_SPACE_IRRADIANCE #pragma multi_compile_fragment _ _LIGHT_COOKIES @@ -97,6 +99,7 @@ Shader "Hidden/TerrainEngine/Details/UniversalPipeline/WavingDoublePass" // ------------------------------------- // Universal Pipeline keywords #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH #pragma multi_compile_fragment _ _LIGHT_COOKIES #pragma multi_compile_fragment _ _VOLUMETRIC_FOG diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/WavingGrassBillboard.shader b/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/WavingGrassBillboard.shader index 720f73f3d09..cfa2a22c86c 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/WavingGrassBillboard.shader +++ b/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/WavingGrassBillboard.shader @@ -29,11 +29,13 @@ Shader "Hidden/TerrainEngine/Details/UniversalPipeline/BillboardWavingDoublePass // ------------------------------------- // Universal Pipeline keywords #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS #pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX #pragma multi_compile_fragment _ _ADDITIONAL_LIGHTS #pragma multi_compile _ _LIGHT_FALLOFF_QUADRATIC #pragma multi_compile_fragment _ _ADDITIONAL_LIGHT_SHADOWS #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH + #pragma multi_compile_fragment _ _SHADOWS_PCSS #pragma multi_compile _ LIGHTMAP_SHADOW_MIXING #pragma multi_compile _ SHADOWS_SHADOWMASK #pragma multi_compile_fragment _ _CLUSTER_LIGHT_LOOP @@ -89,12 +91,14 @@ Shader "Hidden/TerrainEngine/Details/UniversalPipeline/BillboardWavingDoublePass // ------------------------------------- // Universal Pipeline keywords #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile _ _SHADOW_RECEIVER_NORMAL_BIAS #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH #pragma multi_compile_fragment _ _RENDER_PASS_ENABLED #pragma multi_compile_fragment _ _GBUFFER_NORMALS_OCT #pragma multi_compile_fragment _ _SCREEN_SPACE_IRRADIANCE #pragma multi_compile _ _EXPOSURE #include_with_pragmas "Packages/com.unity.render-pipelines.core/ShaderLibrary/FoveatedRenderingKeywords.hlsl" + #include_with_pragmas "Packages/com.unity.render-pipelines.universal/ShaderLibrary/RenderingLayers.hlsl" // ------------------------------------- // Unity defined keywords @@ -104,6 +108,7 @@ Shader "Hidden/TerrainEngine/Details/UniversalPipeline/BillboardWavingDoublePass //-------------------------------------- // GPU Instancing #pragma multi_compile_instancing + #pragma instancing_options renderinglayer #pragma vertex WavingGrassBillboardVert #pragma fragment LitPassFragmentGrass diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/WavingGrassPasses.hlsl b/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/WavingGrassPasses.hlsl index 29cd2e3929b..3f86f36376e 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/WavingGrassPasses.hlsl +++ b/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/WavingGrassPasses.hlsl @@ -63,6 +63,7 @@ void InitializeInputData(GrassVertexOutput input, out InputData inputData) viewDirWS = SafeNormalize(viewDirWS); inputData.normalWS = NormalizeNormalPerPixel(input.normal, UseNormalMap()); + inputData.geometricNormalWS = input.normal.xyz; inputData.viewDirectionWS = viewDirWS; #if USE_VERTEX_SHADOW_COORD_INTERPOLATOR @@ -235,7 +236,7 @@ half4 LitPassFragmentGrass(GrassVertexOutput input) : SV_Target #else URP_LIGHT_ACCUM4 color = UniversalFragmentBlinnPhong(inputData, surfaceData, UseSpecGlossMap() || UseSpecularColor(), UseAlphaPremultiply(), - ReceiveShadows(), IsSurfaceTypeTransparent(), input.normal.xyz); + ReceiveShadows(), IsSurfaceTypeTransparent()); color.rgb = ClampExposed(inputData.preExposureMultiplier * BlendDistanceFog(color.rgb, input.clipPos)); return half4(color.rgb, OutputAlpha(surfaceData.alpha, IsSurfaceTypeTransparent(_Surface))); #endif diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/UI.meta b/Packages/com.unity.render-pipelines.universal/Shaders/UI.meta new file mode 100644 index 00000000000..cb24c101800 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Shaders/UI.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: db4a67e4c5b045ba928d1a130de30686 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-Bumped.shader b/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-Bumped.shader new file mode 100644 index 00000000000..3bda77acba7 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-Bumped.shader @@ -0,0 +1,87 @@ +Shader "UI/Lit/Bumped" +{ + Properties + { + _Color ("Main Color", Color) = (1,1,1,1) + _Specular ("Specular Color", Color) = (0,0,0,0) + _MainTex ("Diffuse (RGB), Alpha (A)", 2D) = "white" {} + [NoScaleOffset] _MainBump ("Diffuse Bump Map", 2D) = "bump" {} + [PowerSlider(5.0)] _Shininess ("Shininess", Range(0.01, 1.0)) = 0.2 + + _StencilComp ("Stencil Comparison", Float) = 8 + _Stencil ("Stencil ID", Float) = 0 + _StencilOp ("Stencil Operation", Float) = 0 + _StencilWriteMask ("Stencil Write Mask", Float) = 255 + _StencilReadMask ("Stencil Read Mask", Float) = 255 + + _ColorMask ("Color Mask", Float) = 15 + + [Toggle(UNITY_UI_ALPHACLIP)] _UseUIAlphaClip ("Use Alpha Clip", Float) = 0 + } + + SubShader + { + LOD 400 + + Tags + { + "Queue" = "Transparent" + "IgnoreProjector" = "True" + "RenderType" = "Transparent" + "PreviewType" = "Plane" + "RenderPipeline" = "UniversalPipeline" + } + + Stencil + { + Ref [_Stencil] + Comp [_StencilComp] + Pass [_StencilOp] + ReadMask [_StencilReadMask] + WriteMask [_StencilWriteMask] + } + + Cull Off + ZWrite Off + ZTest [unity_GUIZTestMode] + Blend SrcAlpha OneMinusSrcAlpha + ColorMask [_ColorMask] + + Pass + { + Name "Default" + Tags { "LightMode" = "UniversalForward" } + + HLSLPROGRAM + #pragma target 3.0 + #pragma vertex UILitVertex + #pragma fragment Fragment + + #pragma multi_compile_local _ UNITY_UI_CLIP_RECT + #pragma multi_compile_local _ UNITY_UI_ALPHACLIP + #pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX + #pragma multi_compile_fragment _ _ADDITIONAL_LIGHTS + #pragma multi_compile_fragment _ _CLUSTER_LIGHT_LOOP + #pragma multi_compile_fragment _ _LIGHT_COOKIES + #pragma multi_compile _ _LIGHT_FALLOFF_QUADRATIC + #pragma multi_compile_instancing + + #include "Packages/com.unity.render-pipelines.universal/Shaders/UI/UILit.hlsl" + + half4 Fragment(UILitVaryings input) : SV_Target + { + UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input); + + half4 col = (SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, input.uv.xy) + _TextureSampleAdd) * input.color; + half3 normalTS = UnpackNormal(SAMPLE_TEXTURE2D(_MainBump, sampler_MainBump, input.uv.xy)); + float3 normalWS = UILitTangentToWorld(input, normalTS); + + half3 color = UILitShade(input, col.rgb, _Specular.a, _Shininess, normalWS); + return UILitOutput(input, color, col.a); + } + ENDHLSL + } + } + + Fallback "UI/Lit/Transparent" +} diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-Bumped.shader.meta b/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-Bumped.shader.meta new file mode 100644 index 00000000000..e541c4350f7 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-Bumped.shader.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 803acc1b5a714730900f6a3e8612f600 +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + preprocessorOverride: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-Detail.shader b/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-Detail.shader new file mode 100644 index 00000000000..737a6febec4 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-Detail.shader @@ -0,0 +1,96 @@ +Shader "UI/Lit/Detail" +{ + Properties + { + _Color ("Main Color", Color) = (1,1,1,1) + _Specular ("Specular Color", Color) = (0,0,0,0) + _MainTex ("Diffuse (RGB), Alpha (A)", 2D) = "white" {} + _MainBump ("Diffuse Bump Map", 2D) = "bump" {} + _DetailTex ("Detail (RGB)", 2D) = "white" {} + _DetailBump ("Detail Bump Map", 2D) = "bump" {} + _Strength ("Detail Strength", Range(0.0, 1.0)) = 0.2 + [PowerSlider(5.0)] _Shininess ("Shininess", Range(0.01, 1.0)) = 0.2 + + _StencilComp ("Stencil Comparison", Float) = 8 + _Stencil ("Stencil ID", Float) = 0 + _StencilOp ("Stencil Operation", Float) = 0 + _StencilWriteMask ("Stencil Write Mask", Float) = 255 + _StencilReadMask ("Stencil Read Mask", Float) = 255 + + _ColorMask ("Color Mask", Float) = 15 + + [Toggle(UNITY_UI_ALPHACLIP)] _UseUIAlphaClip ("Use Alpha Clip", Float) = 0 + } + + SubShader + { + LOD 100 + + Tags + { + "Queue" = "Transparent" + "IgnoreProjector" = "True" + "RenderType" = "Transparent" + "PreviewType" = "Plane" + "RenderPipeline" = "UniversalPipeline" + } + + Stencil + { + Ref [_Stencil] + Comp [_StencilComp] + Pass [_StencilOp] + ReadMask [_StencilReadMask] + WriteMask [_StencilWriteMask] + } + + Cull Off + ZWrite Off + ZTest [unity_GUIZTestMode] + Blend SrcAlpha OneMinusSrcAlpha + ColorMask [_ColorMask] + + Pass + { + Name "Default" + Tags { "LightMode" = "UniversalForward" } + + HLSLPROGRAM + #pragma target 3.0 + #pragma vertex UILitVertex + #pragma fragment Fragment + + #pragma multi_compile_local _ UNITY_UI_CLIP_RECT + #pragma multi_compile_local _ UNITY_UI_ALPHACLIP + #pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX + #pragma multi_compile_fragment _ _ADDITIONAL_LIGHTS + #pragma multi_compile_fragment _ _CLUSTER_LIGHT_LOOP + #pragma multi_compile_fragment _ _LIGHT_COOKIES + #pragma multi_compile _ _LIGHT_FALLOFF_QUADRATIC + #pragma multi_compile_instancing + + #include "Packages/com.unity.render-pipelines.universal/Shaders/UI/UILit.hlsl" + + half4 Fragment(UILitVaryings input) : SV_Target + { + UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input); + + half4 col = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, input.uv.xy) + _TextureSampleAdd; + half4 detail = SAMPLE_TEXTURE2D(_DetailTex, sampler_DetailTex, input.detailUV.xy); + half4 nmMain = SAMPLE_TEXTURE2D(_MainBump, sampler_MainBump, input.uv.xy); + half4 nmDetail = SAMPLE_TEXTURE2D(_DetailBump, sampler_DetailBump, input.detailUV.xy); + half3 normalTS = UnpackNormal((nmMain + nmDetail) * 0.5); + float3 normalWS = UILitTangentToWorld(input, normalTS); + + col.rgb = lerp(col.rgb, col.rgb * detail.rgb, detail.a * _Strength); + col *= input.color; + + half3 color = UILitShade(input, col.rgb, _Specular.a, _Shininess, normalWS); + return UILitOutput(input, color, col.a); + } + ENDHLSL + } + } + + Fallback "UI/Lit/Transparent" +} diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-Detail.shader.meta b/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-Detail.shader.meta new file mode 100644 index 00000000000..91f9501ee09 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-Detail.shader.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 570cda91f48e4ab68e0f240b015894f3 +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + preprocessorOverride: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-Refraction.shader b/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-Refraction.shader new file mode 100644 index 00000000000..57955b82042 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-Refraction.shader @@ -0,0 +1,94 @@ +Shader "UI/Lit/Refraction" +{ + Properties + { + _Color ("Main Color", Color) = (1,1,1,1) + _Specular ("Specular Color", Color) = (0,0,0,0) + _MainTex ("Diffuse (RGB), Alpha (A)", 2D) = "white" {} + _MainBump ("Diffuse Bump Map", 2D) = "bump" {} + _Mask ("Mask (Specularity, Shininess, Refraction)", 2D) = "black" {} + [PowerSlider(5.0)] _Shininess ("Shininess", Range(0.01, 1.0)) = 0.2 + _Focus ("Focus", Range(-100.0, 100.0)) = -100.0 + + _StencilComp ("Stencil Comparison", Float) = 8 + _Stencil ("Stencil ID", Float) = 0 + _StencilOp ("Stencil Operation", Float) = 0 + _StencilWriteMask ("Stencil Write Mask", Float) = 255 + _StencilReadMask ("Stencil Read Mask", Float) = 255 + + _ColorMask ("Color Mask", Float) = 15 + + [Toggle(UNITY_UI_ALPHACLIP)] _UseUIAlphaClip ("Use Alpha Clip", Float) = 0 + } + + SubShader + { + LOD 400 + + Tags + { + "Queue" = "Transparent" + "IgnoreProjector" = "True" + "RenderType" = "Transparent" + "PreviewType" = "Plane" + "RenderPipeline" = "UniversalPipeline" + } + + Stencil + { + Ref [_Stencil] + Comp [_StencilComp] + Pass [_StencilOp] + ReadMask [_StencilReadMask] + WriteMask [_StencilWriteMask] + } + + Cull Off + ZWrite Off + ZTest [unity_GUIZTestMode] + Blend SrcAlpha OneMinusSrcAlpha + ColorMask [_ColorMask] + + Pass + { + Name "Default" + Tags { "LightMode" = "UniversalForward" } + + HLSLPROGRAM + #pragma target 3.0 + #pragma vertex UILitVertex + #pragma fragment Fragment + + #pragma multi_compile_local _ UNITY_UI_CLIP_RECT + #pragma multi_compile_local _ UNITY_UI_ALPHACLIP + #pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX + #pragma multi_compile_fragment _ _ADDITIONAL_LIGHTS + #pragma multi_compile_fragment _ _CLUSTER_LIGHT_LOOP + #pragma multi_compile_fragment _ _LIGHT_COOKIES + #pragma multi_compile _ _LIGHT_FALLOFF_QUADRATIC + #pragma multi_compile_instancing + + #include "Packages/com.unity.render-pipelines.universal/Shaders/UI/UILit.hlsl" + + half4 Fragment(UILitVaryings input) : SV_Target + { + UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input); + + half4 col = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, input.uv.xy) + _TextureSampleAdd; + half3 normalTS = UnpackNormal(SAMPLE_TEXTURE2D(_MainBump, sampler_MainBump, input.uv.zw)); + half3 mask = SAMPLE_TEXTURE2D(_Mask, sampler_Mask, input.uv.xy).rgb; + + // Replaces the Built-in GrabPass with the URP opaque texture + col.rgb = UILitApplyRefraction(input, col.rgb, normalTS, mask.b); + col *= input.color; + + float3 normalWS = UILitTangentToWorld(input, normalTS); + half3 color = UILitShade(input, col.rgb, _Specular.a * mask.r, _Shininess * mask.g, normalWS); + return UILitOutput(input, color, col.a); + } + ENDHLSL + } + } + + Fallback "UI/Lit/Transparent" +} diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-Refraction.shader.meta b/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-Refraction.shader.meta new file mode 100644 index 00000000000..271cf1278dd --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-Refraction.shader.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 6176573355f948f59da051d300add3ec +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + preprocessorOverride: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-RefractionDetail.shader b/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-RefractionDetail.shader new file mode 100644 index 00000000000..c4dc018eda3 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-RefractionDetail.shader @@ -0,0 +1,101 @@ +Shader "UI/Lit/Refraction Detail" +{ + Properties + { + _Color ("Main Color", Color) = (1,1,1,1) + _Specular ("Specular Color", Color) = (0,0,0,0) + _MainTex ("Diffuse (RGB), Alpha (A)", 2D) = "white" {} + _MainBump ("Diffuse Bump Map", 2D) = "bump" {} + _Mask ("Mask (Specularity, Shininess, Refraction)", 2D) = "white" {} + _DetailTex ("Detail (RGB)", 2D) = "white" {} + _DetailBump ("Detail Bump Map", 2D) = "bump" {} + _DetailMask ("Detail Mask (Spec, Shin, Ref)", 2D) = "white" {} + [PowerSlider(5.0)] _Shininess ("Shininess", Range(0.01, 1.0)) = 0.2 + _Focus ("Focus", Range(-100.0, 100.0)) = -100.0 + + _StencilComp ("Stencil Comparison", Float) = 8 + _Stencil ("Stencil ID", Float) = 0 + _StencilOp ("Stencil Operation", Float) = 0 + _StencilWriteMask ("Stencil Write Mask", Float) = 255 + _StencilReadMask ("Stencil Read Mask", Float) = 255 + + _ColorMask ("Color Mask", Float) = 15 + + [Toggle(UNITY_UI_ALPHACLIP)] _UseUIAlphaClip ("Use Alpha Clip", Float) = 0 + } + + SubShader + { + LOD 400 + + Tags + { + "Queue" = "Transparent" + "IgnoreProjector" = "True" + "RenderType" = "Transparent" + "PreviewType" = "Plane" + "RenderPipeline" = "UniversalPipeline" + } + + Stencil + { + Ref [_Stencil] + Comp [_StencilComp] + Pass [_StencilOp] + ReadMask [_StencilReadMask] + WriteMask [_StencilWriteMask] + } + + Cull Off + ZWrite Off + ZTest [unity_GUIZTestMode] + Blend SrcAlpha OneMinusSrcAlpha + ColorMask [_ColorMask] + + Pass + { + Name "Default" + Tags { "LightMode" = "UniversalForward" } + + HLSLPROGRAM + #pragma target 3.0 + #pragma vertex UILitVertex + #pragma fragment Fragment + + #pragma multi_compile_local _ UNITY_UI_CLIP_RECT + #pragma multi_compile_local _ UNITY_UI_ALPHACLIP + #pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX + #pragma multi_compile_fragment _ _ADDITIONAL_LIGHTS + #pragma multi_compile_fragment _ _CLUSTER_LIGHT_LOOP + #pragma multi_compile_fragment _ _LIGHT_COOKIES + #pragma multi_compile _ _LIGHT_FALLOFF_QUADRATIC + #pragma multi_compile_instancing + + #include "Packages/com.unity.render-pipelines.universal/Shaders/UI/UILit.hlsl" + + half4 Fragment(UILitVaryings input) : SV_Target + { + UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input); + + half4 col = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, input.uv.xy) + _TextureSampleAdd; + half4 detail = SAMPLE_TEXTURE2D(_DetailTex, sampler_DetailTex, input.detailUV.xy); + half3 normalTS = UnpackNormal(SAMPLE_TEXTURE2D(_MainBump, sampler_MainBump, input.uv.zw)) + + UnpackNormal(SAMPLE_TEXTURE2D(_DetailBump, sampler_DetailBump, input.detailUV.zw)); + half3 mask = SAMPLE_TEXTURE2D(_Mask, sampler_Mask, input.uv.xy).rgb * + SAMPLE_TEXTURE2D(_DetailMask, sampler_DetailMask, input.maskUV.xy).rgb; + + // Replaces the Built-in GrabPass with the URP opaque texture + col.rgb = UILitApplyRefraction(input, col.rgb, normalTS, mask.b); + col.rgb = lerp(col.rgb, col.rgb * detail.rgb, detail.a); + col *= input.color; + + float3 normalWS = UILitTangentToWorld(input, normalTS); + half3 color = UILitShade(input, col.rgb, _Specular.a * mask.r, _Shininess * mask.g, normalWS); + return UILitOutput(input, color, col.a); + } + ENDHLSL + } + } + + Fallback "UI/Lit/Detail" +} diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-RefractionDetail.shader.meta b/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-RefractionDetail.shader.meta new file mode 100644 index 00000000000..06c618ed543 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-RefractionDetail.shader.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 1fd71c6c564f4ac18fb6160bf1a8f234 +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + preprocessorOverride: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-Transparent.shader b/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-Transparent.shader new file mode 100644 index 00000000000..2928db28cc1 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-Transparent.shader @@ -0,0 +1,83 @@ +Shader "UI/Lit/Transparent" +{ + Properties + { + [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {} + _Color ("Tint", Color) = (1,1,1,1) + _Specular ("Specular Color", Color) = (0,0,0,0) + + _StencilComp ("Stencil Comparison", Float) = 8 + _Stencil ("Stencil ID", Float) = 0 + _StencilOp ("Stencil Operation", Float) = 0 + _StencilWriteMask ("Stencil Write Mask", Float) = 255 + _StencilReadMask ("Stencil Read Mask", Float) = 255 + + _ColorMask ("Color Mask", Float) = 15 + + [Toggle(UNITY_UI_ALPHACLIP)] _UseUIAlphaClip ("Use Alpha Clip", Float) = 0 + } + + SubShader + { + LOD 400 + + Tags + { + "Queue" = "Transparent" + "IgnoreProjector" = "True" + "RenderType" = "Transparent" + "PreviewType" = "Plane" + "CanUseSpriteAtlas" = "True" + "RenderPipeline" = "UniversalPipeline" + } + + Stencil + { + Ref [_Stencil] + Comp [_StencilComp] + Pass [_StencilOp] + ReadMask [_StencilReadMask] + WriteMask [_StencilWriteMask] + } + + Cull Off + ZWrite Off + ZTest [unity_GUIZTestMode] + Blend SrcAlpha OneMinusSrcAlpha + ColorMask [_ColorMask] + + Pass + { + Name "Default" + Tags { "LightMode" = "UniversalForward" } + + HLSLPROGRAM + #pragma target 3.0 + #pragma vertex UILitVertex + #pragma fragment Fragment + + #pragma multi_compile_local _ UNITY_UI_CLIP_RECT + #pragma multi_compile_local _ UNITY_UI_ALPHACLIP + #pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX + #pragma multi_compile_fragment _ _ADDITIONAL_LIGHTS + #pragma multi_compile_fragment _ _CLUSTER_LIGHT_LOOP + #pragma multi_compile_fragment _ _LIGHT_COOKIES + #pragma multi_compile _ _LIGHT_FALLOFF_QUADRATIC + #pragma multi_compile_instancing + + #include "Packages/com.unity.render-pipelines.universal/Shaders/UI/UILit.hlsl" + + half4 Fragment(UILitVaryings input) : SV_Target + { + UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input); + + half4 col = (SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, input.uv.xy) + _TextureSampleAdd) * input.color; + float3 normalWS = NormalizeNormalPerPixel(input.normalWS); + + half3 color = UILitShade(input, col.rgb, 0.0, 0.0, normalWS); + return UILitOutput(input, color, col.a); + } + ENDHLSL + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-Transparent.shader.meta b/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-Transparent.shader.meta new file mode 100644 index 00000000000..36762615dac --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Shaders/UI/UI-Lit-Transparent.shader.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 5271026d34254d68890a585e3c55aa14 +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + preprocessorOverride: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/UI/UILit.hlsl b/Packages/com.unity.render-pipelines.universal/Shaders/UI/UILit.hlsl new file mode 100644 index 00000000000..06db859541e --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Shaders/UI/UILit.hlsl @@ -0,0 +1,223 @@ +#ifndef UNIVERSAL_UI_LIT_INCLUDED +#define UNIVERSAL_UI_LIT_INCLUDED + +// Shared code for the Universal Render Pipeline "UI/Lit/*" shaders. +// Reproduces the per-pixel Phong lighting of the former Built-in Render Pipeline UI/Lit surface shaders. + +#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" +#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" +#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/DeclareOpaqueTexture.hlsl" + +TEXTURE2D(_MainTex); SAMPLER(sampler_MainTex); +TEXTURE2D(_MainBump); SAMPLER(sampler_MainBump); +TEXTURE2D(_DetailTex); SAMPLER(sampler_DetailTex); +TEXTURE2D(_DetailBump); SAMPLER(sampler_DetailBump); +TEXTURE2D(_Mask); SAMPLER(sampler_Mask); +TEXTURE2D(_DetailMask); SAMPLER(sampler_DetailMask); + +CBUFFER_START(UnityPerMaterial) + float4 _MainTex_ST; + float4 _MainBump_ST; + float4 _DetailTex_ST; + float4 _DetailBump_ST; + float4 _Mask_ST; + float4 _DetailMask_ST; + float4 _DetailTex_TexelSize; + float4 _DetailBump_TexelSize; + float4 _DetailMask_TexelSize; + half4 _Color; + half4 _Specular; + half _Shininess; + half _Strength; + half _Focus; +CBUFFER_END + +// Set by the Canvas system rather than by the material +half4 _TextureSampleAdd; +float4 _ClipRect; +int _UIVertexColorAlwaysGammaSpace; + +struct UILitAttributes +{ + float4 positionOS : POSITION; + half4 color : COLOR; + float2 uv0 : TEXCOORD0; + float2 uv1 : TEXCOORD1; + float3 normalOS : NORMAL; + float4 tangentOS : TANGENT; + UNITY_VERTEX_INPUT_INSTANCE_ID +}; + +struct UILitVaryings +{ + float4 positionCS : SV_POSITION; + half4 color : COLOR; + float4 uv : TEXCOORD0; // xy: _MainTex, zw: _MainBump + float4 detailUV : TEXCOORD1; // xy: _DetailTex, zw: _DetailBump + float4 maskUV : TEXCOORD2; // xy: _DetailMask, zw: object space position for the clip rect + float3 positionWS : TEXCOORD3; + float3 normalWS : TEXCOORD4; + float4 tangentWS : TEXCOORD5; + float4 screenPos : TEXCOORD6; +#ifdef _ADDITIONAL_LIGHTS_VERTEX + half3 vertexLighting : TEXCOORD7; +#endif + UNITY_VERTEX_OUTPUT_STEREO +}; + +half3 UIGammaToLinear(half3 value) +{ + half3 low = 0.0849710 * value - 0.000163029; + half3 high = value * (value * (value * 0.265885 + 0.736584) - 0.00980184) + 0.00319697; + + // We should be 0.5 away from any actual gamma value stored in an 8 bit channel + const half3 split = (half3)0.0725490; // Equals 18.5 / 255 + return (value < split) ? low : high; +} + +float UnityGet2DClipping(float2 position, float4 clipRect) +{ + float2 inside = step(clipRect.xy, position.xy) * step(position.xy, clipRect.zw); + return inside.x * inside.y; +} + +// Matches the Built-in UI/Lit refraction, which projected the object-space position rather than the clip-space one +// The Built-in GrabPass needed a flip where UVs start at the top, but the opaque texture follows the render texture convention on every API +float4 UILitRefractionCoords(float4 positionOS) +{ + return float4((positionOS.xy + positionOS.w) * 0.5, positionOS.zw); +} + +UILitVaryings UILitVertex(UILitAttributes input) +{ + UILitVaryings output = (UILitVaryings)0; + UNITY_SETUP_INSTANCE_ID(input); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output); + + VertexPositionInputs positionInputs = GetVertexPositionInputs(input.positionOS.xyz); + VertexNormalInputs normalInputs = GetVertexNormalInputs(input.normalOS, input.tangentOS); + + output.positionCS = positionInputs.positionCS; + output.positionWS = positionInputs.positionWS; + output.screenPos = UILitRefractionCoords(input.positionOS); + output.normalWS = normalInputs.normalWS; + output.tangentWS = float4(normalInputs.tangentWS, input.tangentOS.w * GetOddNegativeScale()); +#ifdef _ADDITIONAL_LIGHTS_VERTEX + output.vertexLighting = VertexLighting(positionInputs.positionWS, normalInputs.normalWS); +#endif + + half4 color = input.color; +#ifndef UNITY_COLORSPACE_GAMMA + if (_UIVertexColorAlwaysGammaSpace) + color.rgb = UIGammaToLinear(color.rgb); +#endif + output.color = color * _Color; + + output.uv.xy = TRANSFORM_TEX(input.uv0, _MainTex); + output.uv.zw = TRANSFORM_TEX(input.uv0, _MainBump); + output.detailUV.xy = TRANSFORM_TEX(input.uv1 * _DetailTex_TexelSize.xy, _DetailTex); + output.detailUV.zw = TRANSFORM_TEX(input.uv1 * _DetailBump_TexelSize.xy, _DetailBump); + output.maskUV.xy = TRANSFORM_TEX(input.uv1 * _DetailMask_TexelSize.xy, _DetailMask); + output.maskUV.zw = input.positionOS.xy; + return output; +} + +float3 UILitTangentToWorld(UILitVaryings input, half3 normalTS) +{ + float3 bitangentWS = input.tangentWS.w * cross(input.normalWS, input.tangentWS.xyz); + float3x3 tangentToWorld = float3x3(input.tangentWS.xyz, bitangentWS, input.normalWS); + return NormalizeNormalPerPixel(TransformTangentToWorld(normalTS, tangentToWorld)); +} + +half3 UILitPhong(half3 albedo, half specularIntensity, half gloss, float3 normalWS, float3 viewDirWS, Light light) +{ + half shininess = gloss * 250.0 + 4.0; + half reflectiveFactor = max(0.0, dot(-viewDirWS, reflect(light.direction, normalWS))); + half diffuseFactor = max(0.0, dot(normalWS, light.direction)); + half specularFactor = pow(reflectiveFactor, shininess) * specularIntensity; + + half3 color = (albedo * diffuseFactor + _Specular.rgb * specularFactor) * light.color; + return color * light.distanceAttenuation * light.shadowAttenuation; +} + +half3 UILitApplyRefraction(UILitVaryings input, half3 color, half3 normalTS, half amount) +{ + // Offset in screen texels like the Built-in GrabPass, since the opaque texture may be downsampled + float2 offset = normalTS.xy * _ScreenSize.zw * _Focus; + float4 proj = input.screenPos; + proj.xy = offset * proj.z + proj.xy; + return lerp(color, SampleSceneColor(proj.xy / proj.w), amount); +} + +// Applies cookies without the shadows and height fog that the full URP light getters add +Light UILitGetMainLight(float3 positionWS) +{ + Light light = GetMainLight(); + // unity_LightData is per-renderer data that overlay canvases never receive, so its culling flag is ignored + light.distanceAttenuation = 1.0; + light.color *= SampleMainLightCookie(positionWS); + return light; +} + +Light UILitGetAdditionalLight(uint i, float3 positionWS) +{ +#if USE_CLUSTER_LIGHT_LOOP + int perObjectLightIndex = i; +#else + int perObjectLightIndex = GetPerObjectLightIndex(i); +#endif + Light light = GetAdditionalPerObjectLight(perObjectLightIndex, positionWS); + light.color *= SampleAdditionalLightCookie(perObjectLightIndex, positionWS); + return light; +} + +half3 UILitShade(UILitVaryings input, half3 albedo, half specularIntensity, half gloss, float3 normalWS) +{ + float3 viewDirWS = GetWorldSpaceNormalizeViewDir(input.positionWS); + + // No ambient or light probe term is applied + // Light layers are not matched because canvas draws carry no rendering layer mask + half3 color = UILitPhong(albedo, specularIntensity, gloss, normalWS, viewDirWS, UILitGetMainLight(input.positionWS)); + +#if defined(_ADDITIONAL_LIGHTS) + InputData inputData = (InputData)0; + inputData.positionWS = input.positionWS; + inputData.normalWS = normalWS; + inputData.normalizedScreenSpaceUV = GetNormalizedScreenSpaceUV(input.positionCS); + + uint pixelLightCount = GetAdditionalLightsCount(); + +#if USE_CLUSTER_LIGHT_LOOP + [loop] for (uint lightIndex = 0; lightIndex < min(URP_FP_DIRECTIONAL_LIGHTS_COUNT, MAX_VISIBLE_LIGHTS); lightIndex++) + { + color += UILitPhong(albedo, specularIntensity, gloss, normalWS, viewDirWS, UILitGetAdditionalLight(lightIndex, input.positionWS)); + } +#endif + + LIGHT_LOOP_BEGIN(pixelLightCount) + color += UILitPhong(albedo, specularIntensity, gloss, normalWS, viewDirWS, UILitGetAdditionalLight(lightIndex, input.positionWS)); + LIGHT_LOOP_END +#endif + + // Per Vertex additional lights are diffuse only and use the interpolated vertex normal +#if defined(_ADDITIONAL_LIGHTS_VERTEX) + color += albedo * input.vertexLighting; +#endif + + return color; +} + +half4 UILitOutput(UILitVaryings input, half3 color, half alpha) +{ +#ifdef UNITY_UI_CLIP_RECT + alpha *= UnityGet2DClipping(input.maskUV.zw, _ClipRect); +#endif + +#ifdef UNITY_UI_ALPHACLIP + clip(alpha - 0.001); +#endif + + return half4(color, alpha); +} + +#endif // UNIVERSAL_UI_LIT_INCLUDED diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/UI/UILit.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Shaders/UI/UILit.hlsl.meta new file mode 100644 index 00000000000..34eb330d067 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Shaders/UI/UILit.hlsl.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 7d3a1f0c9b5e4d2a8c6f1e0b3a9d5c71 +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + preprocessorOverride: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Utils/ClusterDeferred.hlsl b/Packages/com.unity.render-pipelines.universal/Shaders/Utils/ClusterDeferred.hlsl index f8c9dc27310..7a53377506e 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/Utils/ClusterDeferred.hlsl +++ b/Packages/com.unity.render-pipelines.universal/Shaders/Utils/ClusterDeferred.hlsl @@ -48,21 +48,22 @@ Varyings VertexFullScreen(Attributes input) float4x4 _ScreenToWorld[2]; -half3 DeferredLightContribution(Light light, InputData inputData, GBufferData gBufferData) +URP_LIGHT_ACCUM3 DeferredLightContribution(Light light, InputData inputData, GBufferData gBufferData) { + UNITY_BRANCH if (LightLayersAvailable() && !IsMatchingLightLayer(light.layerMask, gBufferData.meshRenderingLayers)) - return half3(0.0, 0.0, 0.0); + return URP_LIGHT_ACCUM3(0.0, 0.0, 0.0); #if defined(_SIMPLELIT) { SurfaceData surfaceData = GBufferDataToSurfaceData(gBufferData); - half3 attenuatedLightColor = light.color * (light.distanceAttenuation * light.shadowAttenuation); - half3 diffuseColor = LightingLambert(attenuatedLightColor, light.direction, inputData.normalWS); + URP_LIGHT_ACCUM3 attenuatedLightColor = light.color * (light.distanceAttenuation * light.shadowAttenuation); + URP_LIGHT_ACCUM3 diffuseColor = LightingLambert(attenuatedLightColor, light.direction, inputData.normalWS); half smoothness = exp2(10 * surfaceData.smoothness + 1); - half3 specularColor = LightingSpecular(attenuatedLightColor, light.direction, inputData.normalWS, inputData.viewDirectionWS, half4(surfaceData.specular, 1), smoothness); + URP_LIGHT_ACCUM3 specularColor = LightingSpecular(attenuatedLightColor, light.direction, inputData.normalWS, inputData.viewDirectionWS, half4(surfaceData.specular, 1), smoothness); // TODO: if !defined(_SPECGLOSSMAP) && !defined(_SPECULAR_COLOR), force specularColor to 0 in gbuffer code - return half3(diffuseColor * surfaceData.albedo + specularColor); + return diffuseColor * surfaceData.albedo + specularColor; } #elif defined(_LIT) { @@ -74,7 +75,7 @@ half3 DeferredLightContribution(Light light, InputData inputData, GBufferData gB #endif BRDFData brdfData = GBufferDataToBRDFData(gBufferData); - return half3(LightingPhysicallyBased(brdfData, light, inputData.normalWS, inputData.viewDirectionWS, !materialSpecularHighlightsOff, false)); + return LightingPhysicallyBased(brdfData, light, inputData.normalWS, inputData.viewDirectionWS, !materialSpecularHighlightsOff, false); } #endif @@ -88,6 +89,9 @@ half4 DeferredShadingClustered(Varyings input) : SV_Target float2 screen_uv = (input.screenUV.xy / input.screenUV.z); + // Raster position, read before the foveated remap below + float2 positionSS = input.positionCS.xy; + #if defined(SUPPORTS_FOVEATED_RENDERING_NON_UNIFORM_RASTER) float2 undistorted_screen_uv = screen_uv; UNITY_BRANCH if (_FOVEATED_RENDERING_NON_UNIFORM_RASTER) @@ -110,14 +114,18 @@ half4 DeferredShadingClustered(Varyings input) : SV_Target float4 posWS = mul(_ScreenToWorld[SLICE_ARRAY_INDEX], float4(input.positionCS.xy, gBufferData.depth, 1.0)); posWS.xyz *= rcp(posWS.w); + half3 geometricNormalWS = half3(SafeNormalize(cross(ddy(posWS.xyz), ddx(posWS.xyz)))); + geometricNormalWS *= half(FastSign(dot(geometricNormalWS, GetWorldSpaceViewDir(posWS.xyz)))); InputData inputData = (InputData)0; inputData.preExposureMultiplier = GetPreExposureMultiplier(); inputData.positionWS = posWS.xyz; inputData.normalWS = gBufferData.normalWS; + inputData.geometricNormalWS = geometricNormalWS; inputData.viewDirectionWS = GetWorldSpaceNormalizeViewDir(posWS.xyz); inputData.normalizedScreenSpaceUV = GetNormalizedScreenSpaceUV(input.positionCS); + inputData.positionCS = float4(positionSS, input.positionCS.zw); AmbientOcclusionFactor aoFactor = GetScreenSpaceAmbientOcclusion(screen_uv, false); @@ -138,10 +146,9 @@ half4 DeferredShadingClustered(Varyings input) : SV_Target UNITY_BRANCH if (!materialReceiveShadowsOff) { float4 shadowCoord = float4(0, 0, 0, 0); - // The GBuffer carries no geometric normal, so the shading normal drives the receiver normal bias if (MainLightShadowsAvailable()) - shadowCoord = MainLightScreenShadowsAvailable() ? float4(screen_uv, 0.0, 1.0) : TransformWorldToShadowCoord(posWS.xyz, false, gBufferData.normalWS); - mainLight.shadowAttenuation = MainLightShadow(shadowCoord, posWS.xyz, gBufferData.shadowMask, _MainLightOcclusionProbes, !materialReceiveShadowsOff, false); + shadowCoord = MainLightScreenShadowsAvailable() ? float4(screen_uv, 0.0, 1.0) : TransformWorldToShadowCoord(posWS.xyz, false, inputData.geometricNormalWS); + mainLight.shadowAttenuation = MainLightShadow(shadowCoord, posWS.xyz, gBufferData.shadowMask, _MainLightOcclusionProbes, !materialReceiveShadowsOff, false, positionSS); } real3 cookieColor = SampleMainLightCookie(posWS.xyz); @@ -158,7 +165,7 @@ half4 DeferredShadingClustered(Varyings input) : SV_Target // We do additional directional lights last because otherwise FXC complains... uint pixelLightCount = GetAdditionalLightsCount(); LIGHT_LOOP_BEGIN(pixelLightCount) - Light light = GetAdditionalLight(lightIndex, inputData, gBufferData.shadowMask, aoFactor, !materialReceiveShadowsOff, false, gBufferData.normalWS); + Light light = GetAdditionalLight(lightIndex, inputData, gBufferData.shadowMask, aoFactor, !materialReceiveShadowsOff, false); UNITY_BRANCH if (materialReceiveShadowsOff) { @@ -171,7 +178,7 @@ half4 DeferredShadingClustered(Varyings input) : SV_Target UNITY_LOOP for (uint lightIndex = 0; lightIndex < min(URP_FP_DIRECTIONAL_LIGHTS_COUNT, MAX_VISIBLE_LIGHTS); lightIndex++) { CLUSTER_LIGHT_LOOP_SUBTRACTIVE_LIGHT_CHECK - Light light = GetAdditionalLight(lightIndex, inputData, gBufferData.shadowMask, aoFactor, !materialReceiveShadowsOff, false, gBufferData.normalWS); + Light light = GetAdditionalLight(lightIndex, inputData, gBufferData.shadowMask, aoFactor, !materialReceiveShadowsOff, false); UNITY_BRANCH if (materialReceiveShadowsOff) { diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Utils/ClusterDeferred.shader b/Packages/com.unity.render-pipelines.universal/Shaders/Utils/ClusterDeferred.shader index 8fc3ddb164e..95d75ee5e64 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/Utils/ClusterDeferred.shader +++ b/Packages/com.unity.render-pipelines.universal/Shaders/Utils/ClusterDeferred.shader @@ -58,9 +58,11 @@ Shader "Hidden/Universal Render Pipeline/ClusterDeferred" // ------------------------------------- // Universal Pipeline keywords #pragma multi_compile_fragment _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile_fragment _ _SHADOW_RECEIVER_NORMAL_BIAS #pragma multi_compile_fragment _ _LIGHT_FALLOFF_QUADRATIC #pragma multi_compile_fragment _ _ADDITIONAL_LIGHT_SHADOWS #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH + #pragma multi_compile_fragment _ _SHADOWS_PCSS #pragma multi_compile_fragment _ LIGHTMAP_SHADOW_MIXING #pragma multi_compile_fragment _ SHADOWS_SHADOWMASK #pragma multi_compile_fragment _ _GBUFFER_NORMALS_OCT @@ -124,9 +126,11 @@ Shader "Hidden/Universal Render Pipeline/ClusterDeferred" // ------------------------------------- // Universal Pipeline keywords #pragma multi_compile_fragment _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile_fragment _ _SHADOW_RECEIVER_NORMAL_BIAS #pragma multi_compile_fragment _ _LIGHT_FALLOFF_QUADRATIC #pragma multi_compile_fragment _ _ADDITIONAL_LIGHT_SHADOWS #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH + #pragma multi_compile_fragment _ _SHADOWS_PCSS #pragma multi_compile_fragment _ LIGHTMAP_SHADOW_MIXING #pragma multi_compile_fragment _ SHADOWS_SHADOWMASK #pragma multi_compile_fragment _ _GBUFFER_NORMALS_OCT diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Utils/ComputeScreenSpaceReflection.shader b/Packages/com.unity.render-pipelines.universal/Shaders/Utils/ComputeScreenSpaceReflection.shader index 251bc054343..2e2e047f584 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/Utils/ComputeScreenSpaceReflection.shader +++ b/Packages/com.unity.render-pipelines.universal/Shaders/Utils/ComputeScreenSpaceReflection.shader @@ -99,5 +99,16 @@ Shader "Hidden/Universal Render Pipeline/ComputeScreenSpaceReflection" ENDHLSL } + Pass + { + Name "SSR_Debug" + + HLSLPROGRAM + #pragma vertex Vert + #pragma fragment SSRDebug + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/ComputeScreenSpaceReflection.hlsl" + ENDHLSL + } + } } diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Utils/GTAODepthPrefilter.compute b/Packages/com.unity.render-pipelines.universal/Shaders/Utils/GTAODepthPrefilter.compute index cdcc5022b89..168c5f2eb2b 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/Utils/GTAODepthPrefilter.compute +++ b/Packages/com.unity.render-pipelines.universal/Shaders/Utils/GTAODepthPrefilter.compute @@ -16,7 +16,7 @@ TEXTURE2D_X_FLOAT(_CameraDepthTexture); // One packed surface for every MIP, so a single UAV reaches all of them and both XR slices. RW_TEXTURE2D_X(float, _GTAODepthPyramid); -float4 _ZBufferParams; // the engine's per camera global, declared here because URP's headers are not included +float4 _ZBufferParams; // set by GTAOPass float4 _GTAOPrefilterSize; // xy = MIP 0 viewport size, zw = max source depth coordinate float4 _GTAOPrefilterSourceSize; // xy = source depth allocation size, zw = its reciprocal float4 _GTAOPrefilterFalloff; // x = falloff multiplier, y = falloff addend, z = max storable depth, w = unused diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Utils/ScreenSpaceShadows.shader b/Packages/com.unity.render-pipelines.universal/Shaders/Utils/ScreenSpaceShadows.shader index d919068c008..c0a5a902c0b 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/Utils/ScreenSpaceShadows.shader +++ b/Packages/com.unity.render-pipelines.universal/Shaders/Utils/ScreenSpaceShadows.shader @@ -33,7 +33,7 @@ Shader "Hidden/Universal Render Pipeline/ScreenSpaceShadows" float4 coords = TransformWorldToShadowCoord(wpos, false); // Screenspace shadowmap is only used for directional lights which use orthogonal projection. - half realtimeShadow = SampleMainLightRealtimeShadow(coords, false); + half realtimeShadow = SampleMainLightRealtimeShadow(coords, wpos, false, input.positionCS.xy); return realtimeShadow; } @@ -50,6 +50,7 @@ Shader "Hidden/Universal Render Pipeline/ScreenSpaceShadows" HLSLPROGRAM #pragma multi_compile _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH + #pragma multi_compile_fragment _ _SHADOWS_PCSS #pragma vertex Vert #pragma fragment Fragment diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Utils/StencilDeferred.hlsl b/Packages/com.unity.render-pipelines.universal/Shaders/Utils/StencilDeferred.hlsl index aa1f2545971..88f7028c320 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/Utils/StencilDeferred.hlsl +++ b/Packages/com.unity.render-pipelines.universal/Shaders/Utils/StencilDeferred.hlsl @@ -85,7 +85,7 @@ Varyings Vertex(Attributes input) float4x4 _ScreenToWorld[2]; float3 _LightPosWS; -half3 _LightColor; +float3 _LightColor; half4 _LightAttenuation; // .xy are used by DistanceAttenuation - .zw are used by AngleAttenuation *for SpotLights) half3 _LightDirection; // directional/spotLights support half4 _LightOcclusionProbInfo; @@ -113,7 +113,7 @@ struct PunctualLightData uint layerMask; // Optional light layer mask }; -Light UnityLightFromPunctualLightDataAndWorldSpacePosition(PunctualLightData punctualLightData, float3 positionWS, half4 shadowMask, int shadowLightIndex, bool materialFlagReceiveShadowsOff, half3 normalWS = half3(0.0, 0.0, 0.0)) +Light UnityLightFromPunctualLightDataAndWorldSpacePosition(PunctualLightData punctualLightData, float3 positionWS, half4 shadowMask, int shadowLightIndex, bool materialFlagReceiveShadowsOff, half3 normalWS = half3(0.0, 0.0, 0.0), float2 positionSS = INVALID_SHADOW_SCREEN_POS) { // Keep in sync with GetAdditionalPerObjectLight in Lighting.hlsl @@ -148,7 +148,7 @@ Light UnityLightFromPunctualLightDataAndWorldSpacePosition(PunctualLightData pun light.shadowAttenuation = 1.0; else { - light.shadowAttenuation = AdditionalLightShadow(shadowLightIndex, positionWS, lightDirection, shadowMask, punctualLightData.occlusionProbeInfo, !materialFlagReceiveShadowsOff, normalWS); + light.shadowAttenuation = AdditionalLightShadow(shadowLightIndex, positionWS, lightDirection, shadowMask, punctualLightData.occlusionProbeInfo, !materialFlagReceiveShadowsOff, normalWS, positionSS); } light.layerMask = punctualLightData.layerMask; @@ -182,7 +182,7 @@ half4 SampleAdditionalLightCookieDeferred(int perObjectLightIndex, float3 sample return cookieColor; } -Light GetStencilLight(float3 posWS, float2 screen_uv, half4 shadowMask, uint materialFlags, half3 normalWS) +Light GetStencilLight(float3 posWS, float2 screen_uv, half4 shadowMask, uint materialFlags, half3 normalWS, float2 positionSS) { Light unityLight; @@ -202,7 +202,7 @@ Light GetStencilLight(float3 posWS, float2 screen_uv, half4 shadowMask, uint mat if (MainLightShadowsAvailable()) shadowCoord = MainLightScreenShadowsAvailable() ? float4(screen_uv, 0.0, 1.0) : TransformWorldToShadowCoord(posWS.xyz, false, normalWS); - unityLight.shadowAttenuation = MainLightShadow(shadowCoord, posWS.xyz, shadowMask, _MainLightOcclusionProbes, !materialReceiveShadowsOff, false); + unityLight.shadowAttenuation = MainLightShadow(shadowCoord, posWS.xyz, shadowMask, _MainLightOcclusionProbes, !materialReceiveShadowsOff, false, positionSS); } real3 cookieColor = SampleMainLightCookie(posWS); @@ -218,7 +218,7 @@ Light GetStencilLight(float3 posWS, float2 screen_uv, half4 shadowMask, uint mat if (!materialReceiveShadowsOff) { - unityLight.shadowAttenuation = AdditionalLightShadow(_ShadowLightIndex, posWS.xyz, _LightDirection, shadowMask, _LightOcclusionProbInfo, !materialReceiveShadowsOff, normalWS); + unityLight.shadowAttenuation = AdditionalLightShadow(_ShadowLightIndex, posWS.xyz, _LightDirection, shadowMask, _LightOcclusionProbInfo, !materialReceiveShadowsOff, normalWS, positionSS); } // Enable/disable is done toggling the keyword _LIGHT_COOKIES, but we could do a "static if" instead if required. @@ -239,7 +239,7 @@ Light GetStencilLight(float3 posWS, float2 screen_uv, half4 shadowMask, uint mat light.occlusionProbeInfo = _LightOcclusionProbInfo; light.flags = _LightFlags; light.layerMask = lightLayerMask; - unityLight = UnityLightFromPunctualLightDataAndWorldSpacePosition(light, posWS.xyz, shadowMask, _ShadowLightIndex, materialReceiveShadowsOff, normalWS); + unityLight = UnityLightFromPunctualLightDataAndWorldSpacePosition(light, posWS.xyz, shadowMask, _ShadowLightIndex, materialReceiveShadowsOff, normalWS, positionSS); // Enable/disable is done toggling the keyword _LIGHT_COOKIES, but we could do a "static if" instead if required. // if(_CookieLightIndex >= 0) @@ -259,6 +259,9 @@ half4 DeferredShading(Varyings input) : SV_Target float2 screen_uv = (input.screenUV.xy / input.screenUV.z); + // Raster position, read before the foveated remap below + float2 positionSS = input.positionCS.xy; + #if defined(SUPPORTS_FOVEATED_RENDERING_NON_UNIFORM_RASTER) float2 undistorted_screen_uv = screen_uv; UNITY_BRANCH if (_FOVEATED_RENDERING_NON_UNIFORM_RASTER) @@ -272,12 +275,6 @@ half4 DeferredShading(Varyings input) : SV_Target URP_LIGHT_ACCUM3 color = 0.0; half alpha = 1.0; - #if defined(GBUFFER_FEATURE_SHADOWMASK) - // If both lights and geometry are static, then no realtime lighting to perform for this combination. - [branch] if ((_LightFlags & gBufferData.materialFlags) == kMaterialFlagSubtractiveMixedLighting) - return half4(color, alpha); // Cannot discard because stencil must be updated. - #endif - #if defined(SUPPORTS_FOVEATED_RENDERING_NON_UNIFORM_RASTER) UNITY_BRANCH if (_FOVEATED_RENDERING_NON_UNIFORM_RASTER) { @@ -292,9 +289,16 @@ half4 DeferredShading(Varyings input) : SV_Target #endif float4 posWS = mul(_ScreenToWorld[eyeIndex], float4(input.positionCS.xy, gBufferData.depth, 1.0)); posWS.xyz *= rcp(posWS.w); + half3 geometricNormalWS = half3(SafeNormalize(cross(ddy(posWS.xyz), ddx(posWS.xyz)))); + geometricNormalWS *= half(FastSign(dot(geometricNormalWS, GetWorldSpaceViewDir(posWS.xyz)))); + + #if defined(GBUFFER_FEATURE_SHADOWMASK) + // If both lights and geometry are static, then no realtime lighting to perform for this combination. + [branch] if ((_LightFlags & gBufferData.materialFlags) == kMaterialFlagSubtractiveMixedLighting) + return half4(color, alpha); // Cannot discard because stencil must be updated. + #endif - // The GBuffer carries no geometric normal, so the shading normal drives the receiver normal bias - Light unityLight = GetStencilLight(posWS.xyz, screen_uv, gBufferData.shadowMask, gBufferData.materialFlags, gBufferData.normalWS); + Light unityLight = GetStencilLight(posWS.xyz, screen_uv, gBufferData.shadowMask, gBufferData.materialFlags, geometricNormalWS, positionSS); #if defined(GBUFFER_FEATURE_RENDERING_LAYERS) [branch] if (!IsMatchingLightLayer(unityLight.layerMask, gBufferData.meshRenderingLayers)) @@ -332,10 +336,10 @@ half4 DeferredShading(Varyings input) : SV_Target color = LightingPhysicallyBased(brdfData, unityLight, inputData.normalWS, inputData.viewDirectionWS, !materialSpecularHighlightsOff, false); #elif defined(_SIMPLELIT) SurfaceData surfaceData = GBufferDataToSurfaceData(gBufferData); - half3 attenuatedLightColor = unityLight.color * (unityLight.distanceAttenuation * unityLight.shadowAttenuation); - half3 diffuseColor = LightingLambert(attenuatedLightColor, unityLight.direction, inputData.normalWS); + URP_LIGHT_ACCUM3 attenuatedLightColor = unityLight.color * (unityLight.distanceAttenuation * unityLight.shadowAttenuation); + URP_LIGHT_ACCUM3 diffuseColor = LightingLambert(attenuatedLightColor, unityLight.direction, inputData.normalWS); half smoothness = exp2(10 * surfaceData.smoothness + 1); - half3 specularColor = LightingSpecular(attenuatedLightColor, unityLight.direction, inputData.normalWS, inputData.viewDirectionWS, half4(surfaceData.specular, 1), smoothness); + URP_LIGHT_ACCUM3 specularColor = LightingSpecular(attenuatedLightColor, unityLight.direction, inputData.normalWS, inputData.viewDirectionWS, half4(surfaceData.specular, 1), smoothness); // TODO: if !defined(_SPECGLOSSMAP) && !defined(_SPECULAR_COLOR), force specularColor to 0 in gbuffer code color = diffuseColor * surfaceData.albedo + specularColor; diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Utils/StencilDeferred.shader b/Packages/com.unity.render-pipelines.universal/Shaders/Utils/StencilDeferred.shader index a2e90452845..4e49d67ee6a 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/Utils/StencilDeferred.shader +++ b/Packages/com.unity.render-pipelines.universal/Shaders/Utils/StencilDeferred.shader @@ -128,7 +128,9 @@ Shader "Hidden/Universal Render Pipeline/StencilDeferred" #pragma multi_compile _POINT _SPOT #pragma multi_compile_fragment _ _LIGHT_FALLOFF_QUADRATIC #pragma multi_compile_fragment _ _ADDITIONAL_LIGHT_SHADOWS + #pragma multi_compile_fragment _ _SHADOW_RECEIVER_NORMAL_BIAS #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH + #pragma multi_compile_fragment _ _SHADOWS_PCSS #pragma multi_compile_fragment _ LIGHTMAP_SHADOW_MIXING #pragma multi_compile_fragment _ SHADOWS_SHADOWMASK #pragma multi_compile_fragment _ _GBUFFER_NORMALS_OCT @@ -194,7 +196,9 @@ Shader "Hidden/Universal Render Pipeline/StencilDeferred" #pragma multi_compile _POINT _SPOT #pragma multi_compile_fragment _ _LIGHT_FALLOFF_QUADRATIC #pragma multi_compile_fragment _ _ADDITIONAL_LIGHT_SHADOWS + #pragma multi_compile_fragment _ _SHADOW_RECEIVER_NORMAL_BIAS #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH + #pragma multi_compile_fragment _ _SHADOWS_PCSS #pragma multi_compile_fragment _ LIGHTMAP_SHADOW_MIXING #pragma multi_compile_fragment _ SHADOWS_SHADOWMASK #pragma multi_compile_fragment _ _GBUFFER_NORMALS_OCT @@ -258,9 +262,11 @@ Shader "Hidden/Universal Render Pipeline/StencilDeferred" // ------------------------------------- // Universal Pipeline keywords #pragma multi_compile_fragment _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile_fragment _ _SHADOW_RECEIVER_NORMAL_BIAS #pragma multi_compile_fragment _ _DEFERRED_MAIN_LIGHT #pragma multi_compile_fragment _ _DEFERRED_FIRST_LIGHT #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH + #pragma multi_compile_fragment _ _SHADOWS_PCSS #pragma multi_compile_fragment _ LIGHTMAP_SHADOW_MIXING #pragma multi_compile_fragment _ SHADOWS_SHADOWMASK #pragma multi_compile_fragment _ _GBUFFER_NORMALS_OCT @@ -325,9 +331,11 @@ Shader "Hidden/Universal Render Pipeline/StencilDeferred" // ------------------------------------- // Universal Pipeline keywords #pragma multi_compile_fragment _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile_fragment _ _SHADOW_RECEIVER_NORMAL_BIAS #pragma multi_compile_fragment _ _DEFERRED_MAIN_LIGHT #pragma multi_compile_fragment _ _DEFERRED_FIRST_LIGHT #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH + #pragma multi_compile_fragment _ _SHADOWS_PCSS #pragma multi_compile_fragment _ LIGHTMAP_SHADOW_MIXING #pragma multi_compile_fragment _ SHADOWS_SHADOWMASK #pragma multi_compile_fragment _ _GBUFFER_NORMALS_OCT diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/XR/XRMotionVector.shader b/Packages/com.unity.render-pipelines.universal/Shaders/XR/XRMotionVector.shader index 348b2899193..55a022a4868 100644 --- a/Packages/com.unity.render-pipelines.universal/Shaders/XR/XRMotionVector.shader +++ b/Packages/com.unity.render-pipelines.universal/Shaders/XR/XRMotionVector.shader @@ -110,6 +110,7 @@ Shader "Hidden/Universal Render Pipeline/XR/XRMotionVector" HLSLPROGRAM #pragma target 3.5 + #pragma target 4.5 _SUBSAMPLE_DEPTH #pragma multi_compile_fragment _ _SUBSAMPLE_DEPTH #pragma vertex Vert @@ -228,6 +229,8 @@ Shader "Hidden/Universal Render Pipeline/XR/XRMotionVector" HLSLPROGRAM #pragma target 3.5 + #pragma target 4.5 _QUADVIEW_INNER_DEPTH + #pragma multi_compile_fragment _ _QUADVIEW_INNER_DEPTH #pragma vertex Vert #pragma fragment Frag @@ -242,11 +245,15 @@ Shader "Hidden/Universal Render Pipeline/XR/XRMotionVector" float4 _QuadViewUVScales; // inner-to-outer UV scale, xy = left eye, zw = right eye float4 _QuadViewUVOffsets; // inner-to-outer UV offset (curr), xy = left eye, zw = right eye float4 _QuadViewPrevUVOffsets; // inner-to-outer UV offset (prev), xy = left eye, zw = right eye + float2 _XRDepthTextureUVScale; + + // Outer depth is treated as a different surface when it is farther than inner depth by more than this fraction + #define QUADVIEW_DEPTH_RELATIVE_TOLERANCE 0.02 TEXTURE2D_X(_QuadViewMVTex); + TEXTURE2D_X(_QuadViewOuterDepthTex); SAMPLER(s_point_clamp_sampler); TEXTURE2D_X(_XRDepthTexture); - SAMPLER(sampler_XRDepthTexture); // ------------------------------------- // Structs @@ -259,7 +266,8 @@ Shader "Hidden/Universal Render Pipeline/XR/XRMotionVector" struct Varyings { float4 position : SV_POSITION; - float2 uv : TEXCOORD0; + float4 posCS : TEXCOORD0; + float2 uv : TEXCOORD1; UNITY_VERTEX_OUTPUT_STEREO }; @@ -271,10 +279,42 @@ Shader "Hidden/Universal Render Pipeline/XR/XRMotionVector" UNITY_SETUP_INSTANCE_ID(input); UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output); output.position = GetFullScreenTriangleVertexPosition(input.vertexID, 1 - UNITY_NEAR_CLIP_VALUE); + output.posCS = output.position; output.uv = GetFullScreenTriangleTexCoord(input.vertexID); return output; } + // ------------------------------------- + // Helpers + #if _QUADVIEW_INNER_DEPTH + // Same camera motion reconstruction as Pass 1 + float4 ComputeCameraMotion(float2 posCSxy, float depth) + { + float3 posWS = ComputeWorldSpacePosition(float4(posCSxy, depth, 1.0), UNITY_MATRIX_I_VP); + + float4 posCS = mul(_NonJitteredViewProjMatrix, float4(posWS, 1.0)); + float4 prevPosCS = mul(_PrevViewProjMatrix, float4(posWS, 1.0)); + + float3 velocity = posCS.xyz * rcp(posCS.w) - prevPosCS.xyz * rcp(prevPosCS.w); + + #if UNITY_UV_STARTS_AT_TOP + velocity.y = velocity.y * _SpaceWarpNDCModifier; + #endif + + return float4(velocity.xyz, 0); + } + + // Reversed-Z depth is roughly near / z, so a relative raw difference approximates a relative linear-depth difference + bool IsOuterSurfaceBehind(float outerDepth, float innerDepth) + { + #if !UNITY_REVERSED_Z + outerDepth = 1.0 - outerDepth; + innerDepth = 1.0 - innerDepth; + #endif + return innerDepth - outerDepth > QUADVIEW_DEPTH_RELATIVE_TOLERANCE * innerDepth; + } + #endif + // ------------------------------------- // Fragment float4 Frag(Varyings input, out float outDepth : SV_Depth) : SV_Target @@ -293,7 +333,41 @@ Shader "Hidden/Universal Render Pipeline/XR/XRMotionVector" input.uv.y * uvScale.y + (1.0 - uvScale.y - uvOffset.y) ); - outDepth = SAMPLE_TEXTURE2D_X(_XRDepthTexture, sampler_XRDepthTexture, outerUV).x; + float outerDepth = SAMPLE_TEXTURE2D_X(_QuadViewOuterDepthTex, s_point_clamp_sampler, outerUV).x; + + #if _QUADVIEW_INNER_DEPTH + // The outer pass split-culls objects fully inside the inset, so outer MVs can belong to surfaces those objects hide. + // Where the outer surface is behind the inner one, rebuild camera motion from inner depth instead. + float innerDepth = SAMPLE_TEXTURE2D_X(_XRDepthTexture, s_point_clamp_sampler, input.uv * _XRDepthTextureUVScale).x; + + // Test against the nearest of the 2x2 outer texels around the sample so a sloped surface spanning them is not rejected + #if SHADER_TARGET >= 45 && defined(PLATFORM_SUPPORT_GATHER) + float4 outerDepth4 = GATHER_RED_TEXTURE2D_X(_QuadViewOuterDepthTex, s_point_clamp_sampler, outerUV); + #if UNITY_REVERSED_Z + float outerNearestDepth = max(max(outerDepth4.x, outerDepth4.y), max(outerDepth4.z, outerDepth4.w)); + #else + float outerNearestDepth = min(min(outerDepth4.x, outerDepth4.y), min(outerDepth4.z, outerDepth4.w)); + #endif + #else + float outerNearestDepth = outerDepth; + #endif + + if (IsOuterSurfaceBehind(outerNearestDepth, innerDepth)) + { + outDepth = innerDepth; + return ComputeCameraMotion(input.posCS.xy, innerDepth); + } + + // Keep the closer surface: outer depth includes transparent MV draws that inner depth does not have + #if UNITY_REVERSED_Z + outDepth = max(outerDepth, innerDepth); + #else + outDepth = min(outerDepth, innerDepth); + #endif + #else + // Without copyDepth the outer MV pass draws every object unculled, so outer data is complete + outDepth = outerDepth; + #endif float4 outerMV = SAMPLE_TEXTURE2D_X(_QuadViewMVTex, s_point_clamp_sampler, outerUV); diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/BufferCaptureTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/BufferCaptureTests.cs new file mode 100644 index 00000000000..00b76bd06a9 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/BufferCaptureTests.cs @@ -0,0 +1,368 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework; +using UnityEditor.SceneManagement; +using UnityEngine; +using UnityEngine.SceneManagement; + +namespace UnityEditor.Rendering.Universal.Tests +{ + class BufferCaptureParseTargetsTests + { + static string[] Names(List targets) => targets.Select(t => t.target.name).ToArray(); + + [TestCase(null)] + [TestCase("")] + [TestCase(" ")] + public void ParseTargets_NoBuffers_DefaultsToNamedColor(string buffers) + { + var targets = BufferCapture.ParseTargets(buffers); + + Assert.That(Names(targets), Is.EqualTo(new[] { "color" })); + Assert.IsTrue(targets[0].named); + } + + [Test] + public void ParseTargets_TrimsAndIgnoresCase() + { + var targets = BufferCapture.ParseTargets(" Depth , ALBEDO "); + + Assert.That(Names(targets), Is.EqualTo(new[] { "depth", "albedo" })); + Assert.IsTrue(targets.All(t => t.named)); + } + + [Test] + public void ParseTargets_IgnoresEmptyEntries() + { + var targets = BufferCapture.ParseTargets("color,,depth,"); + + Assert.That(Names(targets), Is.EqualTo(new[] { "color", "depth" })); + } + + [Test] + public void ParseTargets_RemovesDuplicates() + { + var targets = BufferCapture.ParseTargets("depth,color,depth"); + + Assert.That(Names(targets), Is.EqualTo(new[] { "depth", "color" })); + } + + [Test] + public void ParseTargets_All_ReturnsEveryTargetUnnamed() + { + var targets = BufferCapture.ParseTargets(BufferCapture.allTargets); + + Assert.That(Names(targets), Is.EqualTo(UniversalBufferCaptureTargets.all.Select(t => t.name).ToArray())); + Assert.IsTrue(targets.All(t => !t.named)); + } + + [TestCase("all,depth")] + [TestCase("depth,all")] + public void ParseTargets_AllWithNamedTarget_OnlyNamedTargetIsNamed(string buffers) + { + var targets = BufferCapture.ParseTargets(buffers); + + Assert.AreEqual(UniversalBufferCaptureTargets.all.Length, targets.Count); + foreach (var target in targets) + Assert.AreEqual(target.target.name == "depth", target.named, target.target.name); + } + + [Test] + public void ParseTargets_UnknownBuffer_ThrowsAndListsValidBuffers() + { + var exception = Assert.Throws(() => BufferCapture.ParseTargets("color,nonexistent")); + + StringAssert.Contains("'nonexistent'", exception.Message); + foreach (var target in UniversalBufferCaptureTargets.all) + StringAssert.Contains(target.name, exception.Message); + } + } + + class BufferCaptureOutputSizeTests + { + static Vector2Int GetOutputSize(int cameraWidth, int cameraHeight, bool squareOutput, int width = 0, int height = 0) + { + BufferCapture.GetOutputSize(cameraWidth, cameraHeight, squareOutput, width, height, out var w, out var h); + return new Vector2Int(w, h); + } + + [Test] + public void GetOutputSize_NoSize_UsesCameraSize() + { + Assert.AreEqual(new Vector2Int(800, 600), GetOutputSize(800, 600, false)); + } + + [Test] + public void GetOutputSize_ExplicitSize_OverridesCameraSize() + { + Assert.AreEqual(new Vector2Int(320, 200), GetOutputSize(800, 600, false, 320, 200)); + } + + [Test] + public void GetOutputSize_SquareOutput_IgnoresCameraAspect() + { + Assert.AreEqual(new Vector2Int(1024, 1024), GetOutputSize(800, 600, true)); + Assert.AreEqual(new Vector2Int(512, 512), GetOutputSize(800, 600, true, 512)); + Assert.AreEqual(new Vector2Int(512, 256), GetOutputSize(800, 600, true, 512, 256)); + } + + [TestCase(0, 0)] + [TestCase(1, 600)] + [TestCase(800, 1)] + public void GetOutputSize_DegenerateCameraSize_UsesFallback(int cameraWidth, int cameraHeight) + { + Assert.AreEqual(new Vector2Int(1920, 1080), GetOutputSize(cameraWidth, cameraHeight, false)); + } + + [Test] + public void GetOutputSize_OversizedOutput_ClampsLongestEdgeAndKeepsAspect() + { + Assert.AreEqual(new Vector2Int(8192, 2048), GetOutputSize(16384, 4096, false)); + Assert.AreEqual(new Vector2Int(41, 8192), GetOutputSize(100, 20000, false)); + Assert.AreEqual(new Vector2Int(8192, 8192), GetOutputSize(800, 600, true, 10000, 10000)); + } + } + + class BufferCaptureObjectIdImageTests + { + static readonly Color32 k_Background = new Color32(0, 0, 0, 255); + static readonly Color32 k_Unresolved = new Color32(255, 255, 255, 255); + + readonly List m_Objects = new List(); + + [TearDown] + public void TearDown() + { + foreach (var obj in m_Objects) + { + if (obj != null) + UnityEngine.Object.DestroyImmediate(obj); + } + m_Objects.Clear(); + } + + GameObject CreateGameObject(string name, Transform parent = null) + { + var go = new GameObject(name) { hideFlags = HideFlags.HideAndDontSave }; + go.transform.SetParent(parent, false); + m_Objects.Add(go); + return go; + } + + Material CreateMaterial(string name) + { + var shader = Shader.Find("Universal Render Pipeline/Unlit"); + Assert.IsNotNull(shader, "The URP Unlit shader was not found."); + var material = new Material(shader) { name = name, hideFlags = HideFlags.HideAndDontSave }; + m_Objects.Add(material); + return material; + } + + // Inverse of ObjectIdResult.DecodeIdFromColor + static Color32 EncodeId(int id) => new Color32((byte)id, (byte)(id >> 8), (byte)(id >> 16), (byte)(id >> 24)); + + static Color32[] EncodeIds(params int[] ids) => ids.Select(EncodeId).ToArray(); + + static string ToHex(Color32 color) => "#" + ColorUtility.ToHtmlStringRGB(color); + + [Test] + public void BuildObjectIdImage_ReportsPixelCountsBoundsAndCoverage() + { + var a = CreateGameObject("A"); + var b = CreateGameObject("B"); + var idToObject = new UnityEngine.Object[] { null, a, b }; + + // 3x2 texture, bottom row first: A A bg / B unresolved A + var ids = EncodeIds(1, 1, 0, 2, 99, 1); + var mapping = BufferCapture.BuildObjectIdImage(ids, 3, 2, idToObject, out _); + + Assert.AreEqual(3, mapping.width); + Assert.AreEqual(2, mapping.height); + Assert.AreEqual(1, mapping.unresolvedPixelCount); + Assert.AreEqual(2, mapping.objects.Length); + + var entryA = mapping.objects[0]; + Assert.AreEqual("A", entryA.name); + Assert.AreEqual(3, entryA.pixelCount); + Assert.AreEqual(0.5f, entryA.coverage, 1e-6f); + Assert.AreEqual(0, entryA.bounds.xMin); + Assert.AreEqual(0, entryA.bounds.yMin); + Assert.AreEqual(2, entryA.bounds.xMax); + Assert.AreEqual(1, entryA.bounds.yMax); + + var entryB = mapping.objects[1]; + Assert.AreEqual("B", entryB.name); + Assert.AreEqual(1, entryB.pixelCount); + Assert.AreEqual(1f / 6f, entryB.coverage, 1e-6f); + Assert.AreEqual(0, entryB.bounds.xMin); + Assert.AreEqual(0, entryB.bounds.yMin); + Assert.AreEqual(0, entryB.bounds.xMax); + Assert.AreEqual(0, entryB.bounds.yMax); + } + + [Test] + public void BuildObjectIdImage_ColorsPixelsByObject() + { + var a = CreateGameObject("A"); + var b = CreateGameObject("B"); + var idToObject = new UnityEngine.Object[] { null, a, b }; + + var ids = EncodeIds(1, 1, 0, 2, 99, 1); + var mapping = BufferCapture.BuildObjectIdImage(ids, 3, 2, idToObject, out var colored); + + Assert.AreEqual(ids.Length, colored.Length); + Assert.AreEqual(k_Background, colored[2]); + Assert.AreEqual(k_Unresolved, colored[4]); + Assert.AreEqual(colored[0], colored[1]); + Assert.AreEqual(colored[0], colored[5]); + Assert.AreNotEqual(colored[0], colored[3]); + Assert.AreEqual(ToHex(colored[0]), mapping.objects[0].color); + Assert.AreEqual(ToHex(colored[3]), mapping.objects[1].color); + Assert.AreEqual(ToHex(k_Background), mapping.background); + } + + [Test] + public void BuildObjectIdImage_NullMappingEntry_CountsAsUnresolved() + { + var a = CreateGameObject("A"); + var idToObject = new UnityEngine.Object[] { null, a, null }; + + var mapping = BufferCapture.BuildObjectIdImage(EncodeIds(1, 2), 2, 1, idToObject, out var colored); + + Assert.AreEqual(1, mapping.unresolvedPixelCount); + Assert.AreEqual(1, mapping.objects.Length); + Assert.AreEqual(k_Unresolved, colored[1]); + } + + [Test] + public void BuildObjectIdImage_HighIdBytes_DecodeToTheRightObject() + { + const int k_HighId = 0x010203; + var a = CreateGameObject("A"); + var idToObject = new UnityEngine.Object[k_HighId + 1]; + idToObject[k_HighId] = a; + + var mapping = BufferCapture.BuildObjectIdImage(EncodeIds(k_HighId), 1, 1, idToObject, out _); + + Assert.AreEqual(0, mapping.unresolvedPixelCount); + Assert.AreEqual("A", mapping.objects.Single().name); + } + + [Test] + public void BuildObjectIdImage_SeveralIdsForOneObject_MergeIntoOneEntry() + { + var renderer = CreateGameObject("Multi").AddComponent(); + var idToObject = new UnityEngine.Object[] { null, renderer, renderer }; + + var mapping = BufferCapture.BuildObjectIdImage(EncodeIds(1, 2, 2), 3, 1, idToObject, out var colored); + + Assert.AreEqual(3, mapping.objects.Single().pixelCount); + Assert.AreEqual(colored[0], colored[1]); + Assert.AreEqual(colored[0], colored[2]); + } + + [Test] + public void BuildObjectIdImage_ReportsHierarchyPathAndType() + { + var parent = CreateGameObject("Parent"); + var renderer = CreateGameObject("Child", parent.transform).AddComponent(); + var idToObject = new UnityEngine.Object[] { null, renderer }; + + var entry = BufferCapture.BuildObjectIdImage(EncodeIds(1), 1, 1, idToObject, out _).objects.Single(); + + Assert.AreEqual("Child", entry.name); + Assert.AreEqual("Parent/Child", entry.path); + Assert.AreEqual(nameof(MeshRenderer), entry.type); + } + + [Test] + public void BuildObjectIdImage_SharedMaterialsAndShaders_AreStoredOnce() + { + var shared = CreateMaterial("Shared"); + var other = CreateMaterial("Other"); + + var first = CreateGameObject("First").AddComponent(); + first.sharedMaterials = new[] { shared, null }; + var second = CreateGameObject("Second").AddComponent(); + second.sharedMaterials = new[] { shared, other }; + var noRenderer = CreateGameObject("NoRenderer"); + var idToObject = new UnityEngine.Object[] { null, first, second, noRenderer }; + + // First gets the most pixels so the entry order is fixed + var mapping = BufferCapture.BuildObjectIdImage(EncodeIds(1, 1, 1, 2, 2, 3), 6, 1, idToObject, out _); + + Assert.That(mapping.materials.Select(m => m.name), Is.EqualTo(new[] { "Shared", "Other" })); + Assert.AreEqual(1, mapping.shaders.Length); + Assert.AreEqual(shared.shader.name, mapping.shaders[0].name); + Assert.IsTrue(mapping.materials.All(m => m.shader == 0)); + Assert.IsNull(mapping.materials[0].path); + + Assert.That(mapping.objects[0].materials, Is.EqualTo(new[] { 0, -1 })); + Assert.That(mapping.objects[1].materials, Is.EqualTo(new[] { 0, 1 })); + Assert.IsEmpty(mapping.objects[2].materials); + } + + [Test] + public void BuildObjectIdImage_ObjectsInSeveralScenes_ReferenceSharedSceneEntries() + { + // Hidden, unsaved root objects are removed from regular scenes but stay in preview scenes + var sceneA = EditorSceneManager.NewPreviewScene(); + var sceneB = EditorSceneManager.NewPreviewScene(); + try + { + var first = CreateGameObject("First").AddComponent(); + var second = CreateGameObject("Second").AddComponent(); + var third = CreateGameObject("Third").AddComponent(); + SceneManager.MoveGameObjectToScene(first.gameObject, sceneA); + SceneManager.MoveGameObjectToScene(second.gameObject, sceneA); + SceneManager.MoveGameObjectToScene(third.gameObject, sceneB); + var idToObject = new UnityEngine.Object[] { null, first, second, third }; + + // First gets the most pixels so the entry order is fixed + var mapping = BufferCapture.BuildObjectIdImage(EncodeIds(1, 1, 1, 2, 2, 3), 6, 1, idToObject, out _); + + Assert.AreEqual(2, mapping.scenes.Length); + Assert.That(mapping.objects.Select(o => o.scene), Is.EqualTo(new[] { 0, 0, 1 })); + Assert.IsNull(mapping.scenes[0].path); + } + finally + { + EditorSceneManager.ClosePreviewScene(sceneA); + EditorSceneManager.ClosePreviewScene(sceneB); + } + } + + [Test] + public void BuildObjectIdImage_ObjectWithoutGameObject_HasNoScene() + { + var material = CreateMaterial("NotARenderer"); + var idToObject = new UnityEngine.Object[] { null, material }; + + var mapping = BufferCapture.BuildObjectIdImage(EncodeIds(1), 1, 1, idToObject, out _); + + Assert.AreEqual(-1, mapping.objects.Single().scene); + Assert.IsEmpty(mapping.scenes); + } + + [Test] + public void BuildObjectIdImage_ManyObjects_GetDistinctColors() + { + const int k_ObjectCount = 300; + var idToObject = new UnityEngine.Object[k_ObjectCount + 1]; + var ids = new int[k_ObjectCount]; + for (int i = 0; i < k_ObjectCount; ++i) + { + idToObject[i + 1] = CreateGameObject("Object" + i); + ids[i] = i + 1; + } + + var mapping = BufferCapture.BuildObjectIdImage(EncodeIds(ids), k_ObjectCount, 1, idToObject, out var colored); + + Assert.AreEqual(k_ObjectCount, mapping.objects.Length); + Assert.AreEqual(k_ObjectCount, colored.Distinct().Count()); + CollectionAssert.DoesNotContain(colored, k_Background); + CollectionAssert.DoesNotContain(colored, k_Unresolved); + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/BufferCaptureTests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Editor/BufferCaptureTests.cs.meta new file mode 100644 index 00000000000..24fd76634a7 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/BufferCaptureTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 16773b5b4d19f6a43880ac15a860ba30 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ConstantBufferBudgetTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ConstantBufferBudgetTests.cs index 586d8b7b9f8..21c67ff187a 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ConstantBufferBudgetTests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ConstantBufferBudgetTests.cs @@ -42,6 +42,8 @@ class ConstantBufferBudgetTests ShaderKeywordStrings.ShadowsShadowMask, ShaderKeywordStrings.LIGHTMAP_ON, ShaderKeywordStrings.AdditionalLightShadows, + ShaderKeywordStrings.SoftShadows, + ShaderKeywordStrings.ShadowsPCSS, ShaderKeywordStrings.ScreenSpaceReflection, ShaderKeywordStrings.ScreenSpaceOcclusion, ShaderKeywordStrings.DBufferMRT3, diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ConstantBufferPropertyWarningsTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ConstantBufferPropertyWarningsTests.cs new file mode 100644 index 00000000000..09752f5706e --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ConstantBufferPropertyWarningsTests.cs @@ -0,0 +1,509 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.RegularExpressions; +using NUnit.Framework; +using UnityEngine; +using UnityEngine.Rendering; +using UnityEngine.Rendering.Universal; +using UnityEngine.TestTools; +using CoreBridge = Unity.RenderPipelines.Core.Runtime.Shared.ConstantBufferBackedPropertiesBridge; + +namespace UnityEditor.Rendering.Universal.Tests +{ + class ConstantBufferPropertyWarningsTests + { + // "float4 _AdditionalLightsPosition[MAX_VISIBLE_LIGHTS];", leading whitespace and trailing comment allowed. + static readonly Regex k_HlslDeclaration = new Regex(@"^\s*\w+\s+(\w+)\s*(?:\[[^\]]*\])?\s*;"); + + const string k_TestWarning = "Test warning about '{0}'."; + + static readonly Dictionary k_LightingConstantBufferFiles = new Dictionary + { + { "AdditionalLights", "ShaderLibrary/Input.hlsl" }, + { "AdditionalLightShadows", "ShaderLibrary/Shadows.hlsl" }, + { "urp_ReflectionProbeBuffer", "ShaderLibrary/Input.hlsl" }, + { "LightCookies", "ShaderLibrary/LightCookie/LightCookieInput.hlsl" }, + }; + + [TearDown] + public void TearDown() + { + ConstantBufferPropertyWarnings.Release(); + } + + static Regex WarningRegex(string warning, string propertyName) + { + return new Regex(Regex.Escape(warning.Replace("{0}", propertyName))); + } + + static Regex BoundWarningFor(string propertyName) + { + return WarningRegex(ConstantBufferPropertyWarnings.k_GlobalWarningBound, propertyName); + } + + static Regex FutureWarningFor(string propertyName) + { + return WarningRegex(ConstantBufferPropertyWarnings.k_GlobalWarningBoundLater, propertyName); + } + + static Regex TestWarningFor(string propertyName) + { + return WarningRegex(k_TestWarning, propertyName); + } + + static int MarkWithTestWarning(string propertyName) + { + ConstantBufferPropertyWarnings.MarkProperty(propertyName, k_TestWarning); + return Shader.PropertyToID(propertyName); + } + + static Material CreateTestMaterial() + { + return new Material(Shader.Find("Hidden/InternalErrorShader")); + } + + static string PackageFilePath(string relativePath) + { + var package = PackageManager.PackageInfo.FindForAssembly(typeof(UniversalRenderPipeline).Assembly); + Assert.That(package, Is.Not.Null, "Cannot find the URP package."); + return Path.Combine(package.resolvedPath, relativePath); + } + + // Names of the members declared between every CBUFFER_START(cbufferName) and the next CBUFFER_END of the file. + static void AddConstantBufferMembers(string relativePath, string cbufferName, HashSet members) + { + string start = $"CBUFFER_START({cbufferName})"; + bool inside = false; + bool found = false; + + foreach (string line in File.ReadAllLines(PackageFilePath(relativePath))) + { + string trimmed = line.Trim(); + if (trimmed.StartsWith("//", StringComparison.Ordinal) || trimmed.StartsWith("#", StringComparison.Ordinal)) + continue; + + if (trimmed.StartsWith(start, StringComparison.Ordinal)) + { + inside = true; + found = true; + continue; + } + + if (trimmed.StartsWith("CBUFFER_END", StringComparison.Ordinal)) + { + inside = false; + continue; + } + + if (!inside) + continue; + + var match = k_HlslDeclaration.Match(line); + if (match.Success) + members.Add(match.Groups[1].Value); + } + + Assert.That(found, Is.True, $"{relativePath} no longer declares {start}."); + } + + [Test] + public void LightingConstantBuffers_MatchTheHlslConstantBufferMembers() + { + foreach (var constantBuffer in ConstantBufferPropertyWarnings.k_LightingConstantBuffers) + { + string hlslPath = k_LightingConstantBufferFiles[constantBuffer.name]; + var hlslMembers = new HashSet(); + AddConstantBufferMembers(hlslPath, constantBuffer.name, hlslMembers); + + CollectionAssert.AreEquivalent(hlslMembers, constantBuffer.members, + $"ConstantBufferPropertyWarnings.k_LightingConstantBuffers must list the members of {constantBuffer.name} ({hlslPath})."); + } + } + + [Test] + public void GlobalShaderVariables_MatchTheHlslConstantBufferMembersButThePadding() + { + var hlslMembers = new HashSet(); + AddConstantBufferMembers("ShaderLibrary/GlobalShaderVariables.hlsl", "GlobalShaderVariables", hlslMembers); + hlslMembers.RemoveWhere(name => name.StartsWith("_URPPadding", StringComparison.Ordinal)); + + CollectionAssert.AreEquivalent(hlslMembers, ConstantBufferPropertyWarnings.k_GlobalShaderVariables, + "ConstantBufferPropertyWarnings.k_GlobalShaderVariables must list the members of GlobalShaderVariables but the padding (ShaderLibrary/GlobalShaderVariables.hlsl)."); + } + + [Test] + public void LooseUniformWrite_DuringRenderInConstantBufferMode_WarnsOncePerProperty() + { + int id = Shader.PropertyToID("_MainLightColor"); + Vector4 previous = Shader.GetGlobalVector(id); + + ConstantBufferPropertyWarnings.BeginRender(true); + try + { + LogAssert.Expect(LogType.Warning, BoundWarningFor("_MainLightColor")); + Shader.SetGlobalVector(id, Vector4.one); + Shader.SetGlobalVector(id, Vector4.one); + } + finally + { + ConstantBufferPropertyWarnings.EndRender(); + Shader.SetGlobalVector(id, previous); + } + + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void LooseUniformWrite_AfterEndRender_DoesNotWarn() + { + int id = Shader.PropertyToID("_MainLightPosition"); + Vector4 previous = Shader.GetGlobalVector(id); + + ConstantBufferPropertyWarnings.BeginRender(true); + ConstantBufferPropertyWarnings.EndRender(); + Shader.SetGlobalVector(id, Vector4.one); + Shader.SetGlobalVector(id, previous); + + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void LooseUniformWrite_AfterARenderRequestDuringRender_StillWarnsUntilEndRender() + { + int id = Shader.PropertyToID("_GlossyEnvironmentColor"); + Vector4 previous = Shader.GetGlobalVector(id); + + ConstantBufferPropertyWarnings.BeginRender(false); + // A render request made while URP renders. + ConstantBufferPropertyWarnings.BeginRender(false); + ConstantBufferPropertyWarnings.EndRender(); + try + { + LogAssert.Expect(LogType.Warning, FutureWarningFor("_GlossyEnvironmentColor")); + Shader.SetGlobalVector(id, Vector4.one); + } + finally + { + ConstantBufferPropertyWarnings.EndRender(); + Shader.SetGlobalVector(id, previous); + } + + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void LooseUniformWrite_DuringRenderWithoutTheConstantBufferMode_WarnsAboutTheFutureOnce() + { + int id = Shader.PropertyToID("_ScaledScreenParams"); + Vector4 previous = Shader.GetGlobalVector(id); + + ConstantBufferPropertyWarnings.BeginRender(false); + try + { + LogAssert.Expect(LogType.Warning, FutureWarningFor("_ScaledScreenParams")); + Shader.SetGlobalVector(id, Vector4.one); + Shader.SetGlobalVector(id, Vector4.one); + } + finally + { + ConstantBufferPropertyWarnings.EndRender(); + Shader.SetGlobalVector(id, previous); + } + + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void MaterialWrite_ToALightingConstantBufferMember_WarnsThatItIsIgnoredInBothModes([Values(false, true)] bool useGlobalConstantBuffer) + { + Assume.That(RenderingUtils.usePersistentConstantBuffer, Is.True, "URP binds the lighting constant buffers itself on this graphics API only."); + // A new material, so no earlier array of another size is in the way. + var material = CreateTestMaterial(); + + ConstantBufferPropertyWarnings.BeginRender(useGlobalConstantBuffer); + ConstantBufferPropertyWarnings.EndRender(); + try + { + LogAssert.Expect(LogType.Warning, WarningRegex(ConstantBufferPropertyWarnings.LightingConstantBufferWarning("AdditionalLights"), "_AdditionalLightsColor")); + material.SetVectorArray("_AdditionalLightsColor", new Vector4[8]); + } + finally + { + UnityEngine.Object.DestroyImmediate(material); + } + + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void PipelineWrites_DuringRender_DoNotWarn() + { + int id = Shader.PropertyToID("_ScreenParams"); + Vector4 previous = Shader.GetGlobalVector(id); + + ConstantBufferPropertyWarnings.BeginRender(false); + try + { + ConstantBufferPropertyWarnings.BeginPipelineWrites(); + Shader.SetGlobalVector(id, Vector4.one); + ConstantBufferPropertyWarnings.EndPipelineWrites(); + + // The warnings are back on after the pipeline writes. + LogAssert.Expect(LogType.Warning, FutureWarningFor("_ScreenParams")); + Shader.SetGlobalVector(id, Vector4.one); + } + finally + { + ConstantBufferPropertyWarnings.EndRender(); + Shader.SetGlobalVector(id, previous); + } + + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void UploaderLooseUniformPush_DuringRender_DoesNotWarn() + { + var uploader = new GlobalShaderVariablesUploader(GlobalShaderVariablesGroup.Base | GlobalShaderVariablesGroup.Only3D); + uploader._ScaledScreenParams = Vector4.one; + + using var nativeCmd = new CommandBuffer(); + ConstantBufferPropertyWarnings.BeginRender(false); + try + { + uploader.Push(CommandBufferHelpers.GetUnsafeCommandBuffer(nativeCmd)); + } + finally + { + ConstantBufferPropertyWarnings.EndRender(); + } + + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void LooseUniformWrite_AfterTheModeChanged_WarnsInTheNewMode([Values(false, true)] bool useGlobalConstantBuffer) + { + ConstantBufferPropertyWarnings.BeginRender(!useGlobalConstantBuffer); + ConstantBufferPropertyWarnings.EndRender(); + + int id = Shader.PropertyToID("_SubtractiveShadowColor"); + Vector4 previous = Shader.GetGlobalVector(id); + + ConstantBufferPropertyWarnings.BeginRender(useGlobalConstantBuffer); + try + { + LogAssert.Expect(LogType.Warning, useGlobalConstantBuffer ? BoundWarningFor("_SubtractiveShadowColor") : FutureWarningFor("_SubtractiveShadowColor")); + Shader.SetGlobalVector(id, Vector4.one); + } + finally + { + ConstantBufferPropertyWarnings.EndRender(); + Shader.SetGlobalVector(id, previous); + } + + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void CommandBufferPropertyBlockAndArrayWrites_ToAMarkedProperty_Warn() + { + CoreBridge.ClearWarnings(); + int commandBufferId = MarkWithTestWarning("_CBPropertyWarningsTest_CommandBuffer"); + int propertyBlockId = MarkWithTestWarning("_CBPropertyWarningsTest_PropertyBlock"); + int arrayId = MarkWithTestWarning("_CBPropertyWarningsTest_Array"); + CoreBridge.EnableWarnings(true); + try + { + LogAssert.Expect(LogType.Warning, TestWarningFor("_CBPropertyWarningsTest_CommandBuffer")); + using (var cmd = new CommandBuffer()) + cmd.SetGlobalFloat(commandBufferId, 1.0f); + + LogAssert.Expect(LogType.Warning, TestWarningFor("_CBPropertyWarningsTest_PropertyBlock")); + new MaterialPropertyBlock().SetColor(propertyBlockId, Color.red); + + LogAssert.Expect(LogType.Warning, TestWarningFor("_CBPropertyWarningsTest_Array")); + Shader.SetGlobalVectorArray(arrayId, new[] { Vector4.zero }); + } + finally + { + CoreBridge.EnableWarnings(false); + CoreBridge.ClearWarnings(); + } + + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void MaterialWrite_OutsideRenderInConstantBufferMode_WarnsOncePerProperty() + { + var material = CreateTestMaterial(); + + // After Render(), like a MonoBehaviour.Update() between two frames. + ConstantBufferPropertyWarnings.BeginRender(true); + ConstantBufferPropertyWarnings.EndRender(); + try + { + LogAssert.Expect(LogType.Warning, BoundWarningFor("_TimeParameters")); + material.SetVector("_TimeParameters", Vector4.one); + material.SetVector("_TimeParameters", Vector4.one); + } + finally + { + UnityEngine.Object.DestroyImmediate(material); + } + + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void MaterialWrite_AfterURPIsDisposedButStaysActive_StillWarns() + { + var material = CreateTestMaterial(); + + ConstantBufferPropertyWarnings.BeginRender(true); + ConstantBufferPropertyWarnings.EndRender(); + ConstantBufferPropertyWarnings.OnPipelineDisposed(true); + try + { + LogAssert.Expect(LogType.Warning, BoundWarningFor("_TimeParameters")); + material.SetVector("_TimeParameters", Vector4.one); + } + finally + { + UnityEngine.Object.DestroyImmediate(material); + } + + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void MaterialWrite_AfterAnotherPipelineTakesOver_DoesNotWarn() + { + var material = CreateTestMaterial(); + + ConstantBufferPropertyWarnings.BeginRender(true); + ConstantBufferPropertyWarnings.EndRender(); + ConstantBufferPropertyWarnings.OnPipelineDisposed(false); + try + { + material.SetVector("_TimeParameters", Vector4.one); + } + finally + { + UnityEngine.Object.DestroyImmediate(material); + } + + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void MaterialWrite_WithoutRenderGraphValidityChecks_DoesNotWarn() + { + if (!GraphicsSettings.TryGetRenderPipelineSettings(out var renderGraphSettings)) + Assert.Ignore("Enable Validity Checks lives in the Render Graph settings of the active render pipeline."); + bool validityChecksBefore = renderGraphSettings.enableValidityChecks; + var material = CreateTestMaterial(); + + try + { + renderGraphSettings.enableValidityChecks = true; + ConstantBufferPropertyWarnings.BeginRender(true); + ConstantBufferPropertyWarnings.EndRender(); + + renderGraphSettings.enableValidityChecks = false; + ConstantBufferPropertyWarnings.BeginRender(true); + ConstantBufferPropertyWarnings.EndRender(); + material.SetVector("_TimeParameters", Vector4.one); + } + finally + { + renderGraphSettings.enableValidityChecks = validityChecksBefore; + UnityEngine.Object.DestroyImmediate(material); + } + + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void MaterialWrite_OutsideRenderWithoutTheConstantBufferMode_WarnsAboutTheFuture() + { + var material = CreateTestMaterial(); + + ConstantBufferPropertyWarnings.BeginRender(false); + ConstantBufferPropertyWarnings.EndRender(); + try + { + LogAssert.Expect(LogType.Warning, FutureWarningFor("_TimeParameters")); + material.SetVector("_TimeParameters", Vector4.one); + } + finally + { + UnityEngine.Object.DestroyImmediate(material); + } + + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void MaterialSetters_ToAMarkedProperty_WarnWithTheWarningsDisabled() + { + var material = CreateTestMaterial(); + + CoreBridge.ClearWarnings(); + int floatId = MarkWithTestWarning("_CBPropertyWarningsTest_MaterialFloat"); + int integerId = MarkWithTestWarning("_CBPropertyWarningsTest_MaterialInteger"); + int colorId = MarkWithTestWarning("_CBPropertyWarningsTest_MaterialColor"); + int matrixId = MarkWithTestWarning("_CBPropertyWarningsTest_MaterialMatrix"); + int arrayId = MarkWithTestWarning("_CBPropertyWarningsTest_MaterialArray"); + int textureId = MarkWithTestWarning("_CBPropertyWarningsTest_MaterialTexture"); + try + { + LogAssert.Expect(LogType.Warning, TestWarningFor("_CBPropertyWarningsTest_MaterialFloat")); + material.SetFloat(floatId, 1.0f); + + LogAssert.Expect(LogType.Warning, TestWarningFor("_CBPropertyWarningsTest_MaterialInteger")); + material.SetInteger(integerId, 1); + + LogAssert.Expect(LogType.Warning, TestWarningFor("_CBPropertyWarningsTest_MaterialColor")); + material.SetColor(colorId, Color.red); + + LogAssert.Expect(LogType.Warning, TestWarningFor("_CBPropertyWarningsTest_MaterialMatrix")); + material.SetMatrix(matrixId, Matrix4x4.identity); + + LogAssert.Expect(LogType.Warning, TestWarningFor("_CBPropertyWarningsTest_MaterialArray")); + material.SetVectorArray(arrayId, new[] { Vector4.zero }); + + // Textures cannot live in a constant buffer. + material.SetTexture(textureId, Texture2D.whiteTexture); + } + finally + { + CoreBridge.ClearWarnings(); + UnityEngine.Object.DestroyImmediate(material); + } + + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void TextureWrite_ToAMarkedProperty_DoesNotWarn() + { + CoreBridge.ClearWarnings(); + int id = MarkWithTestWarning("_CBPropertyWarningsTest_Texture"); + CoreBridge.EnableWarnings(true); + try + { + Shader.SetGlobalTexture(id, Texture2D.whiteTexture); + } + finally + { + CoreBridge.EnableWarnings(false); + CoreBridge.ClearWarnings(); + } + + LogAssert.NoUnexpectedReceived(); + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ConstantBufferPropertyWarningsTests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ConstantBufferPropertyWarningsTests.cs.meta new file mode 100644 index 00000000000..0e803187eec --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ConstantBufferPropertyWarningsTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 85f60eacd1214a06a6e0ac074f21cfc8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/DebugDisplaySettingsShadowCachingTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/DebugDisplaySettingsShadowCachingTests.cs new file mode 100644 index 00000000000..c029eb5539a --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/DebugDisplaySettingsShadowCachingTests.cs @@ -0,0 +1,294 @@ +#if URP_SHADOW_CACHING + +using System; +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework; +using UnityEngine; +using UnityEngine.Rendering; +using UnityEngine.Rendering.Universal; + +namespace UnityEditor.Rendering.Universal.Tests.ShadowCaching +{ + static class ShadowCachingDebugDisplaySettingsFactory + { + internal static UniversalRenderPipelineDebugDisplaySettings Create() + { + var discardUnusedMips = Texture.streamingTextureDiscardUnusedMips; + var debugDisplaySettings = new UniversalRenderPipelineDebugDisplaySettings(); + debugDisplaySettings.Reset(); + Texture.streamingTextureDiscardUnusedMips = discardUnusedMips; + return debugDisplaySettings; + } + } + + class EachShadowCachingStateHasItsOwnColorTests + { + const string k_ShaderSource = + "Shader \"Hidden/Universal Render Pipeline/Tests/ShadowCachingForceState\"\n" + + "{\n" + + " SubShader\n" + + " {\n" + + " Pass\n" + + " {\n" + + " ZTest Always\n" + + " ZWrite Off\n" + + " Cull Off\n" + + "\n" + + " HLSLPROGRAM\n" + + " #pragma vertex Vert\n" + + " #pragma fragment Frag\n" + + "\n" + + " #define DEBUG_DISPLAY\n" + + "\n" + + " #include \"Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl\"\n" + + " #include \"Packages/com.unity.render-pipelines.universal/ShaderLibrary/Debug/Debugging3D.hlsl\"\n" + + "\n" + + " int _ShadowCachingState;\n" + + "\n" + + " float4 Vert(uint vertexID : SV_VertexID) : SV_POSITION\n" + + " {\n" + + " return GetFullScreenTriangleVertexPosition(vertexID);\n" + + " }\n" + + "\n" + + " float4 Frag() : SV_Target\n" + + " {\n" + + " return float4(GetDebugShadowCachingStateColor(_ShadowCachingState), 1.0);\n" + + " }\n" + + " ENDHLSL\n" + + " }\n" + + " }\n" + + "}"; + const float k_ReadbackTolerance = 2e-3f; + + RenderTexture m_PreviousActiveTarget; + Shader m_Shader; + Material m_Material; + RenderTexture m_Target; + Texture2D m_Readback; + + [SetUp] + public void SetUp() + { + m_PreviousActiveTarget = RenderTexture.active; + + if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null) + Assert.Ignore("Cannot run: there is no graphics device to draw with."); + if (!SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBFloat)) + Assert.Ignore("Cannot run: this graphics device cannot render to ARGBFloat, so the state colors cannot be read back exactly."); + + m_Shader = ShaderUtil.CreateShaderAsset(k_ShaderSource); + Assert.IsTrue(m_Shader.isSupported, "The state color shader did not compile for this graphics device."); + + m_Material = new Material(m_Shader); + m_Target = new RenderTexture(1, 1, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear); + m_Readback = new Texture2D(1, 1, TextureFormat.RGBAFloat, false, true); + } + + [TearDown] + public void TearDown() + { + RenderTexture.active = m_PreviousActiveTarget; + CoreUtils.Destroy(m_Readback); + CoreUtils.Destroy(m_Target); + CoreUtils.Destroy(m_Material); + CoreUtils.Destroy(m_Shader); + } + + [Test] + public void StateColor_ForEachStateOtherThanNone_DiffersFromOtherStatesAndUnmappedState() + { + var states = Enum.GetValues(typeof(ShadowCachingDebugState)) + .Cast() + .Where(state => state != ShadowCachingDebugState.None) + .ToArray(); + var unmappedState = states.Max(state => (int)state) + 1; + var unmappedColor = ReadBackStateColor(unmappedState); + + var colors = states.Select(state => ReadBackStateColor((int)state)).ToArray(); + + for (var i = 0; i < states.Length; i++) + { + Assert.IsFalse(AreSameColor(colors[i], unmappedColor), $"{states[i]} reads back {colors[i]}, the color an unmapped state gets."); + for (var j = i + 1; j < states.Length; j++) + Assert.IsFalse(AreSameColor(colors[i], colors[j]), $"{states[i]} and {states[j]} both read back {colors[i]}."); + } + } + + Color ReadBackStateColor(int state) + { + m_Material.SetInteger("_ShadowCachingState", state); + + using var cmd = new CommandBuffer(); + cmd.SetRenderTarget(m_Target); + cmd.DrawProcedural(Matrix4x4.identity, m_Material, 0, MeshTopology.Triangles, 3); + Graphics.ExecuteCommandBuffer(cmd); + + RenderTexture.active = m_Target; + m_Readback.ReadPixels(new Rect(0, 0, 1, 1), 0, 0, false); + return m_Readback.GetPixel(0, 0); + } + + static bool AreSameColor(Color first, Color second) + { + return Mathf.Abs(first.r - second.r) <= k_ReadbackTolerance + && Mathf.Abs(first.g - second.g) <= k_ReadbackTolerance + && Mathf.Abs(first.b - second.b) <= k_ReadbackTolerance; + } + } + + class ForceStateReachesShadersTests + { + const string k_DebugDisplayKeyword = "DEBUG_DISPLAY"; + const int k_UnsetForceState = -1; + static readonly int k_ForceStateId = Shader.PropertyToID("_DebugShadowCachingForceState"); + static readonly string[] k_FloatGlobalsSetupWrites = + { + "_DebugMaterialMode", + "_DebugVertexAttributeMode", + "_DebugMipMapOpacity", + "_DebugMipMapRecentlyUpdatedCooldown", + "_DebugMipMapTerrainTextureMode", + "_DebugLightingMode", + "_DebugCurrentRealTime", + }; + static readonly string[] k_IntegerGlobalsSetupWrites = + { + "_DebugMaterialValidationMode", + "_DebugMipInfoMode", + "_DebugMipMapStatusMode", + "_DebugMipMapShowStatusCode", + "_DebugSceneOverrideMode", + "_DebugFullScreenMode", + "_DebugMaxPixelCost", + "_DebugValidationMode", + "_DebugLightingFeatureFlags", + "_DebugShadowCachingForceState", + }; + static readonly string[] k_ColorGlobalsSetupWrites = + { + "_DebugValidateBelowMinThresholdColor", + "_DebugValidateAboveMaxThresholdColor", + "_DebugColorInvalidMode", + }; + + float[] m_PreviousFloats; + int[] m_PreviousIntegers; + Color[] m_PreviousColors; + bool m_PreviousDebugDisplay; + + [SetUp] + public void SetUp() + { + m_PreviousFloats = k_FloatGlobalsSetupWrites.Select(Shader.GetGlobalFloat).ToArray(); + m_PreviousIntegers = k_IntegerGlobalsSetupWrites.Select(Shader.GetGlobalInteger).ToArray(); + m_PreviousColors = k_ColorGlobalsSetupWrites.Select(Shader.GetGlobalColor).ToArray(); + m_PreviousDebugDisplay = Shader.IsKeywordEnabled(k_DebugDisplayKeyword); + } + + [TearDown] + public void TearDown() + { + for (var i = 0; i < k_FloatGlobalsSetupWrites.Length; i++) + Shader.SetGlobalFloat(k_FloatGlobalsSetupWrites[i], m_PreviousFloats[i]); + for (var i = 0; i < k_IntegerGlobalsSetupWrites.Length; i++) + Shader.SetGlobalInteger(k_IntegerGlobalsSetupWrites[i], m_PreviousIntegers[i]); + for (var i = 0; i < k_ColorGlobalsSetupWrites.Length; i++) + Shader.SetGlobalColor(k_ColorGlobalsSetupWrites[i], m_PreviousColors[i]); + + if (m_PreviousDebugDisplay) + Shader.EnableKeyword(k_DebugDisplayKeyword); + else + Shader.DisableKeyword(k_DebugDisplayKeyword); + } + + [Test] + public void DebugHandlerSetup_WhenDebuggerIsActiveForCamera_WritesForceStateForShaders([Values(ShadowCachingDebugState.None, ShadowCachingDebugState.Stale)] ShadowCachingDebugState forceState) + { + Shader.SetGlobalInteger(k_ForceStateId, k_UnsetForceState); + + using var cmd = new CommandBuffer(); + DebugHandler.Setup(CommandBufferHelpers.GetRasterCommandBuffer(cmd), new DebugHandler.DebugSetupPassData + { + isActiveForCamera = true, + materialSettings = new DebugDisplaySettingsMaterial(), + renderingSettings = new DebugDisplaySettingsRendering(), + lightingSettings = new DebugDisplaySettingsLighting(), + shadowCachingSettings = new DebugDisplaySettingsShadowCaching { forceState = forceState }, + }); + Graphics.ExecuteCommandBuffer(cmd); + + Assert.AreEqual((int)forceState, Shader.GetGlobalInteger(k_ForceStateId)); + } + } + + class ForceStateTurnsOnDebugRenderingTests + { + [TestCase(ShadowCachingDebugState.None, ExpectedResult = false)] + [TestCase(ShadowCachingDebugState.Stale, ExpectedResult = true)] + public bool RenderingDebugger_WithForceStateAsOnlySetting_IsActiveUnlessForceStateIsNone(ShadowCachingDebugState forceState) + { + var debugDisplaySettings = ShadowCachingDebugDisplaySettingsFactory.Create(); + var shadowCachingSettings = debugDisplaySettings.shadowCachingSettings; + var previousForceState = shadowCachingSettings.forceState; + try + { + shadowCachingSettings.forceState = ShadowCachingDebugState.None; + Assert.That(debugDisplaySettings.AreAnySettingsActive, Is.False, + "Another Rendering Debugger setting is active, so Force State cannot be the setting that turns the debugger on."); + + shadowCachingSettings.forceState = forceState; + return debugDisplaySettings.AreAnySettingsActive; + } + finally + { + shadowCachingSettings.forceState = previousForceState; + } + } + + [TestCase(ShadowCachingDebugState.None, ExpectedResult = false)] + [TestCase(ShadowCachingDebugState.Stale, ExpectedResult = true)] + public bool DeferredRendering_WithForceStateAsOnlyDebugMode_FallsBackUnlessForceStateIsNone(ShadowCachingDebugState forceState) + { + return DebugHandler.IsModeUnsupportedForDeferred( + new DebugDisplaySettingsLighting(), + new DebugDisplaySettingsMaterial(), + new DebugDisplaySettingsRendering(), + new DebugDisplaySettingsShadowCaching { forceState = forceState }); + } + } + + class RenderingDebuggerShowsShadowCachingTabTests + { + [Test] + public void RenderingDebugger_WithShadowCachingDefine_RegistersShadowCachingTab() + { + var registered = new List(); + ShadowCachingDebugDisplaySettingsFactory.Create().ForEach(registered.Add); + var shadowCaching = registered.OfType().Single(); + + using var panel = ((IDebugDisplaySettingsData)shadowCaching).CreatePanel(); + + Assert.AreEqual("Shadow Caching", panel.PanelName); + } + + [Test] + public void ForceStateField_WhenFieldOrSettingChanges_ShowsTheSameValueInBoth() + { + var settings = new DebugDisplaySettingsShadowCaching(); + using var panel = new DebugDisplaySettingsShadowCaching.SettingsPanel(settings); + var forceState = panel.Widgets + .OfType() + .SelectMany(foldout => foldout.children) + .OfType() + .Single(field => field.displayName == DebugDisplaySettingsShadowCaching.Strings.ForceState.name); + + forceState.SetValue((int)ShadowCachingDebugState.Stale); + Assert.AreEqual(ShadowCachingDebugState.Stale, settings.forceState); + + settings.forceState = ShadowCachingDebugState.RecentlyRefreshed; + Assert.AreEqual((int)ShadowCachingDebugState.RecentlyRefreshed, forceState.GetValue()); + } + } +} +#endif diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/DebugDisplaySettingsShadowCachingTests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Editor/DebugDisplaySettingsShadowCachingTests.cs.meta new file mode 100644 index 00000000000..eeed1605184 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/DebugDisplaySettingsShadowCachingTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 98d8e2fbc41514d48b1095d75c0894c7 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/DeprecatedSurfaceIsolationTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/DeprecatedSurfaceIsolationTests.cs index f5530a3004d..f5b3f69d2bf 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Editor/DeprecatedSurfaceIsolationTests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/DeprecatedSurfaceIsolationTests.cs @@ -87,10 +87,11 @@ public void LiveSourcesDoNotReferenceDeprecatedContractMacros() static readonly Regex k_Include = new Regex( @"^\s*#\s*include(?:_with_pragmas)?\s+""([^""]+\.deprecated\.hlsl)""", RegexOptions.Compiled); - // Return type = builtin scalar/vector/matrix, or a struct name (PascalCase with at least - // one lowercase letter, so all-caps macros like UNITY_BRANCH never parse as a type). + // Return type = builtin scalar/vector/matrix, a struct name (PascalCase with at least + // one lowercase letter, so all-caps macros like UNITY_BRANCH never parse as a type), or + // the URP_LIGHT_ACCUM aliases, which are all-caps macros that stand in for a type. static readonly Regex k_FunctionDefinition = new Regex( - @"^\s*(?:inline\s+)?(?:(?:half|float|real|void|bool|int|uint|min16float)(?:[1-4](?:x[1-4])?)?|[A-Z]\w*[a-z]\w*)\s+(\w+)\s*\(", + @"^\s*(?:inline\s+)?(?:(?:half|float|real|void|bool|int|uint|min16float)(?:[1-4](?:x[1-4])?)?|URP_LIGHT_ACCUM[34]|[A-Z]\w*[a-z]\w*)\s+(\w+)\s*\(", RegexOptions.Compiled | RegexOptions.Multiline); static readonly Regex k_MacroDefinition = new Regex( @"^\s*#\s*define\s+(\w+)", RegexOptions.Compiled | RegexOptions.Multiline); diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/DynamicKeywordGuardTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/DynamicKeywordGuardTests.cs index 8d29472176f..9ab7c90605a 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Editor/DynamicKeywordGuardTests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/DynamicKeywordGuardTests.cs @@ -47,10 +47,12 @@ class DynamicKeywordGuardTests "_REFLECTION_PROBE_BLENDING", "_SCREEN_SPACE_OCCLUSION", "_SCREEN_SPACE_REFLECTION", + "_SHADOWS_PCSS", "_SHADOWS_SOFT", "_SHADOWS_SOFT_HIGH", "_SHADOWS_SOFT_LOW", "_SHADOWS_SOFT_MEDIUM", + "_SHADOW_RECEIVER_NORMAL_BIAS", "_SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A", "_SPECGLOSSMAP", "_SPECULARHIGHLIGHTS_OFF", @@ -84,14 +86,16 @@ static readonly (string path, string keyword, int count)[] k_SanctionedGuards = ("Editor/ShaderGraph/Includes/PBRForwardPass.hlsl", "_SPECULAR_SETUP", 1), ("Editor/ShaderGraph/Includes/PBRForwardPass.hlsl", "_CLEARCOAT", 1), ("Editor/ShaderGraph/Includes/PBRGBufferPass.hlsl", "_NORMALMAP", 1), - ("Editor/ShaderGraph/Includes/PBRGBufferPass.hlsl", "_SURFACE_TYPE_TRANSPARENT", 1), + ("Editor/ShaderGraph/Includes/PBRGBufferPass.hlsl", "_SURFACE_TYPE_TRANSPARENT", 2), ("Editor/ShaderGraph/Includes/PBRGBufferPass.hlsl", "_SPECULAR_SETUP", 1), ("Editor/ShaderGraph/Includes/SixWayForwardPass.hlsl", "_SURFACE_TYPE_TRANSPARENT", 3), ("Editor/ShaderGraph/Includes/UnlitPass.hlsl", "_SURFACE_TYPE_TRANSPARENT", 5), ("Editor/ShaderGraph/Includes/Varyings.hlsl", "_NORMALMAP", 1), + ("Editor/ShaderGraph/Includes/Varyings.hlsl", "_SURFACE_TYPE_TRANSPARENT", 1), ("Editor/ShaderGraph/Includes/Terrain/PBRForwardPass.hlsl", "_NORMALMAP", 1), - ("Editor/ShaderGraph/Includes/Terrain/PBRForwardPass.hlsl", "_SURFACE_TYPE_TRANSPARENT", 1), + ("Editor/ShaderGraph/Includes/Terrain/PBRForwardPass.hlsl", "_SURFACE_TYPE_TRANSPARENT", 2), ("Editor/ShaderGraph/Includes/Terrain/PBRGBufferPass.hlsl", "_NORMALMAP", 1), + ("Editor/ShaderGraph/Includes/Terrain/PBRGBufferPass.hlsl", "_SURFACE_TYPE_TRANSPARENT", 1), }; enum RestrictionScope diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/EditorTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/EditorTests.cs index 4d178a336a9..956eb2b2fe5 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Editor/EditorTests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/EditorTests.cs @@ -87,9 +87,6 @@ public void ValidateAssetSettings() UniversalRenderPipelineAsset asset = UniversalRenderPipelineAsset.Create(data); if (asset != null) { - asset.shadowDistance = -1.0f; - Assert.GreaterOrEqual(asset.shadowDistance, 0.0f); - asset.renderScale = -1.0f; Assert.GreaterOrEqual(asset.renderScale, UniversalRenderPipeline.minRenderScale); @@ -293,4 +290,32 @@ public void MaterialPostprocessor_MissingMaterial_DoesNotThrow() Assert.DoesNotThrow(() => UnityEditor.Rendering.Universal.MaterialPostprocessor.OnPostprocessAllAssets(imported, none, none, none)); } + + // Users can't save package materials, so validating them must not change them + [Test] + public void SceneTemplateMaterials_AreUpToDateWithLitValidation() + { + var guids = AssetDatabase.FindAssets("t:Material", new[] { "Packages/com.unity.render-pipelines.universal/Editor/SceneTemplates/Materials" }); + Assert.IsNotEmpty(guids); + + foreach (var guid in guids) + { + var path = AssetDatabase.GUIDToAssetPath(guid); + var material = AssetDatabase.LoadAssetAtPath(path); + var validated = new Material(material); + try + { + new UnityEditor.Rendering.Universal.ShaderGUI.LitShader().ValidateMaterial(validated); + + CollectionAssert.AreEquivalent(material.shaderKeywords, validated.shaderKeywords, $"{path} is out of date with its shader."); + + // Loading the material already ran the Editor's validation on it, so a value it changed only shows as the material being dirty + Assert.IsFalse(EditorUtility.IsDirty(material), $"{path} was changed when it was loaded and validated."); + } + finally + { + Object.DestroyImmediate(validated); + } + } + } } diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/FilterFunctionDefinitionGeneratorTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/FilterFunctionDefinitionGeneratorTests.cs index db185ab5d0a..ddecde9d049 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Editor/FilterFunctionDefinitionGeneratorTests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/FilterFunctionDefinitionGeneratorTests.cs @@ -11,20 +11,9 @@ namespace UnityEngine.Rendering.Universal.Tests { // Tests FilterFunctionDefinitionGenerator: Blackboard property -> FilterFunctionDefinition parameter - // mapping, and the generated applySettingsCallback's runtime behavior. + // mapping, and the pass setup that lets UI Toolkit draw it instanced. class FilterFunctionDefinitionGeneratorTests { - // FilterPassContext setters are internal to the engine module; reflection avoids an IVT grant needing an engine rebuild. - static FilterPassContext MakeContext(FilterFunction filterFunction, bool readsGamma = false) - { - object boxed = new FilterPassContext(); - typeof(FilterPassContext).GetProperty(nameof(FilterPassContext.filterFunction)) - .GetSetMethod(nonPublic: true).Invoke(boxed, new object[] { filterFunction }); - typeof(FilterPassContext).GetProperty(nameof(FilterPassContext.readsGamma)) - .GetSetMethod(nonPublic: true).Invoke(boxed, new object[] { readsGamma }); - return (FilterPassContext)boxed; - } - static (GraphData graph, UniversalFilterSubTarget subTarget) NewFilterGraph() { var graph = new GraphData(); @@ -105,94 +94,65 @@ public void Generate_MoreThanFourExposedProperties_KeepsOnlyFourAndWarns() } [Test] - public void Generate_ApplySettingsCallback_WritesLiveParameterValuesIntoPropertyBlock() + public void Generate_LeavesTheParametersToTheBindings() { - // parameterBindings alone is metadata; only applySettingsCallback pushes values at runtime. + // A settings callback would make UI Toolkit draw the pass one element at a time var (graph, _) = NewFilterGraph(); - - var floatProperty = new Vector1ShaderProperty { displayName = "Amount", generatePropertyBlock = true, value = 0.1f }; - graph.AddGraphInput(floatProperty); + graph.AddGraphInput(new Vector1ShaderProperty { displayName = "Amount", generatePropertyBlock = true }); var definition = FilterFunctionDefinitionGenerator.Generate(graph, NewDummyMaterial(), "TestFilter"); - Assert.IsNotNull(definition.passes[0].applySettingsCallback, - "applySettingsCallback must be set -- parameterBindings alone is not applied at runtime."); - // A *different* live value than the property's baked-in default (0.1f), to prove the callback - // reads the live FilterFunction value rather than the definition's own default. - var liveFunction = new FilterFunction(definition); - liveFunction.AddParameter(new FilterParameter(0.75f)); - - var context = MakeContext(liveFunction); - var mpb = new MaterialPropertyBlock(); - definition.passes[0].applySettingsCallback(mpb, context); - - Assert.AreEqual(0.75f, mpb.GetFloat(floatProperty.referenceName)); + Assert.IsNull(definition.passes[0].applySettingsCallback); + Assert.IsNull(definition.passes[0].writeParametersCallback); } [Test] - public void Generate_ApplySettingsCallback_WritesLiveColorValue() + public void Generate_EnablesInstancingOnTheMaterial() { var (graph, _) = NewFilterGraph(); - - var colorProperty = new ColorShaderProperty { displayName = "Tint", generatePropertyBlock = true, value = Color.black }; - graph.AddGraphInput(colorProperty); - - var definition = FilterFunctionDefinitionGenerator.Generate(graph, NewDummyMaterial(), "TestFilter"); - - var liveFunction = new FilterFunction(definition); - liveFunction.AddParameter(new FilterParameter(Color.cyan)); - - var context = MakeContext(liveFunction); - var mpb = new MaterialPropertyBlock(); - definition.passes[0].applySettingsCallback(mpb, context); - - Assert.AreEqual(Color.cyan, mpb.GetColor(colorProperty.referenceName)); + var material = NewDummyMaterial(); + try + { + FilterFunctionDefinitionGenerator.Generate(graph, material, "TestFilter"); + + Assert.IsTrue(material.enableInstancing); + } + finally + { + UnityEngine.Object.DestroyImmediate(material); + } } [Test] - public void Generate_ApplySettingsCallback_UnderSpecifiedFilterFunction_LeavesMaterialDefaults() + public void InstancedParameters_DeclareEveryExposedNumberPerInstance() { - // The public FilterFunction ctor does not pad missing parameters; the callback must skip them. var (graph, _) = NewFilterGraph(); - - var colorProperty = new ColorShaderProperty { displayName = "Tint", generatePropertyBlock = true, value = Color.red }; - graph.AddGraphInput(colorProperty); - - var definition = FilterFunctionDefinitionGenerator.Generate(graph, NewDummyMaterial(), "TestFilter"); - - var liveFunction = new FilterFunction(definition); // no AddParameter: parameterCount == 0 - - var mpb = new MaterialPropertyBlock(); - definition.passes[0].applySettingsCallback(mpb, MakeContext(liveFunction)); - - Assert.IsTrue(mpb.isEmpty, - "Bindings without a live parameter value must not be written; the material's own defaults (the blackboard values) must show through."); - } - - [Test] - public void Generate_ApplySettingsCallback_ReadsGamma_WritesRawSRGBColor() - { - // Assert.Ignore, not Assume: UTR reports Inconclusive as a failure, and PRV projects run in Gamma. - if (QualitySettings.activeColorSpace != ColorSpace.Linear) - Assert.Ignore("Only meaningful in a Linear color-space project, where SetColor linearizes."); - - var (graph, _) = NewFilterGraph(); - - var gray = new Color(0.5f, 0.5f, 0.5f, 1f); - var colorProperty = new ColorShaderProperty { displayName = "Tint", generatePropertyBlock = true, value = gray }; - graph.AddGraphInput(colorProperty); - - var definition = FilterFunctionDefinitionGenerator.Generate(graph, NewDummyMaterial(), "TestFilter"); - - var liveFunction = new FilterFunction(definition); - liveFunction.AddParameter(new FilterParameter(gray)); - - var mpb = new MaterialPropertyBlock(); - definition.passes[0].applySettingsCallback(mpb, MakeContext(liveFunction, readsGamma: true)); - - var stored = mpb.GetVector(colorProperty.referenceName); - Assert.AreEqual(0.5f, stored.x, 1e-3f, - "A gamma-reading pass must receive the raw sRGB value, not a linearized one."); + var numbers = new (AbstractShaderProperty property, string type)[] + { + (new Vector1ShaderProperty { displayName = "Amount", generatePropertyBlock = true }, "float"), + (new BooleanShaderProperty { displayName = "Enabled", generatePropertyBlock = true }, "float"), + (new Vector2ShaderProperty { displayName = "Offset", generatePropertyBlock = true }, "float2"), + (new Vector3ShaderProperty { displayName = "Axis", generatePropertyBlock = true }, "float3"), + (new Vector4ShaderProperty { displayName = "Bounds", generatePropertyBlock = true }, "float4"), + (new ColorShaderProperty { displayName = "Tint", generatePropertyBlock = true }, "float4"), + }; + foreach (var (property, _) in numbers) + { + graph.AddGraphInput(property); + } + var texture = new Texture2DShaderProperty { displayName = "Mask", generatePropertyBlock = true }; + graph.AddGraphInput(texture); + + var builder = new ShaderStringBuilder(); + new FilterInstancedParametersProperty(graph.properties) + .ForeachHLSLProperty(GenerationMode.ForReals, declaration => declaration.AppendTo(builder)); + var code = builder.ToCodeBlock(); + + foreach (var (property, type) in numbers) + { + StringAssert.Contains($"UNITY_DEFINE_INSTANCED_PROP({type}, {property.referenceName})", code); + } + StringAssert.DoesNotContain(texture.referenceName, code); } [Test] diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/FilterSubTargetTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/FilterSubTargetTests.cs index 155fee35de3..90e147e828f 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Editor/FilterSubTargetTests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/FilterSubTargetTests.cs @@ -260,5 +260,66 @@ public void UniversalFilterSubTarget_GeneratesCompilingShader_ForFilterInputWith Assert.IsNotNull(shader, "No Shader asset was produced for a Filter Input node with UV Space = Local."); Assert.IsFalse(ShaderUtil.ShaderHasError(shader), "The generated filter shader has compile errors:\n" + string.Join("\n", ShaderUtil.GetShaderMessages(shader).Select(m => m.message))); } + +#if ENABLE_CORECLR + [Explicit("MultiJson-serialized ShaderGraph written to disk fails to reimport on CoreCLR (JSON parse error: The document root must not follow by other values), so no Shader sub-assets are produced, see https://jira.unity3d.com/browse/UUM-150436")] +#endif + [Test] + public void UniversalFilterSubTarget_GeneratesCompilingInstancedVariant_ForGraphReadingItsParameters() + { + // The instancing variant reads the parameters and the rect per instance, and builds the quad without vertex buffer + var graph = NewGraphWithActiveSubTarget(typeof(UniversalFilterSubTarget)); + + var amount = new Vector1ShaderProperty { displayName = "Amount", generatePropertyBlock = true }; + graph.AddGraphInput(amount); + var tint = new ColorShaderProperty { displayName = "Tint", generatePropertyBlock = true }; + graph.AddGraphInput(tint); + var offset = new Vector2ShaderProperty { displayName = "Offset", generatePropertyBlock = true }; + graph.AddGraphInput(offset); + + var amountNode = new PropertyNode { property = amount }; + graph.AddNode(amountNode); + var tintNode = new PropertyNode { property = tint }; + graph.AddNode(tintNode); + var offsetNode = new PropertyNode { property = offset }; + graph.AddNode(offsetNode); + var filterInput = new FilterInputNode { uvSpace = FilterUVSpace.Local }; + graph.AddNode(filterInput); + var multiply = new MultiplyNode(); + graph.AddNode(multiply); + var scaledOffset = new MultiplyNode(); + graph.AddNode(scaledOffset); + + var baseColorBlock = new BlockNode(); + baseColorBlock.Init(BlockFields.SurfaceDescription.BaseColor); + graph.AddBlock(baseColorBlock, graph.fragmentContext, graph.fragmentContext.blocks.Count); + var alphaBlock = new BlockNode(); + alphaBlock.Init(BlockFields.SurfaceDescription.Alpha); + graph.AddBlock(alphaBlock, graph.fragmentContext, graph.fragmentContext.blocks.Count); + + graph.Connect(filterInput.GetSlotReference(1), multiply.GetSlotReference(0)); + graph.Connect(tintNode.GetSlotReference(PropertyNode.OutputSlotId), multiply.GetSlotReference(1)); + graph.Connect(multiply.GetSlotReference(2), baseColorBlock.GetSlotReference(0)); + graph.Connect(amountNode.GetSlotReference(PropertyNode.OutputSlotId), scaledOffset.GetSlotReference(0)); + graph.Connect(offsetNode.GetSlotReference(PropertyNode.OutputSlotId), scaledOffset.GetSlotReference(1)); + graph.Connect(scaledOffset.GetSlotReference(2), alphaBlock.GetSlotReference(0)); + graph.ValidateGraph(); + + var path = AssetDatabase.GenerateUniqueAssetPath(kTestAssetPath); + m_GeneratedAssetPath = path; + FileUtilities.WriteShaderGraphToDisk(path, graph); + AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceSynchronousImport | ImportAssetOptions.ForceUpdate | ImportAssetOptions.DontDownloadFromCacheServer); + + var shader = AssetDatabase.LoadAllAssetsAtPath(path).OfType().FirstOrDefault(); + Assert.IsNotNull(shader, "No Shader asset was produced for a filter graph reading its parameters."); + Assert.IsFalse(ShaderUtil.ShaderHasError(shader), "The generated filter shader has compile errors:\n" + string.Join("\n", ShaderUtil.GetShaderMessages(shader).Select(m => m.message))); + + var pass = ShaderUtil.GetShaderData(shader).GetSubshader(0).GetPass(0); + foreach (var stage in new[] { UnityEditor.Rendering.ShaderType.Vertex, UnityEditor.Rendering.ShaderType.Fragment }) + { + var result = pass.CompileVariant(stage, new[] { "INSTANCING_ON" }, UnityEditor.Rendering.ShaderCompilerPlatform.D3D, BuildTarget.StandaloneWindows64); + Assert.IsTrue(result.Success, $"The {stage} stage of the instancing variant has compile errors:\n" + string.Join("\n", result.Messages.Select(m => m.message))); + } + } } } diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/GBufferRenderingLayersTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/GBufferRenderingLayersTests.cs new file mode 100644 index 00000000000..de217bba2a2 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/GBufferRenderingLayersTests.cs @@ -0,0 +1,65 @@ +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework; +using UnityEngine; +using UnityEngine.Rendering; +using UnityEngine.Rendering.Universal; + +namespace UnityEditor.Rendering.Universal.Tests +{ + // With Rendering Layers enabled, deferred lighting only lights a pixel whose GBuffer rendering layers mask + // contains the light's layers. A GBuffer pass without the _WRITE_RENDERING_LAYERS variant leaves that mask + // unwritten, so what it draws takes whatever was there before, usually nothing, and goes unlit. + class GBufferRenderingLayersTests + { + const string k_ShaderFolder = "Packages/com.unity.render-pipelines.universal/Shaders"; + + [Test] + public void GBufferPassesDeclareWriteRenderingLayers() + { + var lightMode = new ShaderTagId("LightMode"); + var renderPipeline = new ShaderTagId("RenderPipeline"); + var checkedShaders = new HashSet(); + var missing = new List(); + + foreach (var guid in AssetDatabase.FindAssets("t:Shader", new[] { k_ShaderFolder })) + { + var path = AssetDatabase.GUIDToAssetPath(guid); + var shader = AssetDatabase.LoadAssetAtPath(path); + Assert.IsNotNull(shader, $"Failed to load shader at path '{path}'"); + + var data = ShaderUtil.GetShaderData(shader); + // Serialized subshaders only: the runtime list also holds the Fallback shader's subshaders. + for (int s = 0; s < data.SerializedSubshaderCount; ++s) + { + var subshader = data.GetSerializedSubshader(s); + // Shader Graph assets can carry subshaders for other pipelines, such as HDRP, which URP never selects. + // Untagged subshaders stay in: URP can select them. + var pipelineTag = subshader.FindTagValue(renderPipeline).name; + if (!string.IsNullOrEmpty(pipelineTag) && pipelineTag != "UniversalPipeline") + continue; + + for (int p = 0; p < subshader.PassCount; ++p) + { + var pass = subshader.GetPass(p); + if (pass.FindTagValue(lightMode).name != "UniversalGBuffer") + continue; + + checkedShaders.Add(path); + var keywords = ShaderUtil.GetPassKeywords(shader, new PassIdentifier((uint)s, (uint)p), ShaderType.Fragment); + if (!keywords.Any(k => k.name == ShaderKeywordStrings.WriteRenderingLayers)) + missing.Add($"{path} (subshader {s}, pass '{pass.Name}')"); + } + } + } + + Assert.That(checkedShaders, Does.Contain($"{k_ShaderFolder}/Lit.shader"), + "Found no GBuffer pass in Lit.shader; did the shader folder or the LightMode tag change?"); + Assert.That(missing, Is.Empty, + $"These GBuffer passes do not declare {ShaderKeywordStrings.WriteRenderingLayers}, so with Rendering Layers on in " + + "Deferred they leave the rendering layers target unwritten and deferred lighting skips them. Add " + + "#include_with_pragmas \"Packages/com.unity.render-pipelines.universal/ShaderLibrary/RenderingLayers.hlsl\" " + + "to the pass:\n" + string.Join("\n", missing)); + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/GBufferRenderingLayersTests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Editor/GBufferRenderingLayersTests.cs.meta new file mode 100644 index 00000000000..0b8651424d9 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/GBufferRenderingLayersTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5d2ed4d1fc144e858d6c2ea194f8fe4e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/GlobalConstantBufferShaderDefineTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/GlobalConstantBufferShaderDefineTests.cs deleted file mode 100644 index 7b1e74620eb..00000000000 --- a/Packages/com.unity.render-pipelines.universal/Tests/Editor/GlobalConstantBufferShaderDefineTests.cs +++ /dev/null @@ -1,38 +0,0 @@ -using NUnit.Framework; -using static UnityEditor.Rendering.Universal.GlobalConstantBufferShaderDefine; - -// Target Decide rather than Reconcile: acting on the decision calls SetShaderBuildSettings, which reimports every -// shader in the project and mutates global editor state. -namespace UnityEditor.Rendering.Universal.Tests -{ - class GlobalConstantBufferShaderDefineTests - { - [Test] - public void Wanted_DefineMissing_IsAdded() - { - Assert.That(Decide(wanted: true, hasDefine: false), Is.EqualTo(DefineAction.Add)); - } - - [Test] - public void NotWanted_DefinePresent_IsRemoved() - { - Assert.That(Decide(wanted: false, hasDefine: true), Is.EqualTo(DefineAction.Remove)); - } - - [Test] - public void Wanted_DefineAlreadyPresent_NoWriteNeeded() - { - Assert.That(Decide(wanted: true, hasDefine: true), Is.EqualTo(DefineAction.None), - "Writing the shader build settings back reimports every shader in the project, so a state that is " - + "already correct must not write."); - } - - [Test] - public void NotWanted_DefineAbsent_NoWriteNeeded() - { - Assert.That(Decide(wanted: false, hasDefine: false), Is.EqualTo(DefineAction.None), - "Writing the shader build settings back reimports every shader in the project, so a state that is " - + "already correct must not write."); - } - } -} diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/GlobalConstantBufferShaderDefineTests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Editor/GlobalConstantBufferShaderDefineTests.cs.meta deleted file mode 100644 index f4bf128774c..00000000000 --- a/Packages/com.unity.render-pipelines.universal/Tests/Editor/GlobalConstantBufferShaderDefineTests.cs.meta +++ /dev/null @@ -1,2 +0,0 @@ -fileFormatVersion: 2 -guid: 5cac8bf56598c4c0084b77b5cc5e51d1 diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/GlobalShaderVariablesLayoutTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/GlobalShaderVariablesLayoutTests.cs index c1dc33cfb12..67176eb0b50 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Editor/GlobalShaderVariablesLayoutTests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/GlobalShaderVariablesLayoutTests.cs @@ -6,6 +6,7 @@ using System.Text.RegularExpressions; using NUnit.Framework; using UnityEngine; +using UnityEngine.Experimental.Rendering; using UnityEngine.Rendering.Universal; // GlobalShaderVariables and its sub-structs mirror an HLSL constant buffer layout, so they must obey the packing @@ -18,6 +19,9 @@ class GlobalShaderVariablesLayoutTests // A cbuffer is addressed as an array of float4 registers. const int k_RegisterSize = 16; + // The cache line size guideline 5 in GlobalShaderVariables.cs lays the matrices out for. + const int k_CacheLineSize = 64; + static readonly BindingFlags k_FieldFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly; @@ -61,8 +65,8 @@ class GlobalShaderVariablesLayoutTests // Integer defines of that same file, the only thing an array length is allowed to reference. static readonly Regex k_HlslDefine = new Regex(@"^#define\s+(\w+)\s+(\d+)\s*$"); - // The shader define selecting the persistent constant buffer, so the layout the hlsl is read for. - const string k_PersistentConstantBuffersDefine = "URP_GLOBAL_CONSTANT_BUFFER"; + // The define URP declares its global constant buffer under, so the layout the hlsl is read for. + const string k_GlobalConstantBufferDefine = "URP_GLOBAL_CONSTANT_BUFFER_ACTIVE"; [Test] public void FieldTypesAreConstantBufferSafe([ValueSource(nameof(k_LayoutTypes))] Type layoutType) @@ -101,6 +105,23 @@ public void NoFieldStraddlesRegisterBoundary([ValueSource(nameof(k_LayoutTypes)) }); } + // Guideline 5 starts every matrix on a cache line, so that a lit draw reads each main light shadow cascade from a + // single line. A register added or removed before them breaks that without any compile or packing error, only the + // GPU time shows it. The offset counts from the start of the buffer, so the check runs on GlobalShaderVariables. + [Test] + public void MatricesStartOnCacheLineBoundary() + { + ForEachLeafField(typeof(GlobalShaderVariables), 0, (field, offset) => + { + if (field.FieldType == typeof(Matrix4x4)) + { + Assert.That(offset % k_CacheLineSize, Is.Zero, + $"{field.DeclaringType.Name}.{field.Name} is a Matrix4x4 at offset {offset}, it must start on a {k_CacheLineSize}-byte boundary. " + + $"Keep the number of registers before it a multiple of {k_CacheLineSize / k_RegisterSize}, see guideline 5 in GlobalShaderVariables.cs."); + } + }); + } + // A field with no bit would never be pushed after the first ResetToDefault, and a bit with no field is dead. // Neither shows up as a compile error, so the correspondence is checked here instead. [TestCase(typeof(GlobalShaderVariablesBase), typeof(GlobalShaderVariablesBaseDirty))] @@ -176,6 +197,133 @@ public void DirtyFlagsAreDistinctPowersOfTwo(Type dirtyType) } } + // The variables that describe what URP binds or configures (light lists, shadow maps and their PCSS filtering, + // cookies, probe volumes, rendering layers, dithering texture) are read-only on the public interfaces: render graph + // passes read them, and URP writes them through GlobalShaderVariablesUploader. Opening or closing a setter is an + // API decision, so it must be made here as well. + static readonly HashSet k_ReadOnlyOnInterfaces = new HashSet + { + nameof(IGlobalShaderVariablesOnly3DUploader._FPParams0), + nameof(IGlobalShaderVariablesOnly3DUploader._FPParams1), + nameof(IGlobalShaderVariablesOnly3DUploader._FPParams2), + nameof(IGlobalShaderVariablesOnly3DUploader._AdditionalLightsCount), + nameof(IGlobalShaderVariablesOnly3DUploader._MainLightShadowOffset0), + nameof(IGlobalShaderVariablesOnly3DUploader._MainLightShadowOffset1), + nameof(IGlobalShaderVariablesOnly3DUploader._MainLightShadowmapSize), + nameof(IGlobalShaderVariablesOnly3DUploader._MainLightPCSSParams0), + nameof(IGlobalShaderVariablesOnly3DUploader._MainLightPCSSParams1), + nameof(IGlobalShaderVariablesOnly3DUploader._MainLightPCSSScalars), + nameof(IGlobalShaderVariablesOnly3DUploader._AdditionalShadowOffset0), + nameof(IGlobalShaderVariablesOnly3DUploader._AdditionalShadowOffset1), + nameof(IGlobalShaderVariablesOnly3DUploader._AdditionalShadowmapSize), + nameof(IGlobalShaderVariablesOnly3DUploader._MainLightCookieTextureFormat), + nameof(IGlobalShaderVariablesOnly3DUploader._AdditionalLightsCookieAtlasTextureFormat), + nameof(IGlobalShaderVariablesOnly3DUploader._RenderingLayerMaxInt), + nameof(IGlobalShaderVariablesOnly3DUploader._EnableProbeVolumes), + nameof(IGlobalShaderVariablesBaseUploader._DitheringTextureInvSize), + }; + + // A field with no property still packs, has its bit and its hlsl declaration, so nothing fails, but render graph + // passes cannot read it. Every pushable field must be a property of the same name and type on the public interface + // of its group, with a getter, and a setter unless k_ReadOnlyOnInterfaces lists it, and every property of that + // interface must be a field. GlobalShaderVariablesUploader must have a setter for every one of them. + [TestCase(typeof(GlobalShaderVariablesBase), typeof(IGlobalShaderVariablesBaseUploader))] + // URP 2D-only globals, empty so disabled. + // [TestCase(typeof(GlobalShaderVariablesOnly2D), typeof(IGlobalShaderVariablesOnly2DUploader))] + [TestCase(typeof(GlobalShaderVariablesOnly3D), typeof(IGlobalShaderVariablesOnly3DUploader))] + public void EveryFieldHasAPropertyOnItsInterface(Type layoutType, Type interfaceType) + { + var fields = new HashSet(); + foreach (var field in layoutType.GetFields(k_FieldFlags)) + { + if (!field.Name.StartsWith("_URPPadding", StringComparison.Ordinal)) + fields.Add($"{field.FieldType.Name} {field.Name}"); + } + + var properties = new HashSet(); + foreach (var property in interfaceType.GetProperties()) + { + bool readOnly = k_ReadOnlyOnInterfaces.Contains(property.Name); + Assert.That(property.CanRead, Is.True, + $"{interfaceType.Name}.{property.Name} needs a getter, like every other variable."); + Assert.That(property.CanWrite, Is.EqualTo(!readOnly), readOnly + ? $"{interfaceType.Name}.{property.Name} is read-only on the interface, see k_ReadOnlyOnInterfaces." + : $"{interfaceType.Name}.{property.Name} needs a setter, like every variable k_ReadOnlyOnInterfaces doesn't list."); + + PropertyInfo uploaderProperty = typeof(GlobalShaderVariablesUploader).GetProperty(property.Name); + Assert.That(uploaderProperty != null && uploaderProperty.CanWrite, Is.True, + $"GlobalShaderVariablesUploader.{property.Name} needs a setter: URP fills every variable through it."); + + properties.Add($"{property.PropertyType.Name} {property.Name}"); + } + + Assert.That(properties, Is.EquivalentTo(fields), + $"{interfaceType.Name} and {layoutType.Name} have drifted apart. Every pushable field needs a property " + + "of the same name and type, and every property a field."); + } + + // A setter writing the wrong field or marking the wrong bit compiles and passes every test above, and its variable + // stays stale on the GPU. Each property is written here through its interface on a fresh uploader, or through the + // uploader when it is read-only on the interface: it must read back what was written, and change only the field and + // the bit of its own name. + [TestCase(typeof(IGlobalShaderVariablesBaseUploader), nameof(GlobalShaderVariables.varsBase))] + // URP 2D-only globals, empty so disabled. + // [TestCase(typeof(IGlobalShaderVariablesOnly2DUploader), nameof(GlobalShaderVariables.vars2D))] + [TestCase(typeof(IGlobalShaderVariablesOnly3DUploader), nameof(GlobalShaderVariables.vars3D))] + public void EveryPropertyWritesItsFieldAndItsDirtyFlag(Type interfaceType, string groupName) + { + var stagingVars = typeof(GlobalShaderVariablesUploader).GetField("m_StagingVars", BindingFlags.NonPublic | BindingFlags.Instance); + var stagingDirty = typeof(GlobalShaderVariablesUploader).GetField("m_StagingDirty", BindingFlags.NonPublic | BindingFlags.Instance); + Assert.That(stagingVars, Is.Not.Null, "GlobalShaderVariablesUploader.m_StagingVars was renamed, update this test."); + Assert.That(stagingDirty, Is.Not.Null, "GlobalShaderVariablesUploader.m_StagingDirty was renamed, update this test."); + + FieldInfo group = typeof(GlobalShaderVariables).GetField(groupName, k_FieldFlags); + FieldInfo groupDirty = typeof(GlobalShaderVariablesDirty).GetField(groupName, k_FieldFlags); + + foreach (var property in interfaceType.GetProperties()) + { + PropertyInfo setter = property.CanWrite ? property : typeof(GlobalShaderVariablesUploader).GetProperty(property.Name); + var uploader = new GlobalShaderVariablesUploader(GlobalShaderVariablesGroup.All); + object value = NonDefaultValueOf(property.PropertyType); + setter.SetValue(uploader, value); + + Assert.That(property.GetValue(uploader), Is.EqualTo(value), + $"{interfaceType.Name}.{property.Name} does not read back what was written."); + + object expectedVars = Activator.CreateInstance(group.FieldType); + group.FieldType.GetField(property.Name, k_FieldFlags).SetValue(expectedVars, value); + Assert.That(group.GetValue(stagingVars.GetValue(uploader)), Is.EqualTo(expectedVars), + $"{interfaceType.Name}.{property.Name} must write the {group.FieldType.Name} field of the same name, and only that one."); + + object expectedDirty = new GlobalShaderVariablesDirty(); + groupDirty.SetValue(expectedDirty, Enum.Parse(groupDirty.FieldType, property.Name)); + Assert.That(stagingDirty.GetValue(uploader), Is.EqualTo(expectedDirty), + $"{interfaceType.Name}.{property.Name} must mark the {groupDirty.FieldType.Name} bit of the same name, and only that one."); + } + } + + // A value no field holds on a fresh uploader, so a setter writing the wrong field cannot pass by chance. + static object NonDefaultValueOf(Type type) + { + if (type == typeof(int)) return 3; + if (type == typeof(uint)) return 3u; + if (type == typeof(float)) return 1.5f; + if (type == typeof(Vector2)) return new Vector2(1f, 2f); + if (type == typeof(Vector2Int)) return new Vector2Int(1, 2); + if (type == typeof(Vector4)) return new Vector4(1f, 2f, 3f, 4f); + if (type == typeof(Matrix4x4)) + return new Matrix4x4(new Vector4(1f, 2f, 3f, 4f), new Vector4(5f, 6f, 7f, 8f), new Vector4(9f, 10f, 11f, 12f), new Vector4(13f, 14f, 15f, 16f)); + + // The structs standing for an hlsl array, like MainLightShadowMatrices. + Assert.That(IsNestedLayoutStruct(type), Is.True, $"No test value for {type.Name}, add one to NonDefaultValueOf()."); + + object value = Activator.CreateInstance(type); + foreach (var field in type.GetFields(k_FieldFlags)) + field.SetValue(value, NonDefaultValueOf(field.FieldType)); + + return value; + } + // The hlsl and these structs are two hand-maintained copies of one cbuffer layout. A rename or reorder in // either compiles cleanly on both sides and silently feeds shaders the wrong register [Test] @@ -218,8 +366,8 @@ static List ParseHlslDeclarations() var defines = new Dictionary(); // A member can be declared once per branch of a conditional, when only its precision changes. The layout - // read here is the one the persistent constant buffer mode compiles, so the branch taken is the one that - // mode selects. Conditions are tracked as a stack because of the include guard wrapping the whole file. + // read here is the one declared under URP_GLOBAL_CONSTANT_BUFFER_ACTIVE, so the branch taken is the one that + // define selects. Conditions are tracked as a stack because of the include guard wrapping the whole file. var conditions = new List(); bool skipping = false; @@ -246,16 +394,16 @@ static List ParseHlslDeclarations() else if (trimmed.StartsWith("#elif", StringComparison.Ordinal)) { Assert.Fail("GlobalShaderVariables.hlsl uses #elif, which this parser cannot attribute to a " + - "branch. Declare the layout under a plain #if on URP_GLOBAL_CONSTANT_BUFFER instead."); + $"branch. Declare the layout under a plain #if on {k_GlobalConstantBufferDefine} instead."); } else if (trimmed.StartsWith("#else", StringComparison.Ordinal)) { - // Only the persistent constant buffer condition has a known answer here, so anything else + // Only the URP_GLOBAL_CONSTANT_BUFFER_ACTIVE condition has a known answer here, so anything else // would leave the layout ambiguous instead of silently picking one of the two branches. Assert.That(conditions.Count, Is.GreaterThan(0), "GlobalShaderVariables.hlsl has an #else without a matching #if."); - Assert.That(conditions[conditions.Count - 1], Does.Contain(k_PersistentConstantBuffersDefine), + Assert.That(conditions[conditions.Count - 1], Does.Contain(k_GlobalConstantBufferDefine), $"GlobalShaderVariables.hlsl declares members under '{conditions[conditions.Count - 1]}', whose #else branch " + - $"cannot be resolved. Only a conditional on {k_PersistentConstantBuffersDefine} may hold two versions of a member."); + $"cannot be resolved. Only a conditional on {k_GlobalConstantBufferDefine} may hold two versions of a member."); skipping = true; } @@ -369,9 +517,9 @@ static void ForEachLeafField(Type layoutType, int baseOffset, Action type.IsValueType && !type.IsPrimitive && !type.IsEnum - && type.Namespace == typeof(GlobalShaderVariables).Namespace; + && type.Assembly == typeof(GlobalShaderVariables).Assembly; } } \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/GlobalShaderVariablesUploaderTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/GlobalShaderVariablesUploaderTests.cs index d40138093b3..61cea46936c 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Editor/GlobalShaderVariablesUploaderTests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/GlobalShaderVariablesUploaderTests.cs @@ -3,8 +3,10 @@ using System.Reflection; using NUnit.Framework; using UnityEngine; +using UnityEngine.Experimental.Rendering; using UnityEngine.Rendering; using UnityEngine.Rendering.Universal; +using UnityEngine.TestTools; // GlobalShaderVariablesUploader only re-uploads the variables whose accessors were used since the last push. // A regression there is silent: too few pushes leave stale uniforms on the GPU, too many just cost CPU. Neither @@ -156,7 +158,7 @@ GlobalShaderVariablesUploader CreateFlushedUploader(GlobalShaderVariablesGroup g { var uploader = new GlobalShaderVariablesUploader(groups); uploader.ResetToDefault(); - uploader.PushGlobal(m_Cmd); + uploader.Push(m_Cmd); return uploader; } @@ -194,7 +196,7 @@ static void FillBaseDefaults(GlobalShaderVariablesUploader uploader) } [Test] - public void PushGlobal_AfterResetToDefault_PushesEveryVariable( + public void Push_AfterResetToDefault_PushesEveryVariable( [Values(GlobalShaderVariablesGroup.Base | GlobalShaderVariablesGroup.Only3D, GlobalShaderVariablesGroup.Base | GlobalShaderVariablesGroup.Only2D)] GlobalShaderVariablesGroup groups) { @@ -202,16 +204,85 @@ public void PushGlobal_AfterResetToDefault_PushesEveryVariable( FillBaseDefaults(uploader); uploader.ResetToDefault(); - Assert.That(Recorded(cmd => uploader.PushGlobal(cmd)), Is.EqualTo(CostOfFullPush()), + Assert.That(Recorded(cmd => uploader.Push(cmd)), Is.EqualTo(CostOfFullPush()), "ResetToDefault must mark everything the frame uses dirty."); } [Test] - public void PushGlobal_WithNoPendingChange_RecordsNothing() + public void PushAfterCameraSetup_LooseUniforms_PushesTheStagedValuesTheSetupOverwrote() + { + var uploader = new GlobalShaderVariablesUploader(GlobalShaderVariablesGroup.Base); + FillBaseDefaults(uploader); + uploader.PushDefault(m_Cmd); + + // A pass pushes a value of its own, which the camera setup must not drop. + var pushed = new Vector4(5f, 6f, 7f, 8f); + uploader._ScreenParams = pushed; + uploader.Push(m_Cmd); + + Assert.That(Recorded(cmd => uploader.PushAfterCameraSetup(cmd)), Is.EqualTo(CostOfPushes(7)), + "The native camera setup overwrites 7 base variables, and only those are pushed again."); + Assert.That(uploader._ScreenParams, Is.EqualTo(pushed), "The staged value is kept, not reset to the camera's."); + Assert.That(Recorded(cmd => uploader.Push(cmd)), Is.Zero, "Nothing is left pending."); + } + + [Test] + public void PushAfterCameraSetup_LooseUniforms_SendsTheStagedValueNotTheCameraDefault() + { + int screenParamsID = Shader.PropertyToID("_ScreenParams"); + Vector4 saved = Shader.GetGlobalVector(screenParamsID); + try + { + var uploader = new GlobalShaderVariablesUploader(GlobalShaderVariablesGroup.Base); + FillBaseDefaults(uploader); + uploader.PushDefault(m_Cmd); + + // A pass pushes a value of its own, then the engine's camera setup overwrites the loose uniform. + var pushed = new Vector4(5f, 6f, 7f, 8f); + uploader._ScreenParams = pushed; + uploader.Push(m_Cmd); + m_NativeCmd.SetGlobalVector(screenParamsID, new Vector4(-1f, -1f, -1f, -1f)); + + uploader.PushAfterCameraSetup(m_Cmd); + ExecuteTestCmd(); + + Assert.That(Shader.GetGlobalVector(screenParamsID), Is.EqualTo(pushed), + "The value the pass pushed comes back after the camera setup, not the camera's."); + } + finally + { + Shader.SetGlobalVector(screenParamsID, saved); + } + } + + [Test] + public void PushAfterCameraSetup_ConstantBufferMode_RecordsNothing() + { + var uploader = CreateConstantBufferUploader(); + uploader.PushDefault(m_Cmd); + + Assert.That(Recorded(cmd => uploader.PushAfterCameraSetup(cmd)), Is.Zero, + "The native camera setup writes loose uniforms only: the bound buffer still holds the staged values."); + } + + [Test] + public void PushAfterCameraSetup_WithATemporaryCopyLeftOpen_Throws([Values] bool constantBuffer) + { + var uploader = constantBuffer ? CreateConstantBufferUploader() : CreateFlushedUploader(); + var leaked = uploader.Get(); + leaked._ScreenSize = k_TemporaryScreenSize; + leaked.Push(m_Cmd); + + Assert.Throws(() => uploader.PushAfterCameraSetup(m_Cmd), + "Like the other pushes of the staged variables, the one after the camera setup finds the copy still open."); + } + + [Test] + public void Push_WithNoPendingChange_RecordsNothing() { var uploader = CreateFlushedUploader(); - Assert.That(Recorded(cmd => uploader.PushGlobal(cmd)), Is.Zero, + Assert.That(Recorded(cmd => uploader.Push(cmd)), Is.Zero, "Pushing twice in a row must not re-send anything."); } @@ -222,7 +293,7 @@ public void Setter_MarksOnlyItsOwnVariable() uploader._ScreenSize = new Vector4(1920f, 1080f, 1f / 1920f, 1f / 1080f); - Assert.That(Recorded(cmd => uploader.PushGlobal(cmd)), Is.EqualTo(CostOfPushes(1)), + Assert.That(Recorded(cmd => uploader.Push(cmd)), Is.EqualTo(CostOfPushes(1)), "Assigning one variable must push exactly that one."); } @@ -235,7 +306,7 @@ public void Setters_AccumulateUntilPushed() uploader._ZBufferParams = new Vector4(5f, 6f, 7f, 8f); uploader._GlobalMipBias = new Vector2(-1f, 0.5f); - Assert.That(Recorded(cmd => uploader.PushGlobal(cmd)), Is.EqualTo(CostOfPushes(3)), + Assert.That(Recorded(cmd => uploader.Push(cmd)), Is.EqualTo(CostOfPushes(3)), "Every variable touched since the last push must be sent, and only those."); } @@ -247,21 +318,21 @@ public void Setter_AssignedTwice_PushesOnce() uploader._Time = new Vector4(1f, 2f, 3f, 4f); uploader._Time = new Vector4(5f, 6f, 7f, 8f); - Assert.That(Recorded(cmd => uploader.PushGlobal(cmd)), Is.EqualTo(CostOfPushes(1)), + Assert.That(Recorded(cmd => uploader.Push(cmd)), Is.EqualTo(CostOfPushes(1)), "Flags are a set, not a counter."); } [Test] - public void PushGlobal_ClearsFlags_SoNextChangePushesAlone() + public void Push_ClearsFlags_SoNextChangePushesAlone() { var uploader = CreateFlushedUploader(); uploader._Time = new Vector4(1f, 2f, 3f, 4f); - uploader.PushGlobal(m_Cmd); + uploader.Push(m_Cmd); uploader._ScreenParams = new Vector4(9f, 9f, 9f, 9f); - Assert.That(Recorded(cmd => uploader.PushGlobal(cmd)), Is.EqualTo(CostOfPushes(1)), + Assert.That(Recorded(cmd => uploader.Push(cmd)), Is.EqualTo(CostOfPushes(1)), "A pushed variable must not be pushed again by the following push."); } @@ -277,29 +348,29 @@ public void Setter_RoundTripsThroughStaging() } [Test] - public void PushDefaultToGlobal_DiscardsLocalChanges() + public void PushDefault_DiscardsLocalChanges() { var uploader = new GlobalShaderVariablesUploader(GlobalShaderVariablesGroup.All); FillBaseDefaults(uploader); uploader._Time = new Vector4(99f, 99f, 99f, 99f); - uploader.PushDefaultToGlobal(m_Cmd); + uploader.PushDefault(m_Cmd); Assert.That(uploader._Time, Is.EqualTo(k_DefaultTime), - "PushDefaultToGlobal re-baselines staging onto the frame defaults."); + "PushDefault re-baselines staging onto the frame defaults."); } [Test] - public void PushDefaultToGlobal_RepushesEverythingEvenWhenOnlyOneVariableChanged() + public void PushDefault_RepushesEverythingEvenWhenOnlyOneVariableChanged() { var uploader = new GlobalShaderVariablesUploader(GlobalShaderVariablesGroup.All); FillBaseDefaults(uploader); - uploader.PushDefaultToGlobal(m_Cmd); + uploader.PushDefault(m_Cmd); uploader._Time = new Vector4(1f, 2f, 3f, 4f); - Assert.That(Recorded(cmd => uploader.PushDefaultToGlobal(cmd)), Is.EqualTo(CostOfFullPush()), + Assert.That(Recorded(cmd => uploader.PushDefault(cmd)), Is.EqualTo(CostOfFullPush()), "It runs right after cmd.SetupCameraProperties, which overwrites part of these globals behind our " + "back, so it must not trust staging and has to re-send all of them."); } @@ -317,47 +388,47 @@ GlobalShaderVariablesUploader CreateConstantBufferUploader() } [Test] - public void PushDefaultToGlobal_ConstantBufferMode_UploadsDefaultsOnceThenRecordsNothing() + public void PushDefault_ConstantBufferMode_UploadsDefaultsOnceThenRecordsNothing() { var uploader = CreateConstantBufferUploader(); - Assert.That(Recorded(cmd => uploader.PushDefaultToGlobal(cmd)), Is.EqualTo(CostOfUploadAndBind()), + Assert.That(Recorded(cmd => uploader.PushDefault(cmd)), Is.EqualTo(CostOfUploadAndBind()), "The first push of a camera has to get the frozen defaults onto the GPU."); - Assert.That(Recorded(cmd => uploader.PushDefaultToGlobal(cmd)), Is.Zero, + Assert.That(Recorded(cmd => uploader.PushDefault(cmd)), Is.Zero, "The defaults buffer already holds exactly what an upload would write and still owns the slot, so " + "both the upload and the bind are pure waste."); } [Test] - public void PushGlobal_ConstantBufferMode_OverrideDoesNotInvalidateDefaults() + public void Push_ConstantBufferMode_OverrideDoesNotInvalidateDefaults() { var uploader = CreateConstantBufferUploader(); - uploader.PushDefaultToGlobal(m_Cmd); + uploader.PushDefault(m_Cmd); uploader._Time = new Vector4(99f, 99f, 99f, 99f); - Assert.That(Recorded(cmd => uploader.PushGlobal(cmd)), Is.EqualTo(CostOfUploadAndBind()), + Assert.That(Recorded(cmd => uploader.Push(cmd)), Is.EqualTo(CostOfUploadAndBind()), "A diverged staging cannot be served by the defaults buffer, it goes to the overrides one."); - Assert.That(Recorded(cmd => uploader.PushDefaultToGlobal(cmd)), Is.EqualTo(CostOfBind()), + Assert.That(Recorded(cmd => uploader.PushDefault(cmd)), Is.EqualTo(CostOfBind()), "The override wrote to the other buffer, so the defaults are still resident and only need a rebind."); } [Test] - public void PushGlobal_ConstantBufferMode_OverrideAfterASkippedPushStillCostsTheDefaultsTheirBind() + public void Push_ConstantBufferMode_OverrideAfterASkippedPushStillCostsTheDefaultsTheirBind() { var uploader = CreateConstantBufferUploader(); - uploader.PushDefaultToGlobal(m_Cmd); + uploader.PushDefault(m_Cmd); // A defaults push records nothing while its buffer is up to date and still bound. That skip must not be // read as "the slot is ours forever": the override below takes it over. - uploader.PushDefaultToGlobal(m_Cmd); + uploader.PushDefault(m_Cmd); uploader._Time = new Vector4(99f, 99f, 99f, 99f); - uploader.PushGlobal(m_Cmd); + uploader.Push(m_Cmd); - Assert.That(Recorded(cmd => uploader.PushDefaultToGlobal(cmd)), Is.EqualTo(CostOfBind()), + Assert.That(Recorded(cmd => uploader.PushDefault(cmd)), Is.EqualTo(CostOfBind()), "Whatever was skipped in between, the slot holds the override buffer and has to be bound back."); } @@ -365,12 +436,12 @@ public void PushGlobal_ConstantBufferMode_OverrideAfterASkippedPushStillCostsThe public void EndFill_ConstantBufferMode_InvalidatesTheUploadedDefaults() { var uploader = CreateConstantBufferUploader(); - uploader.PushDefaultToGlobal(m_Cmd); + uploader.PushDefault(m_Cmd); // Next camera of the frame: same uploader, new defaults. FillBaseDefaults(uploader); - Assert.That(Recorded(cmd => uploader.PushDefaultToGlobal(cmd)), Is.EqualTo(CostOfUploadAndBind()), + Assert.That(Recorded(cmd => uploader.PushDefault(cmd)), Is.EqualTo(CostOfUploadAndBind()), "Rebinding here would bind the previous camera's values, the new defaults must reach the GPU first."); } @@ -378,31 +449,572 @@ public void EndFill_ConstantBufferMode_InvalidatesTheUploadedDefaults() public void Release_ConstantBufferMode_ForcesAReuploadOnTheNextPush() { var uploader = CreateConstantBufferUploader(); - uploader.PushDefaultToGlobal(m_Cmd); + uploader.PushDefault(m_Cmd); uploader.Release(); - Assert.That(Recorded(cmd => uploader.PushDefaultToGlobal(cmd)), Is.EqualTo(CostOfUploadAndBind()), + Assert.That(Recorded(cmd => uploader.PushDefault(cmd)), Is.EqualTo(CostOfUploadAndBind()), "The buffer holding the defaults is gone, whatever replaces it starts empty."); } [Test] - public void PushGlobal_ConstantBufferMode_WithNoPendingChange_RecordsNothing() + public void Push_ConstantBufferMode_WithNoPendingChange_RecordsNothing() { var uploader = CreateConstantBufferUploader(); - uploader.PushDefaultToGlobal(m_Cmd); + uploader.PushDefault(m_Cmd); - Assert.That(Recorded(cmd => uploader.PushGlobal(cmd)), Is.Zero, + Assert.That(Recorded(cmd => uploader.Push(cmd)), Is.Zero, "Nothing was staged since the last push, so there is no reason to rebind either."); } [Test] - public void PushDefaultToGlobal_ConstantBufferMode_UploadsEveryGroupEvenWhenOnlyOneIsAsked() + public void PushDefault_ConstantBufferMode_UploadsEveryGroupEvenWhenOnlyOneIsAsked() { var uploader = CreateConstantBufferUploader(); - Assert.That(Recorded(cmd => uploader.PushDefaultToGlobal(cmd, GlobalShaderVariablesGroup.Base)), Is.EqualTo(CostOfUploadAndBind()), + Assert.That(Recorded(cmd => uploader.PushDefault(cmd, GlobalShaderVariablesGroup.Base)), Is.EqualTo(CostOfUploadAndBind()), "A constant buffer is uploaded as a whole: group filtering cannot make the push any cheaper."); } + + // Temporary copies (Get). A temporary copy records its restore into the command buffer it was made with, + // so these tests measure what one step records on m_Cmd rather than on a fresh buffer. Emptied first: the payload + // of an upload is aligned within the buffer, so only steps recorded from its start compare with the probes. + int RecordedOnTestCmd(Action action) + { + m_NativeCmd.Clear(); + int before = m_NativeCmd.sizeInBytes; + action(); + return m_NativeCmd.sizeInBytes - before; + } + + // Runs what was recorded so far, so the global values it set can be read back with Shader.GetGlobalVector. + void ExecuteTestCmd() + { + Graphics.ExecuteCommandBuffer(m_NativeCmd); + m_NativeCmd.Clear(); + } + + static readonly int k_ScreenSizeID = Shader.PropertyToID("_ScreenSize"); + static readonly Vector4 k_StagedScreenSize = new Vector4(640f, 360f, 1f / 640f, 1f / 360f); + static readonly Vector4 k_TemporaryScreenSize = new Vector4(256f, 256f, 1f / 256f, 1f / 256f); + + // Two compute shaders of the package, only used as targets of the recorded commands. + static ComputeShader LoadComputeShader(string name) => + AssetDatabase.LoadAssetAtPath($"Packages/com.unity.render-pipelines.universal/Runtime/MipGen/Shaders/{name}.compute"); + + // The same commands PushToCompute() records, as one sequence from the start of a fresh buffer. + static int CostOfUploadAndComputeBind(ComputeShader computeShader) + { + using var probe = new CommandBuffer(); + var constantBuffer = new ConstantBuffer(ComputeBufferMode.Dynamic); + + int before = probe.sizeInBytes; + constantBuffer.UpdateData(probe, default(GlobalShaderVariables)); + constantBuffer.Set(probe, computeShader, k_ProbeConstantBufferID); + int cost = probe.sizeInBytes - before; + + constantBuffer.Release(); + return cost; + } + + // What Dispose() records to unbind one compute shader: a null buffer removes its binding. + static int CostOfComputeUnbind(ComputeShader computeShader) + { + using var probe = new CommandBuffer(); + int before = probe.sizeInBytes; + probe.SetComputeConstantBufferParam(computeShader, k_ProbeConstantBufferID, (GraphicsBuffer)null, 0, 0); + return probe.sizeInBytes - before; + } + + [Test] + public void Get_StartsFromTheStagedValues() + { + var uploader = CreateFlushedUploader(); + uploader._ScreenSize = k_StagedScreenSize; + uploader.Push(m_Cmd); + + using var temporary = uploader.Get(); + + Assert.That(temporary._ScreenSize, Is.EqualTo(k_StagedScreenSize), + "A temporary copy reads what the passes before it staged, not the camera defaults."); + } + + [Test] + public void TemporaryFirstPush_LooseUniforms_PushesThePendingStagedValuesFirst() + { + var uploader = CreateFlushedUploader(); + uploader._ScreenSize = k_StagedScreenSize; + var temporary = uploader.Get(); + temporary._Time = new Vector4(1f, 2f, 3f, 4f); + + Assert.That(RecordedOnTestCmd(() => temporary.Push(m_Cmd)), Is.EqualTo(CostOfPushes(2)), + "Dispose() puts back what the GPU held, so the pending staged value goes out with the first push."); + Assert.That(RecordedOnTestCmd(() => temporary.Push(m_Cmd)), Is.Zero, "Only the first push sends it."); + + ((IDisposable)temporary).Dispose(); + Assert.That(Recorded(cmd => uploader.Push(cmd)), Is.Zero, "Nothing is left pending on the staged values."); + } + + [Test] + public void TemporaryWithoutPush_ConstantBufferMode_LeavesThePendingChangeToTheParent() + { + var uploader = CreateConstantBufferUploader(); + uploader.PushDefault(m_Cmd); + uploader._ScreenSize = k_StagedScreenSize; + + var temporary = uploader.Get(); + Assert.That(RecordedOnTestCmd(() => ((IDisposable)temporary).Dispose()), Is.Zero, + "The copy bound nothing, so there is nothing to put back: no global command on async compute."); + Assert.That(Recorded(cmd => uploader.Push(cmd)), Is.EqualTo(CostOfUploadAndBind()), + "The pending change is still the parent's, pushed by its next push."); + } + + [Test] + public void TemporaryDispose_RecordsOnTheCommandBufferOfTheLastPush() + { + var uploader = CreateFlushedUploader(); + var temporary = uploader.Get(); + temporary._ScreenSize = k_TemporaryScreenSize; + temporary.Push(m_Cmd); + + using var other = new CommandBuffer(); + temporary.Push(CommandBufferHelpers.GetRasterCommandBuffer(other)); + + Assert.That(RecordedOnTestCmd(() => ((IDisposable)temporary).Dispose()), Is.Zero); + Assert.That(other.sizeInBytes, Is.EqualTo(CostOfPushes(1)), + "Dispose() has no command buffer of its own: it puts back on the one of the last push."); + } + + [Test] + public void TemporaryPush_LooseUniforms_IsUndoneByDispose() + { + Vector4 saved = Shader.GetGlobalVector(k_ScreenSizeID); + try + { + var uploader = new GlobalShaderVariablesUploader(GlobalShaderVariablesGroup.Base | GlobalShaderVariablesGroup.Only3D); + FillBaseDefaults(uploader); + uploader.PushDefault(m_Cmd); + + // A persistent change made by an earlier pass, like the upscaler does for _ScreenSize. + uploader._ScreenSize = k_StagedScreenSize; + uploader.Push(m_Cmd); + + using (var temporary = uploader.Get()) + { + temporary._ScreenSize = k_TemporaryScreenSize; + temporary.Push(m_Cmd); + + ExecuteTestCmd(); + Assert.That(Shader.GetGlobalVector(k_ScreenSizeID), Is.EqualTo(k_TemporaryScreenSize), + "The draws of the pass read the temporary value."); + } + + ExecuteTestCmd(); + Assert.That(Shader.GetGlobalVector(k_ScreenSizeID), Is.EqualTo(k_StagedScreenSize), + "Dispose() restores the value staged before Get(), not the camera default: the earlier pass meant it."); + Assert.That(uploader._ScreenSize, Is.EqualTo(k_StagedScreenSize), + "Temporary changes never reach the staged values."); + } + finally + { + Shader.SetGlobalVector(k_ScreenSizeID, saved); + } + } + + [Test] + public void TemporaryDispose_LooseUniforms_RestoresOnlyWhatTheTemporaryCopyPushed() + { + var uploader = CreateFlushedUploader(); + var temporary = uploader.Get(); + + temporary._Time = new Vector4(1f, 2f, 3f, 4f); + temporary._ScreenSize = k_TemporaryScreenSize; + temporary.Push(m_Cmd); + + // Changed but never pushed: the GPU never saw it, there is nothing to put back. + temporary._ZBufferParams = new Vector4(5f, 6f, 7f, 8f); + + Assert.That(RecordedOnTestCmd(() => ((IDisposable)temporary).Dispose()), Is.EqualTo(CostOfPushes(2))); + Assert.That(Recorded(cmd => uploader.Push(cmd)), Is.Zero, + "Nothing the temporary copy did is pending on the staged values."); + } + + [Test] + public void TemporaryDispose_WithoutAnyPush_RecordsNothing() + { + var uploader = CreateFlushedUploader(); + var temporary = uploader.Get(); + temporary._Time = new Vector4(1f, 2f, 3f, 4f); + + Assert.That(RecordedOnTestCmd(() => ((IDisposable)temporary).Dispose()), Is.Zero); + } + + [Test] + public void TemporaryResetToDefault_LooseUniforms_PushesTheCameraDefaultsThenDisposeRestoresTheStagedValues() + { + var uploader = new GlobalShaderVariablesUploader(GlobalShaderVariablesGroup.All); + FillBaseDefaults(uploader); + uploader.PushDefault(m_Cmd); + uploader._Time = new Vector4(99f, 99f, 99f, 99f); + uploader.Push(m_Cmd); + + var temporary = uploader.Get(); + temporary.ResetToDefault(); + + Assert.That(temporary._Time, Is.EqualTo(k_DefaultTime)); + Assert.That(RecordedOnTestCmd(() => temporary.Push(m_Cmd)), Is.EqualTo(CostOfFullPush())); + Assert.That(RecordedOnTestCmd(() => ((IDisposable)temporary).Dispose()), Is.EqualTo(CostOfFullPush())); + Assert.That(uploader._Time, Is.EqualTo(new Vector4(99f, 99f, 99f, 99f))); + } + + [Test] + public void TemporaryPushToCompute_LooseUniforms_PushesGloballyUntilDispose() + { + var computeShader = LoadComputeShader("ColorPyramid"); + var uploader = CreateFlushedUploader(); + var temporary = uploader.Get(); + temporary._ScreenSize = k_TemporaryScreenSize; + + Assert.That(RecordedOnTestCmd(() => temporary.PushToCompute(m_Cmd, computeShader)), Is.EqualTo(CostOfPushes(1)), + "Compute shaders read the global value of what they do not set, and what they set sticks to them for good."); + Assert.That(RecordedOnTestCmd(() => ((IDisposable)temporary).Dispose()), Is.EqualTo(CostOfPushes(1))); + } + + [Test] + public void TemporaryPush_ConstantBufferMode_UploadsToItsOwnBufferAndDisposeOnlyRebinds() + { + var uploader = CreateConstantBufferUploader(); + uploader.PushDefault(m_Cmd); + + var temporary = uploader.Get(); + temporary._Time = new Vector4(99f, 99f, 99f, 99f); + + Assert.That(RecordedOnTestCmd(() => temporary.Push(m_Cmd)), Is.EqualTo(CostOfUploadAndBind())); + Assert.That(RecordedOnTestCmd(() => ((IDisposable)temporary).Dispose()), Is.EqualTo(CostOfBind()), + "The temporary copy never wrote the defaults buffer, so getting them back is a bind."); + Assert.That(Recorded(cmd => uploader.PushDefault(cmd)), Is.Zero, + "The defaults buffer is uploaded and bound again, a defaults push has nothing left to do."); + } + + [Test] + public void TemporaryPush_ConstantBufferMode_KeepsTheOverridesOfEarlierPasses() + { + var uploader = CreateConstantBufferUploader(); + uploader.PushDefault(m_Cmd); + uploader._Time = new Vector4(99f, 99f, 99f, 99f); + uploader.Push(m_Cmd); + + var temporary = uploader.Get(); + temporary._ScreenSize = k_TemporaryScreenSize; + + Assert.That(RecordedOnTestCmd(() => temporary.Push(m_Cmd)), Is.EqualTo(CostOfUploadAndBind()), + "The temporary copy has its own buffer, the override buffer keeps the staged state."); + Assert.That(OverrideBufferOf(temporary), Is.Not.Null.And.Not.SameAs(OverrideBufferOf(uploader)), + "The temporary copy uploads to a buffer of its own, never to the parent's override buffer."); + Assert.That(RecordedOnTestCmd(() => ((IDisposable)temporary).Dispose()), Is.EqualTo(CostOfBind()), + "The override buffer still holds the staged state, binding it back is enough."); + Assert.That(Recorded(cmd => uploader.Push(cmd)), Is.Zero); + Assert.That(uploader._Time, Is.EqualTo(new Vector4(99f, 99f, 99f, 99f))); + Assert.That(Recorded(cmd => uploader.PushDefault(cmd)), Is.EqualTo(CostOfBind()), + "Dispose() bound the override buffer back, not the defaults one, so the defaults need a bind again."); + } + + static object OverrideBufferOf(GlobalShaderVariablesUploader uploader) => + typeof(GlobalShaderVariablesUploader).GetField("m_OverrideConstantBuffer", BindingFlags.NonPublic | BindingFlags.Instance) + .GetValue(uploader); + + [Test] + public void TemporaryDispose_ConstantBufferMode_BindsBackWhatWasBoundAtGet_EvenAfterAParentWrite() + { + var uploader = CreateConstantBufferUploader(); + uploader.PushDefault(m_Cmd); + + var temporary = uploader.Get(); + temporary._Time = new Vector4(99f, 99f, 99f, 99f); + temporary.Push(m_Cmd); + + // Written on the parent while the temporary copy is open, without a push: it must not change what Dispose() + // binds back, here the defaults buffer bound at Get(). + uploader._ScreenSize = k_StagedScreenSize; + + Assert.That(RecordedOnTestCmd(() => ((IDisposable)temporary).Dispose()), Is.EqualTo(CostOfBind())); + Assert.That(Recorded(cmd => uploader.Push(cmd)), Is.EqualTo(CostOfUploadAndBind()), + "The parent's write stays pending until its own push."); + } + + [Test] + public void TemporaryDispose_LooseUniforms_LeavesAParentWriteToTheParentsNextPush() + { + Vector4 saved = Shader.GetGlobalVector(k_ScreenSizeID); + try + { + var uploader = new GlobalShaderVariablesUploader(GlobalShaderVariablesGroup.Base | GlobalShaderVariablesGroup.Only3D); + FillBaseDefaults(uploader); + uploader.PushDefault(m_Cmd); + Vector4 cameraScreenSize = uploader._ScreenSize; + + using (var temporary = uploader.Get()) + { + temporary._Time = new Vector4(99f, 99f, 99f, 99f); + temporary.Push(m_Cmd); + + uploader._ScreenSize = k_StagedScreenSize; + } + + ExecuteTestCmd(); + Assert.That(Shader.GetGlobalVector(k_ScreenSizeID), Is.EqualTo(cameraScreenSize), + "Dispose() only puts back what the copy pushed: the parent's write waits for its own push, as with the constant buffer."); + + uploader.Push(m_Cmd); + ExecuteTestCmd(); + Assert.That(Shader.GetGlobalVector(k_ScreenSizeID), Is.EqualTo(k_StagedScreenSize)); + } + finally + { + Shader.SetGlobalVector(k_ScreenSizeID, saved); + } + } + + [Test] + public void TemporaryResetToDefault_ConstantBufferMode_BindsTheParentDefaultsBuffer() + { + var uploader = CreateConstantBufferUploader(); + uploader.PushDefault(m_Cmd); + uploader._Time = new Vector4(99f, 99f, 99f, 99f); + uploader.Push(m_Cmd); + + var temporary = uploader.Get(); + temporary.ResetToDefault(); + + Assert.That(RecordedOnTestCmd(() => temporary.Push(m_Cmd)), Is.EqualTo(CostOfBind()), + "The camera defaults are already uploaded in the parent's defaults buffer."); + Assert.That(RecordedOnTestCmd(() => ((IDisposable)temporary).Dispose()), Is.EqualTo(CostOfBind())); + } + + [Test] + public void TemporaryPushToCompute_ConstantBufferMode_BindsEachComputeShaderAndDisposeUnbindsThem() + { + var colorPyramid = LoadComputeShader("ColorPyramid"); + var depthPyramid = LoadComputeShader("DepthPyramid"); + var uploader = CreateConstantBufferUploader(); + uploader.PushDefault(m_Cmd); + + var temporary = uploader.Get(); + temporary._ScreenSize = k_TemporaryScreenSize; + + Assert.That(RecordedOnTestCmd(() => temporary.PushToCompute(m_Cmd, colorPyramid)), Is.EqualTo(CostOfUploadAndComputeBind(colorPyramid))); + Assert.That(RecordedOnTestCmd(() => temporary.PushToCompute(m_Cmd, depthPyramid)), Is.EqualTo(CostOfUploadAndComputeBind(depthPyramid))); + Assert.That(RecordedOnTestCmd(() => ((IDisposable)temporary).Dispose()), Is.EqualTo(CostOfComputeUnbind(colorPyramid) + CostOfComputeUnbind(depthPyramid)), + "The global slot was never taken: Dispose() only unbinds the compute shaders, which read the global buffer again."); + } + + [Test] + public void ContextItemGet_ReturnsTheTemporaryCopyOfItsUploader() + { + var uploader = CreateFlushedUploader(); + var shaderData = new UniversalGlobalShaderData(); + shaderData.Set(uploader); + var shaderData2D = new Universal2DGlobalShaderData(); + shaderData2D.Set(uploader); + + var temporary = shaderData.Get(); + temporary.Dispose(); + var temporary2D = shaderData2D.Get(); + temporary2D.Dispose(); + + Assert.That(temporary2D, Is.SameAs(temporary), "One temporary copy per uploader, reused, so a pass allocates nothing."); + Assert.That(temporary, Is.Not.SameAs(uploader)); + Assert.That(shaderData.GetGlobal(), Is.SameAs(uploader), "GetGlobal() hands out the renderer's uploader itself."); + Assert.That(shaderData2D.GetGlobal(), Is.SameAs(uploader)); + } + + [Test] + public void ContextItemGet_WhileTheRenderGraphRecords_Throws() + { + // The renderer only sets the uploader when the render graph executes, the item is empty while it records. + Assert.Throws(() => new UniversalGlobalShaderData().Get()); + Assert.Throws(() => new Universal2DGlobalShaderData().Get()); + Assert.Throws(() => new UniversalGlobalShaderData().GetGlobal()); + Assert.Throws(() => new Universal2DGlobalShaderData().GetGlobal()); + } + + [Test] + public void Push_WithATemporaryCopyLeftOpen_Throws() + { + var uploader = CreateFlushedUploader(); + var temporary = uploader.Get(); + temporary._ScreenSize = k_TemporaryScreenSize; + temporary.Push(m_Cmd); + + Assert.Throws(() => uploader.Push(m_Cmd)); + Assert.Throws(() => temporary.Push(m_Cmd), "The temporary copy is closed."); + Assert.DoesNotThrow(() => uploader.Push(m_Cmd), "Once closed, the copy no longer blocks the pushes."); + } + + [Test] + public void Get_WithATemporaryCopyLeftOpen_ThrowsAndRecordsNothingOnItsCommandBuffer([Values] bool constantBuffer) + { + var uploader = constantBuffer ? CreateConstantBufferUploader() : CreateFlushedUploader(); + using var earlierPassCmd = new CommandBuffer(); + var leaked = uploader.Get(); + leaked._ScreenSize = k_TemporaryScreenSize; + leaked.Push(CommandBufferHelpers.GetComputeCommandBuffer(earlierPassCmd)); + earlierPassCmd.Clear(); + + Assert.Throws(() => uploader.Get()); + Assert.That(earlierPassCmd.sizeInBytes, Is.Zero, + "The command buffer of the leaked copy's last push can belong to an earlier pass, or be back in the pool."); + + using var temporary = uploader.Get(); + Assert.That(temporary, Is.Not.Null, "Once closed, the copy no longer blocks Get()."); + } + + [Test] + public void Push_WithATemporaryCopyOnlyRead_DoesNotThrow([Values] bool constantBuffer) + { + var uploader = constantBuffer ? CreateConstantBufferUploader() : CreateFlushedUploader(); + _ = uploader.Get()._ScreenSize; + + Assert.DoesNotThrow(() => uploader.Push(m_Cmd), "A copy that was only read has nothing to put back."); + using var temporary = uploader.Get(); + Assert.That(temporary, Is.Not.Null); + } + + [Test] + public void Get_WithATemporaryCopyOnlyRead_HandsItOutAgain() + { + var uploader = CreateFlushedUploader(); + var readOnly = uploader.Get(); + _ = readOnly._ScreenSize; + + using var temporary = uploader.Get(); + Assert.That(temporary, Is.SameAs(readOnly)); + } + + [Test] + public void Get_WithATemporaryCopyChangedButNotPushed_Throws() + { + var uploader = CreateFlushedUploader(); + uploader.Get()._ScreenSize = k_TemporaryScreenSize; + + Assert.Throws(() => uploader.Get(), + "Handing out the same object again would drop the change."); + } + + [Test] + public void TemporaryPush_AfterDispose_Throws() + { + var uploader = CreateFlushedUploader(); + var temporary = uploader.Get(); + ((IDisposable)temporary).Dispose(); + + Assert.Throws(() => temporary.Push(m_Cmd)); + Assert.Throws(() => temporary.PushToCompute(m_Cmd, LoadComputeShader("ColorPyramid"))); + Assert.That(RecordedOnTestCmd(() => ((IDisposable)temporary).Dispose()), Is.Zero, "Disposing twice is a no-op."); + } + + [Test] + public void Get_WhileFillingTheDefaults_Throws() + { + var uploader = new GlobalShaderVariablesUploader(GlobalShaderVariablesGroup.All); + uploader.BeginFill(); + + Assert.Throws(() => uploader.Get()); + } + + [Test] + public void EndRenderGraph_WithATemporaryCopyNeverDisposed_LogsAnErrorAndRecovers() + { + var uploader = CreateFlushedUploader(); + uploader.Get()._ScreenSize = k_TemporaryScreenSize; + + LogAssert.Expect(LogType.Exception, new System.Text.RegularExpressions.Regex("wasn't disposed")); + using var cameraCmd = new CommandBuffer(); + uploader.EndRenderGraph(cameraCmd); + FillBaseDefaults(uploader); + + using var temporary = uploader.Get(); + Assert.That(temporary, Is.Not.Null, "The next camera can use a temporary copy again."); + } + + [Test] + public void EndRenderGraph_WithAPushedTemporaryCopyNeverDisposed_RestoresOnTheCameraCommandBuffer([Values] bool constantBuffer) + { + Vector4 saved = Shader.GetGlobalVector(k_ScreenSizeID); + try + { + GlobalShaderVariablesUploader uploader; + if (constantBuffer) + uploader = CreateConstantBufferUploader(); + else + { + uploader = new GlobalShaderVariablesUploader(GlobalShaderVariablesGroup.Base | GlobalShaderVariablesGroup.Only3D); + FillBaseDefaults(uploader); + } + uploader.PushDefault(m_Cmd); + Vector4 cameraScreenSize = uploader._ScreenSize; + + var leaked = uploader.Get(); + leaked._ScreenSize = k_TemporaryScreenSize; + leaked.Push(m_Cmd); + // The constant buffer tests never run their commands: the global slot would keep a test buffer. + if (!constantBuffer) + ExecuteTestCmd(); + + LogAssert.Expect(LogType.Exception, new System.Text.RegularExpressions.Regex("wasn't disposed")); + using var cameraCmd = new CommandBuffer(); + uploader.EndRenderGraph(cameraCmd); + + Assert.That(cameraCmd.sizeInBytes, Is.EqualTo(constantBuffer ? CostOfBind() : CostOfPushes(1)), + "The end of the camera puts back what the copy changed, on the camera's command buffer."); + if (!constantBuffer) + { + Graphics.ExecuteCommandBuffer(cameraCmd); + Assert.That(Shader.GetGlobalVector(k_ScreenSizeID), Is.EqualTo(cameraScreenSize)); + } + } + finally + { + Shader.SetGlobalVector(k_ScreenSizeID, saved); + } + } + + [Test] + public void EndRenderGraph_WithATemporaryCopyOnlyRead_LogsAndRecordsNothing() + { + var uploader = CreateFlushedUploader(); + _ = uploader.Get()._ScreenSize; + + using var cameraCmd = new CommandBuffer(); + uploader.EndRenderGraph(cameraCmd); + + Assert.That(cameraCmd.sizeInBytes, Is.Zero, "A copy that was only read has nothing to put back."); + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void EndRenderGraph_ConstantBufferMode_UnbindsTheComputeShadersATemporaryCopyLeftBound([Values] bool disposedFromARasterPass) + { + var computeShader = LoadComputeShader("ColorPyramid"); + var uploader = CreateConstantBufferUploader(); + uploader.PushDefault(m_Cmd); + + var temporary = uploader.Get(); + temporary._ScreenSize = k_TemporaryScreenSize; + temporary.PushToCompute(m_Cmd, computeShader); + using var raster = new CommandBuffer(); + if (disposedFromARasterPass) + { + temporary.Push(CommandBufferHelpers.GetRasterCommandBuffer(raster)); + ((IDisposable)temporary).Dispose(); + } + else + LogAssert.Expect(LogType.Exception, new System.Text.RegularExpressions.Regex("wasn't disposed")); + + using var cameraCmd = new CommandBuffer(); + uploader.EndRenderGraph(cameraCmd); + Assert.That(cameraCmd.sizeInBytes, Is.EqualTo(CostOfComputeUnbind(computeShader)), + "The compute shader's binding wins over the global slot: the end of the camera unbinds it."); + } } } diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/Light2DBlendStyleIsolationTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/Light2DBlendStyleIsolationTests.cs new file mode 100644 index 00000000000..4f8a2b4a74a --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/Light2DBlendStyleIsolationTests.cs @@ -0,0 +1,191 @@ +using NUnit.Framework; +using UnityEditor.SceneManagement; +using UnityEngine; +using UnityEngine.Rendering; +using UnityEngine.Rendering.Universal; + +namespace UnityEditor.Rendering.Universal.Tests +{ + // UUM-161536: a 2D light must not change when a light that does not overlap it switches to + // another blend style. On OpenGLCore with NVIDIA drivers, the MRT light pass wrote the + // Multiply light's colour into the Additive light texture as well, so the Multiply light got brighter. + class Light2DBlendStyleIsolationTests + { + const string k_Dir = "Assets/Light2DBlendStyleIsolationTests"; + const int k_Size = 256; + + RenderPipelineAsset m_PrevDefault; + RenderPipelineAsset m_PrevQuality; + Camera m_Camera; + RenderTexture m_RT; + Texture2D m_Readback; + Texture2D m_SpriteTex; + Sprite m_Sprite; + + [SetUp] + public void SetUp() + { + m_PrevDefault = GraphicsSettings.defaultRenderPipeline; + m_PrevQuality = QualitySettings.renderPipeline; + if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null) + Assert.Ignore("Cannot run: there is no graphics device to draw with."); + + EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); + + if (!AssetDatabase.IsValidFolder(k_Dir)) + AssetDatabase.CreateFolder("Assets", "Light2DBlendStyleIsolationTests"); + var rendererData = ScriptableObject.CreateInstance(); + AssetDatabase.CreateAsset(rendererData, k_Dir + "/Renderer2D.asset"); + var urp = UniversalRenderPipelineAsset.Create(rendererData); + AssetDatabase.CreateAsset(urp, k_Dir + "/URP.asset"); + AssetDatabase.SaveAssets(); + GraphicsSettings.defaultRenderPipeline = urp; + QualitySettings.renderPipeline = urp; + } + + [TearDown] + public void TearDown() + { + GraphicsSettings.defaultRenderPipeline = m_PrevDefault; + QualitySettings.renderPipeline = m_PrevQuality; + if (m_Camera != null) Object.DestroyImmediate(m_Camera.gameObject); + if (m_RT != null) { m_RT.Release(); Object.DestroyImmediate(m_RT); } + if (m_Readback != null) Object.DestroyImmediate(m_Readback); + if (m_Sprite != null) Object.DestroyImmediate(m_Sprite); + if (m_SpriteTex != null) Object.DestroyImmediate(m_SpriteTex); + EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); + AssetDatabase.DeleteAsset(k_Dir); + } + + [Test] + public void MultiplyLight_IsUnchanged_WhenNonOverlappingLightSwitchesToAdditive() + { + var cam = SetUpScene(out var lightB, out int ax, out int ay, out _, out _); + + var withMultiply = RenderAndSample(cam, ax, ay); + lightB.blendStyleIndex = 1; // Additive + var withAdditive = RenderAndSample(cam, ax, ay); + + const float tolerance = 2f / 255f; + string msg = $"Light A centre changed when non-overlapping light B switched Multiply -> Additive " + + $"(device {SystemInfo.graphicsDeviceType}, {SystemInfo.graphicsDeviceName}). " + + $"B Multiply: {withMultiply}, B Additive: {withAdditive}"; + Assert.That(withAdditive.r, Is.EqualTo(withMultiply.r).Within(tolerance), msg); + Assert.That(withAdditive.g, Is.EqualTo(withMultiply.g).Within(tolerance), msg); + Assert.That(withAdditive.b, Is.EqualTo(withMultiply.b).Within(tolerance), msg); + } + + // Each blend style must still light its own area when two styles are active in one frame. + [Test] + public void BothLights_StillLightTheirOwnArea_WhenTwoBlendStylesAreActive() + { + if (Application.platform == RuntimePlatform.WindowsEditor && SystemInfo.graphicsDeviceType == GraphicsDeviceType.Direct3D12 + && SystemInfo.renderingThreadingMode == RenderingThreadingMode.NativeGraphicsJobsSplitThreading + && System.Array.Exists(System.Environment.GetCommandLineArgs(), arg => arg.Equals("-force-ugk", System.StringComparison.OrdinalIgnoreCase))) + Assert.Ignore("https://jira.unity3d.com/browse/UUM-161921"); + + var cam = SetUpScene(out var lightB, out int ax, out int ay, out int bx, out int by); + + lightB.enabled = false; + var bOff = RenderAndSample(cam, bx, by); + lightB.enabled = true; + lightB.blendStyleIndex = 1; // Additive + var aLit = RenderAndSample(cam, ax, ay); + var bLit = m_Readback.GetPixel(bx, by); + + string msg = $"(device {SystemInfo.graphicsDeviceType}) A: {aLit}, B off: {bOff}, B Additive: {bLit}"; + // A is an orange Multiply light on a 0.1 global light, so its centre is well above 0.1 in red. + Assert.Greater(aLit.r, 0.3f, "Multiply light A did not render. " + msg); + // B is a white Additive light, so its centre must be brighter than with B disabled. + Assert.Greater(bLit.r, bOff.r + 0.1f, "Additive light B did not render. " + msg); + Assert.Greater(bLit.g, bOff.g + 0.1f, "Additive light B did not render. " + msg); + } + + Camera SetUpScene(out Light2D lightB, out int ax, out int ay, out int bx, out int by) + { + var cam = m_Camera = new GameObject("Camera").AddComponent(); + cam.orthographic = true; + cam.orthographicSize = 5; + cam.transform.position = new Vector3(0, 0, -10); + cam.clearFlags = CameraClearFlags.SolidColor; + cam.backgroundColor = new Color(0f, 0f, 0.3f); + m_RT = new RenderTexture(k_Size, k_Size, 24, RenderTextureFormat.ARGB32); + cam.targetTexture = m_RT; + + // A white Sprite-Lit sprite that covers the whole view. + m_SpriteTex = new Texture2D(4, 4); + var px = new Color[16]; + for (int i = 0; i < px.Length; i++) px[i] = Color.white; + m_SpriteTex.SetPixels(px); + m_SpriteTex.Apply(); + var sr = new GameObject("Background").AddComponent(); + sr.sprite = m_Sprite = Sprite.Create(m_SpriteTex, new Rect(0, 0, 4, 4), new Vector2(0.5f, 0.5f), 4f / 20f); + sr.sharedMaterial = AssetDatabase.LoadAssetAtPath( + "Packages/com.unity.render-pipelines.universal/Runtime/Materials/Sprite-Lit-Default.mat"); + + var global = new GameObject("Global").AddComponent(); + global.lightType = Light2D.LightType.Global; + global.intensity = 0.1f; + + // Light A (Multiply) at x=-3, light B at x=+3. Radius 1.5, so they never overlap. + MakeLight("LightA", new Vector3(-3, 0, 0), 0, new Color(1f, 0.5f, 0.25f)); + lightB = MakeLight("LightB", new Vector3(3, 0, 0), 0, Color.white); + + // Light centres: x=-3 and x=+3 in [-5,5] -> u=0.2 and u=0.8. + ax = (int)(0.2f * k_Size); ay = k_Size / 2; + bx = (int)(0.8f * k_Size); by = k_Size / 2; + return cam; + } + + static Light2D MakeLight(string name, Vector3 pos, int blendStyle, Color color) + { + var go = new GameObject(name); + go.transform.position = pos; + var l = go.AddComponent(); + l.lightType = Light2D.LightType.Point; + l.pointLightOuterRadius = 1.5f; + l.pointLightInnerRadius = 1.0f; + l.blendStyleIndex = blendStyle; + l.color = color; + l.intensity = 0.5f; + return l; + } + + Color RenderAndSample(Camera cam, int x, int y) + { + // LateUpdate does not run in EditMode tests, so build light meshes and bounds by hand. + foreach (var l in Object.FindObjectsByType(FindObjectsInactive.Exclude)) + { + if (l.lightType == Light2D.LightType.Global) continue; + l.UpdateMesh(true); + l.UpdateBoundingSphere(); + } + + for (int i = 0; i < 3; i++) + cam.Render(); + + var prev = RenderTexture.active; + RenderTexture.active = m_RT; + if (m_Readback == null) + m_Readback = new Texture2D(k_Size, k_Size, TextureFormat.RGBA32, false); + m_Readback.ReadPixels(new Rect(0, 0, k_Size, k_Size), 0, 0); + m_Readback.Apply(); + RenderTexture.active = prev; + return m_Readback.GetPixel(x, y); + } + } + + // Kept apart from Light2DBlendStyleIsolationTests so it skips that fixture's asset and scene setup, + // and still runs without a graphics device. + class Renderer2DSupportsMRTTests + { + [Test] + public void SupportsMRT_IsFalseOnlyOnOpenGLDevices() + { + var device = SystemInfo.graphicsDeviceType; + bool isGL = device == GraphicsDeviceType.OpenGLCore || device == GraphicsDeviceType.OpenGLES3; + Assert.AreEqual(isGL, Renderer2D.IsGLDevice(), $"device {device}"); + Assert.AreEqual(!isGL, Renderer2D.supportsMRT, $"device {device}"); + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/Light2DBlendStyleIsolationTests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Editor/Light2DBlendStyleIsolationTests.cs.meta new file mode 100644 index 00000000000..af46280acdd --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/Light2DBlendStyleIsolationTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 22925a6a32c749148acdcc3b3fe179cb \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/Light2DCustomMaterialSyncTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/Light2DCustomMaterialSyncTests.cs new file mode 100644 index 00000000000..7171be65464 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/Light2DCustomMaterialSyncTests.cs @@ -0,0 +1,179 @@ +using NUnit.Framework; +using UnityEngine; +using UnityEngine.Rendering; +using UnityEngine.Rendering.Universal; + +namespace UnityEditor.Rendering.Universal.Tests +{ + // UUM-152882: edits to a Light2D's custom material must reach the material the light is drawn + // with, without a domain reload or Play mode change. + class Light2DCustomMaterialSyncTests + { + const string k_ColorShader = @" +Shader ""Hidden/Test/ColorLight2D"" +{ + Properties + { + _Volumetric (""Volumetric"", Color) = (1, 1, 1, 1) + _SrcBlend (""SrcBlend"", Float) = 5 + _DstBlend (""DstBlend"", Float) = 10 + _VolSrcBlend (""VolSrcBlend"", Float) = 5 + _VolDstBlend (""VolDstBlend"", Float) = 10 + } + SubShader + { + Pass + { + Name ""Light2D"" + HLSLPROGRAM + #pragma vertex vert + #pragma fragment frag + half4 _Volumetric; + float4 vert(float4 pos : POSITION) : SV_POSITION { return pos; } + half4 frag() : SV_Target { return _Volumetric; } + ENDHLSL + } + } +}"; + + const string k_DualPassShader = @" +Shader ""Hidden/Test/DualPassLight2D"" +{ + SubShader + { + Pass + { + Name ""Light2D"" + HLSLPROGRAM + #pragma vertex vert + #pragma fragment frag + float4 vert(float4 pos : POSITION) : SV_POSITION { return pos; } + half4 frag() : SV_Target { return 1; } + ENDHLSL + } + Pass + { + Name ""Light2DVolumetric"" + HLSLPROGRAM + #pragma vertex vert + #pragma fragment frag + float4 vert(float4 pos : POSITION) : SV_POSITION { return pos; } + half4 frag() : SV_Target { return 1; } + ENDHLSL + } + } +}"; + + static readonly int k_VolumetricID = Shader.PropertyToID("_Volumetric"); + static readonly int k_SrcBlendID = Shader.PropertyToID("_SrcBlend"); + static readonly int k_DstBlendID = Shader.PropertyToID("_DstBlend"); + static readonly int k_VolSrcBlendID = Shader.PropertyToID("_VolSrcBlend"); + static readonly int k_VolDstBlendID = Shader.PropertyToID("_VolDstBlend"); + + Shader m_Shader; + Material m_Material; + GameObject m_GameObject; + Renderer2DData m_RendererData; + + [SetUp] + public void SetUp() + { + m_Shader = ShaderUtil.CreateShaderAsset(k_ColorShader); + m_Material = new Material(m_Shader); + m_GameObject = new GameObject("Light2D"); + m_RendererData = ScriptableObject.CreateInstance(); + } + + [TearDown] + public void TearDown() + { + if (m_RendererData != null) + { + m_RendererData.ClearLightMaterialCache(); + Object.DestroyImmediate(m_RendererData); + } + if (m_GameObject != null) + Object.DestroyImmediate(m_GameObject); + if (m_Material != null) + Object.DestroyImmediate(m_Material); + if (m_Shader != null) + Object.DestroyImmediate(m_Shader); + } + + [Test] + public void GetLightMaterial_SourceMaterialColorChanged_DrawMaterialFollows() + { + var light = m_GameObject.AddComponent(); + light.material = m_Material; + + m_Material.SetColor(k_VolumetricID, Color.yellow); + var first = m_RendererData.GetLightMaterial(light, true, false); + Assert.AreEqual(Color.yellow, first.GetColor(k_VolumetricID)); + + m_Material.SetColor(k_VolumetricID, Color.red); + var second = m_RendererData.GetLightMaterial(light, true, false); + + Assert.AreEqual(Color.red, second.GetColor(k_VolumetricID), + "The material used to draw the light should pick up the new color on the source material."); + } + + // The sync copies the source's blend floats onto the clone; the per-light blend state must + // still win, and the clone must stay the same object so light batching is unchanged. + [Test] + public void GetLightMaterial_SourceMaterialChanged_KeepsCloneAndPerLightBlendState() + { + var light = m_GameObject.AddComponent(); + light.lightType = Light2D.LightType.Point; + light.overlapOperation = Light2D.OverlapOperation.Additive; + light.material = m_Material; + + m_Material.SetFloat(k_SrcBlendID, (float)BlendMode.SrcAlpha); + m_Material.SetFloat(k_DstBlendID, (float)BlendMode.OneMinusSrcAlpha); + m_Material.SetFloat(k_VolSrcBlendID, (float)BlendMode.SrcAlpha); + m_Material.SetFloat(k_VolDstBlendID, (float)BlendMode.OneMinusSrcAlpha); + m_Material.SetColor(k_VolumetricID, Color.yellow); + var first = m_RendererData.GetLightMaterial(light, false, false); + + m_Material.SetColor(k_VolumetricID, Color.red); + var second = m_RendererData.GetLightMaterial(light, false, false); + + Assert.AreSame(first, second, "The cached clone should be reused, not replaced."); + Assert.AreNotSame(m_Material, second, "The source material should not be drawn directly."); + Assert.AreEqual(Color.red, second.GetColor(k_VolumetricID)); + Assert.AreEqual((float)BlendMode.One, second.GetFloat(k_SrcBlendID), "_SrcBlend"); + Assert.AreEqual((float)BlendMode.One, second.GetFloat(k_DstBlendID), "_DstBlend"); + Assert.AreEqual((float)BlendMode.One, second.GetFloat(k_VolSrcBlendID), "_VolSrcBlend"); + Assert.AreEqual((float)BlendMode.One, second.GetFloat(k_VolDstBlendID), "_VolDstBlend"); + + // The source keeps its own values; only the clone gets the per-light blend state. + Assert.AreEqual((float)BlendMode.SrcAlpha, m_Material.GetFloat(k_SrcBlendID)); + } + + // Swapping the shader on the source must reach the clone, so the pass count used to pick + // the volumetric pass matches the shader the user assigned. + [Test] + public void GetLightMaterial_SourceShaderChanged_CloneUsesNewShader() + { + var light = m_GameObject.AddComponent(); + light.material = m_Material; + var first = m_RendererData.GetLightMaterial(light, false, false); + Assert.AreEqual(1, first.passCount); + + var dualPassShader = ShaderUtil.CreateShaderAsset(k_DualPassShader); + try + { + m_Material.shader = dualPassShader; + var second = m_RendererData.GetLightMaterial(light, false, false); + + Assert.AreSame(first, second, "The cached clone should be reused, not replaced."); + Assert.AreSame(dualPassShader, second.shader); + Assert.AreEqual(2, second.passCount); + } + finally + { + m_RendererData.ClearLightMaterialCache(); + Object.DestroyImmediate(dualPassShader); + } + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/Light2DCustomMaterialSyncTests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Editor/Light2DCustomMaterialSyncTests.cs.meta new file mode 100644 index 00000000000..2a5c172e4f9 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/Light2DCustomMaterialSyncTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 63fc8e98433da1649b5b6a2e4e6fe5d8 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/Light2DPrefilteringAnalysisTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/Light2DPrefilteringAnalysisTests.cs index 6f902384360..dd819d38d44 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Editor/Light2DPrefilteringAnalysisTests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/Light2DPrefilteringAnalysisTests.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using NUnit.Framework; using UnityEditor; using UnityEditor.Rendering.Universal; @@ -12,17 +13,24 @@ class Light2DPrefilteringAnalysisTests const string k_MissingScenePath = "Assets/Light2DPrefilteringAnalysisTests_Missing.unity"; const string k_ExistingScenePath = "Assets/Light2DPrefilteringAnalysisTests_Existing.unity"; const string k_SecondScenePath = "Assets/Light2DPrefilteringAnalysisTests_Second.unity"; + const string k_NoLightScenePath = "Assets/Light2DPrefilteringAnalysisTests_NoLight.unity"; + const string k_PrefabPath = "Assets/Light2DPrefilteringAnalysisTests_Light.prefab"; const string k_NotASceneFolderName = "Light2DPrefilteringAnalysisTests_NotAScene.unity"; const string k_NotASceneFolderPath = "Assets/" + k_NotASceneFolderName; + // A scene shipped in the URP package, so its path is under Packages/. + const string k_PackageScenePath = "Packages/com.unity.render-pipelines.universal/Editor/SceneTemplates/Basic.unity"; + const string k_ShadowCombo = "USE_SHADOW_MAP,USE_ADDITIVE_BLENDING,USE_SHAPE_LIGHT_TYPE_0"; EditorBuildSettingsScene[] m_SavedScenes; SceneSetup[] m_SavedSceneSetup; + SerializationMode m_SavedSerializationMode; [SetUp] public void SetUp() { m_SavedScenes = EditorBuildSettings.scenes; m_SavedSceneSetup = EditorSceneManager.GetSceneManagerSetup(); + m_SavedSerializationMode = EditorSettings.serializationMode; } [TearDown] @@ -42,76 +50,88 @@ public void TearDown() EditorBuildSettings.scenes = m_SavedScenes; AssetDatabase.DeleteAsset(k_ExistingScenePath); AssetDatabase.DeleteAsset(k_SecondScenePath); + AssetDatabase.DeleteAsset(k_NoLightScenePath); + AssetDatabase.DeleteAsset(k_PrefabPath); AssetDatabase.DeleteAsset(k_NotASceneFolderPath); + + // Restore after the test assets are gone. Leaving Mixed mode re-serializes only the + // assets whose format doesn't match, so the rest of the project is untouched. + if (EditorSettings.serializationMode != m_SavedSerializationMode) + EditorSettings.serializationMode = m_SavedSerializationMode; } } [Test] - public void AnalyzeBuildScenes_SkipsEnabledSceneWhoseFileIsMissing() + public void AnalyzeScenes_SkipsSceneWhoseFileIsMissing() { - EditorBuildSettings.scenes = new[] - { - new EditorBuildSettingsScene(k_MissingScenePath, true) - }; - string[] combos = null; - Assert.DoesNotThrow(() => combos = Light2DPrefilteringAnalysis.AnalyzeBuildScenes()); + Assert.DoesNotThrow(() => combos = Light2DPrefilteringAnalysis.AnalyzeScenes(new[] { k_MissingScenePath })); Assert.IsNotNull(combos); Assert.IsEmpty(combos); } [Test] - public void AnalyzeBuildScenes_SkipsEnabledEntryWithEmptyPath() + public void AnalyzeScenes_SkipsEntryWithEmptyPath() { - EditorBuildSettings.scenes = new[] - { - new EditorBuildSettingsScene(string.Empty, true) - }; - string[] combos = null; - Assert.DoesNotThrow(() => combos = Light2DPrefilteringAnalysis.AnalyzeBuildScenes()); + Assert.DoesNotThrow(() => combos = Light2DPrefilteringAnalysis.AnalyzeScenes(new[] { string.Empty, null })); Assert.IsNotNull(combos); Assert.IsEmpty(combos); } [Test] - public void AnalyzeBuildScenes_SkipsEnabledEntryThatIsNotASceneAsset() + public void AnalyzeScenes_SkipsEntryThatIsNotASceneAsset() { // A folder whose name ends in .unity exists in the AssetDatabase but is not a scene. AssetDatabase.CreateFolder("Assets", k_NotASceneFolderName); - EditorBuildSettings.scenes = new[] - { - new EditorBuildSettingsScene(k_NotASceneFolderPath, true) - }; string[] combos = null; - Assert.DoesNotThrow(() => combos = Light2DPrefilteringAnalysis.AnalyzeBuildScenes()); + Assert.DoesNotThrow(() => combos = Light2DPrefilteringAnalysis.AnalyzeScenes(new[] { k_NotASceneFolderPath })); Assert.IsNotNull(combos); Assert.IsEmpty(combos); } [Test] - public void AnalyzeBuildScenes_StillAnalyzesExistingSceneListedAfterMissingOne() + public void AnalyzeScenes_StillAnalyzesExistingSceneListedAfterMissingOne() { CreateSceneWithPointLights(k_ExistingScenePath, new[] { 0 }); + + string[] combos = null; + Assert.DoesNotThrow(() => combos = Light2DPrefilteringAnalysis.AnalyzeScenes(new[] { k_MissingScenePath, k_ExistingScenePath })); + Assert.IsNotNull(combos); + Assert.IsNotEmpty(combos); + } + + // The parameterless call reads the Build Profiles list, whose entries can be stale. + [Test] + public void AnalyzeBuildScenes_DoesNotThrow_WhenBuildProfilesListHasMissingEmptyAndNonSceneEntries() + { + AssetDatabase.CreateFolder("Assets", k_NotASceneFolderName); EditorBuildSettings.scenes = new[] { new EditorBuildSettingsScene(k_MissingScenePath, true), - new EditorBuildSettingsScene(k_ExistingScenePath, true) + new EditorBuildSettingsScene(string.Empty, true), + new EditorBuildSettingsScene(k_NotASceneFolderPath, true) }; - string[] combos = null; - Assert.DoesNotThrow(() => combos = Light2DPrefilteringAnalysis.AnalyzeBuildScenes()); - Assert.IsNotNull(combos); - Assert.IsNotEmpty(combos); + Assert.DoesNotThrow(() => Light2DPrefilteringAnalysis.AnalyzeBuildScenes()); } - static void CreatePointLight(int blendStyleIndex, Light2D.OverlapOperation overlapOperation) + static Light2D CreatePointLight(int blendStyleIndex, Light2D.OverlapOperation overlapOperation) { var light = new GameObject("Style " + blendStyleIndex).AddComponent(); light.lightType = Light2D.LightType.Point; light.blendStyleIndex = blendStyleIndex; light.overlapOperation = overlapOperation; + return light; + } + + // Creates an additive point Light2D on blend style 0 that casts shadows. + static Light2D CreateShadowLight() + { + var light = CreatePointLight(0, Light2D.OverlapOperation.Additive); + light.shadowsEnabled = true; + return light; } // Saves a new scene with one point light per blend style. Lights use alpha blending unless @@ -126,14 +146,32 @@ static void CreateSceneWithPointLights(string path, int[] blendStyleIndices, par } EditorSceneManager.SaveScene(scene, path); - // Replace it with an untitled scene so AnalyzeBuildScenes has to open the saved one. + // Replace it with an untitled scene so the analysis has to open the saved one. + EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); + } + + // Saves a scene with one additive point Light2D that casts shadows. + static void SaveShadowLightScene(string path) + { + var scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); + CreateShadowLight(); + EditorSceneManager.SaveScene(scene, path); EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); } + static void SaveSceneWithoutLight2D(string path) + { + var scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); + new GameObject("Not a light"); + EditorSceneManager.SaveScene(scene, path); + EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); + } + + // Analyzes only the given scenes. The parameterless AnalyzeBuildScenes also scans every + // scene under Assets/, so other scenes in the test project would change the result. static string[] AnalyzeBuildScenes(params string[] scenePaths) { - EditorBuildSettings.scenes = System.Array.ConvertAll(scenePaths, path => new EditorBuildSettingsScene(path, true)); - return Light2DPrefilteringAnalysis.AnalyzeBuildScenes(); + return Light2DPrefilteringAnalysis.AnalyzeScenes(scenePaths); } static string KeptCombosMessage(string[] combos) => "Kept combos: " + string.Join(" | ", combos); @@ -205,5 +243,148 @@ public void AnalyzeBuildScenes_IgnoresOutOfRangeBlendStyleWhenRanking() CollectionAssert.Contains(combos, "USE_SHAPE_LIGHT_TYPE_0", message); CollectionAssert.DoesNotContain(combos, "USE_SHAPE_LIGHT_TYPE_1", message); } + + // UUM-160655: BuildPipeline.BuildPlayer can build a scene that is not in the Build Profiles + // scene list. Its shadowed Light2D must still keep USE_SHADOW_MAP, or the stripper removes + // the shadow variant and the player draws the light without shadows. + [Test] + public void AnalyzeBuildScenes_KeepsShadowCombo_ForSceneBuiltByScriptOutsideBuildProfilesList() + { + SaveShadowLightScene(k_ExistingScenePath); + + // The Build Profiles list is empty; the scene is only passed to BuildPlayer. + EditorBuildSettings.scenes = new EditorBuildSettingsScene[0]; + + // Same scan as AnalyzeBuildScenes, but record the opened scenes. Other scenes in the test + // project may also keep the shadow combo, so check that this scene was the one scanned. + var opened = new List(); + string[] combos = Light2DPrefilteringAnalysis.AnalyzeScenes(Light2DPrefilteringAnalysis.GetCandidateScenePaths(), opened); + + CollectionAssert.Contains(opened, k_ExistingScenePath); + CollectionAssert.Contains(combos, k_ShadowCombo, KeptCombosMessage(combos)); + } + + // Build Profiles scenes outside Assets/ (for example in a package) must still be scanned. + [Test] + public void GetCandidateScenePaths_IncludesBuildProfilesSceneUnderPackages() + { + Assume.That(AssetDatabase.GetMainAssetTypeAtPath(k_PackageScenePath), Is.EqualTo(typeof(SceneAsset))); + EditorBuildSettings.scenes = new[] { new EditorBuildSettingsScene(k_PackageScenePath, true) }; + + CollectionAssert.Contains(new List(Light2DPrefilteringAnalysis.GetCandidateScenePaths()), k_PackageScenePath); + } + + [Test] + public void GetCandidateScenePaths_IncludesAssetsSceneNotInBuildProfiles_AndSkipsDisabledEntries() + { + SaveSceneWithoutLight2D(k_ExistingScenePath); + EditorBuildSettings.scenes = new[] { new EditorBuildSettingsScene(k_PackageScenePath, false) }; + + var candidates = new List(Light2DPrefilteringAnalysis.GetCandidateScenePaths()); + + CollectionAssert.Contains(candidates, k_ExistingScenePath); + CollectionAssert.DoesNotContain(candidates, k_PackageScenePath); + } + + // Saves the test assets as text or binary. Binary uses Mixed mode, which saves new assets as + // binary without re-serializing the project (ForceBinary would rewrite every asset). + // Switching to ForceText would rewrite every binary asset in the project as text, and + // restoring Mixed afterwards would not undo it, so the text case only runs in text projects. + static void UseSceneFormat(bool binary) + { + var current = EditorSettings.serializationMode; + if (binary) + { + if (current == SerializationMode.ForceText) + EditorSettings.serializationMode = SerializationMode.Mixed; + } + else if (current != SerializationMode.ForceText) + { + Assert.Ignore("The text case needs a project in Force Text serialization mode."); + } + } + + static void AssertSavedFormat(string path, bool binary) + { + byte[] header = new byte[5]; + using (var stream = System.IO.File.OpenRead(path)) + stream.Read(header, 0, header.Length); + bool isText = System.Text.Encoding.ASCII.GetString(header) == "%YAML"; + Assert.AreEqual(!binary, isText, path + " was not saved as " + (binary ? "binary" : "text")); + } + + // Opening a scene is costly, so a scene that doesn't reference Light2D is skipped. The check + // must work for text and binary scenes alike. + [TestCase(false)] + [TestCase(true)] + public void AnalyzeScenes_OpensOnlyScenesThatDependOnLight2D(bool binary) + { + UseSceneFormat(binary); + SaveShadowLightScene(k_ExistingScenePath); + SaveSceneWithoutLight2D(k_NoLightScenePath); + AssertSavedFormat(k_ExistingScenePath, binary); + AssertSavedFormat(k_NoLightScenePath, binary); + + var opened = new List(); + string[] combos = Light2DPrefilteringAnalysis.AnalyzeScenes(new[] { k_NoLightScenePath, k_ExistingScenePath }, opened); + + CollectionAssert.AreEqual(new[] { k_ExistingScenePath }, opened); + CollectionAssert.Contains(combos, k_ShadowCombo, KeptCombosMessage(combos)); + } + + // The recursive dependency check must find a Light2D that only lives in a prefab instance. + [TestCase(false)] + [TestCase(true)] + public void AnalyzeScenes_OpensScene_WhenLight2DIsOnlyInAPrefabInstance(bool binary) + { + UseSceneFormat(binary); + + var prefabSource = CreateShadowLight().gameObject; + var prefab = PrefabUtility.SaveAsPrefabAsset(prefabSource, k_PrefabPath); + Object.DestroyImmediate(prefabSource); + + var scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); + PrefabUtility.InstantiatePrefab(prefab, scene); + EditorSceneManager.SaveScene(scene, k_ExistingScenePath); + EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); + AssertSavedFormat(k_ExistingScenePath, binary); + + var opened = new List(); + string[] combos = Light2DPrefilteringAnalysis.AnalyzeScenes(new[] { k_ExistingScenePath }, opened); + + CollectionAssert.AreEqual(new[] { k_ExistingScenePath }, opened); + CollectionAssert.Contains(combos, k_ShadowCombo, KeptCombosMessage(combos)); + } + + // A loaded scene can gain its first Light2D after its last save. Its saved file doesn't + // reference Light2D yet, but the build includes the light once the user saves the scene. + [Test] + public void AnalyzeScenes_KeepsCombo_ForUnsavedLight2DInLoadedScene() + { + SaveSceneWithoutLight2D(k_NoLightScenePath); + var scene = EditorSceneManager.OpenScene(k_NoLightScenePath, OpenSceneMode.Single); + CreateShadowLight(); + // Adding a component from script doesn't dirty the scene; the editor's Undo path does. + EditorSceneManager.MarkSceneDirty(scene); + + var opened = new List(); + string[] combos = Light2DPrefilteringAnalysis.AnalyzeScenes(new[] { k_NoLightScenePath }, opened); + + // The loaded scene is scanned in place, not opened again. + CollectionAssert.IsEmpty(opened); + CollectionAssert.Contains(combos, k_ShadowCombo, KeptCombosMessage(combos)); + } + + // A scene listed twice (in Build Profiles and under Assets/) is opened once. + [Test] + public void AnalyzeScenes_OpensSceneOnce_WhenListedTwice() + { + SaveShadowLightScene(k_ExistingScenePath); + + var opened = new List(); + Light2DPrefilteringAnalysis.AnalyzeScenes(new[] { k_ExistingScenePath, k_ExistingScenePath }, opened); + + Assert.AreEqual(1, opened.Count, string.Join(" | ", opened)); + } } } diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/Light2DShaderGraphHdrEmulationTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/Light2DShaderGraphHdrEmulationTests.cs new file mode 100644 index 00000000000..e442e411ac0 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/Light2DShaderGraphHdrEmulationTests.cs @@ -0,0 +1,215 @@ +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework; +using UnityEditor; +using UnityEditor.Rendering.Universal.ShaderGraph; +using UnityEditor.SceneManagement; +using UnityEditor.ShaderGraph; + +namespace UnityEngine.Rendering.Universal.Tests +{ + // UUM-161407: a light using the untouched default Light2D Shader Graph must be as bright as the + // same light drawn with the built-in Light2D shader when HDR Emulation Scale is above 1. With the + // Alpha Blend overlap (SrcAlpha, OneMinusSrcAlpha), any scaling of the light's alpha darkens it. +#if ENABLE_CORECLR + [Explicit("MultiJson-serialized ShaderGraph written to disk fails to reimport on CoreCLR (JSON parse error: The document root must not follow by other values), so no Shader or Material sub-assets are produced, see https://jira.unity3d.com/browse/UUM-150436")] +#endif + class Light2DShaderGraphHdrEmulationTests + { + const string k_Folder = "Assets/__Light2DShaderGraphHdrEmulationTests"; + const string k_GraphPath = k_Folder + "/DefaultLight2D.shadergraph"; + const string k_RendererPath = k_Folder + "/Renderer2D.asset"; + const string k_PipelinePath = k_Folder + "/URP2D.asset"; + const int k_Size = 300; + + Material m_GraphMaterial; + RenderPipelineAsset m_OriginalDefaultPipeline; + RenderPipelineAsset m_OriginalQualityPipeline; + bool m_OriginalAllowAsyncCompilation; + RenderTexture m_Target; + readonly List m_CreatedObjects = new List(); + + [OneTimeSetUp] + public void OneTimeSetUp() + { + if (!AssetDatabase.IsValidFolder(k_Folder)) + AssetDatabase.CreateFolder("Assets", k_Folder.Substring("Assets/".Length)); + m_GraphMaterial = CreateDefaultLight2DGraphMaterial(); + } + + [OneTimeTearDown] + public void OneTimeTearDown() + { + AssetDatabase.DeleteAsset(k_Folder); + } + + [SetUp] + public void SetUp() + { + m_OriginalDefaultPipeline = GraphicsSettings.defaultRenderPipeline; + m_OriginalQualityPipeline = QualitySettings.renderPipeline; + m_OriginalAllowAsyncCompilation = ShaderUtil.allowAsyncCompilation; + ShaderUtil.allowAsyncCompilation = false; + EditorSceneManager.NewScene(NewSceneSetup.EmptyScene); + } + + [TearDown] + public void TearDown() + { + GraphicsSettings.defaultRenderPipeline = m_OriginalDefaultPipeline; + QualitySettings.renderPipeline = m_OriginalQualityPipeline; + ShaderUtil.allowAsyncCompilation = m_OriginalAllowAsyncCompilation; + if (m_Target != null) + { + RenderTexture.active = null; + foreach (var cam in Object.FindObjectsByType()) + cam.targetTexture = null; + m_Target.Release(); + Object.DestroyImmediate(m_Target); + } + EditorSceneManager.NewScene(NewSceneSetup.EmptyScene); + foreach (var obj in m_CreatedObjects) + { + if (obj != null) + Object.DestroyImmediate(obj); + } + m_CreatedObjects.Clear(); + AssetDatabase.DeleteAsset(k_PipelinePath); + AssetDatabase.DeleteAsset(k_RendererPath); + } + + T Track(T obj) where T : Object + { + m_CreatedObjects.Add(obj); + return obj; + } + + static Material CreateDefaultLight2DGraphMaterial() + { + // Same graph the "Light2D Shader Graph" Create menu writes. + var target = new UniversalTarget(); + Assert.IsTrue(target.TrySetActiveSubTarget(typeof(UniversalLight2DSubTarget))); + var graph = new GraphData(); + graph.AddContexts(); + graph.InitializeOutputs(new Target[] { target }, UniversalLight2DSubTarget.kActiveBlocks); + graph.OnEnable(); + graph.ValidateGraph(); + + FileUtilities.WriteShaderGraphToDisk(k_GraphPath, graph); + AssetDatabase.ImportAsset(k_GraphPath, ImportAssetOptions.ForceSynchronousImport | ImportAssetOptions.ForceUpdate); + var assets = AssetDatabase.LoadAllAssetsAtPath(k_GraphPath); + var shader = assets.OfType().FirstOrDefault(); + Assert.IsNotNull(shader, "The default Light2D Shader Graph produced no shader."); + Assert.IsFalse(ShaderUtil.ShaderHasError(shader), "The default Light2D Shader Graph has compile errors."); + // The Material sub-asset the importer adds beside the shader, as a user would assign it. + var material = assets.OfType().FirstOrDefault(); + Assert.IsNotNull(material, "The default Light2D Shader Graph produced no Material sub-asset."); + return material; + } + + static Renderer2DData CreatePipeline(float hdrEmulationScale) + { + var rendererData = ScriptableObject.CreateInstance(); + AssetDatabase.CreateAsset(rendererData, k_RendererPath); + var so = new SerializedObject(rendererData); + so.FindProperty("m_HDREmulationScale").floatValue = hdrEmulationScale; + so.ApplyModifiedPropertiesWithoutUndo(); + + var pipeline = UniversalRenderPipelineAsset.Create(rendererData); + AssetDatabase.CreateAsset(pipeline, k_PipelinePath); + AssetDatabase.SaveAssets(); + + GraphicsSettings.defaultRenderPipeline = pipeline; + QualitySettings.renderPipeline = pipeline; + return rendererData; + } + + static Light2D CreateLight(Light2D.LightType type, float x, Sprite cookie, Material material) + { + var go = new GameObject(type + (material != null ? "_Graph" : "_BuiltIn")); + go.transform.position = new Vector3(x, 0, 0); + go.transform.localScale = type == Light2D.LightType.Sprite ? new Vector3(0.5f, 0.5f, 1) : new Vector3(1.5f, 1.5f, 1); + var light = go.AddComponent(); + light.lightType = type; + light.intensity = 0.5f; + light.color = Color.white; + light.blendStyleIndex = 0; + light.overlapOperation = Light2D.OverlapOperation.AlphaBlend; + if (type == Light2D.LightType.Sprite) + light.lightCookieSprite = cookie; + light.material = material; + // LateUpdate does not run in batch mode; build the light mesh directly. + light.UpdateMesh(true); + return light; + } + + Sprite WhiteSprite() + { + var tex = Track(new Texture2D(4, 4)); + tex.SetPixels(Enumerable.Repeat(Color.white, 16).ToArray()); + tex.Apply(); + return Track(Sprite.Create(tex, new Rect(0, 0, 4, 4), new Vector2(0.5f, 0.5f), 1)); + } + + static float BrightestGreen(Texture2D tex, int cx, int cy, int radius) + { + float best = 0; + for (int y = cy - radius; y <= cy + radius; y++) + for (int x = cx - radius; x <= cx + radius; x++) + best = Mathf.Max(best, tex.GetPixel(x, y).g); + return best; + } + + // Freeform and Sprite are the reported cases. Point lights already matched (built-in + // frag_point scales RGBA too) and must keep matching. Scale 1 is the control. + [TestCase(Light2D.LightType.Freeform, 2f)] + [TestCase(Light2D.LightType.Sprite, 2f)] + [TestCase(Light2D.LightType.Freeform, 4f)] + [TestCase(Light2D.LightType.Sprite, 4f)] + [TestCase(Light2D.LightType.Point, 2f)] + [TestCase(Light2D.LightType.Freeform, 1f)] + public void DefaultLight2DShaderGraph_MatchesBuiltInBrightness_AtHdrEmulationScale(Light2D.LightType type, float hdrEmulationScale) + { + var rendererData = CreatePipeline(hdrEmulationScale); + Assert.AreEqual(hdrEmulationScale, rendererData.hdrEmulationScale); + + // Orthographic size 3 over 300 px: 50 px per unit, origin at the center. + var cam = new GameObject("Camera").AddComponent(); + cam.orthographic = true; + cam.orthographicSize = 3; + cam.transform.position = new Vector3(0, 0, -10); + cam.clearFlags = CameraClearFlags.SolidColor; + cam.backgroundColor = Color.black; + + // A white 8x8-unit lit sprite fills the view, so each pixel shows the light that reaches it. + var sprite = WhiteSprite(); + var background = new GameObject("Background").AddComponent(); + background.sprite = sprite; + background.sharedMaterial = Track(new Material(Shader.Find("Universal Render Pipeline/2D/Sprite-Lit-Default"))); + background.transform.localScale = new Vector3(2, 2, 1); + + // Built-in light on the left, graph light on the right. Each light, falloff included, + // stays within 1.5 units (75 px) of its center, so the two never overlap. + CreateLight(type, -1.5f, sprite, null); + CreateLight(type, 1.5f, sprite, m_GraphMaterial); + + m_Target = new RenderTexture(k_Size, k_Size, 24, RenderTextureFormat.ARGB32); + cam.targetTexture = m_Target; + for (int i = 0; i < 3; i++) + cam.Render(); + + RenderTexture.active = m_Target; + var read = Track(new Texture2D(k_Size, k_Size, TextureFormat.RGBA32, false)); + read.ReadPixels(new Rect(0, 0, k_Size, k_Size), 0, 0); + read.Apply(); + RenderTexture.active = null; + + float builtIn = BrightestGreen(read, k_Size / 2 - 75, k_Size / 2, 70); + float graph = BrightestGreen(read, k_Size / 2 + 75, k_Size / 2, 70); + + Assert.Greater(builtIn, 0.05f, "The built-in light did not light the sprite; the scene did not render."); + Assert.AreEqual(builtIn, graph, 2f / 255f, + $"{type} light: the default Light2D Shader Graph rendered {graph * 255:F0}/255 but the built-in light rendered {builtIn * 255:F0}/255 at HDR Emulation Scale {hdrEmulationScale}."); + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/Light2DShaderGraphHdrEmulationTests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Editor/Light2DShaderGraphHdrEmulationTests.cs.meta new file mode 100644 index 00000000000..81c21c5f719 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/Light2DShaderGraphHdrEmulationTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 344d8825e16cc9c4ea927366fb21fc92 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ObsoleteShadowPropertiesTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ObsoleteShadowPropertiesTests.cs new file mode 100644 index 00000000000..a914f1a0cf5 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ObsoleteShadowPropertiesTests.cs @@ -0,0 +1,139 @@ +using NUnit.Framework; +using UnityEngine; +using UnityEngine.Rendering; +using UnityEngine.Rendering.Universal; + +namespace UnityEditor.Rendering.Universal.Tests +{ + class ObsoleteShadowPropertiesTests + { + UniversalRenderPipelineAsset m_Asset; + bool m_InitializedVolumeManager; + VolumeStack m_PreviousStack; + VolumeStack m_Stack; + ShadowsVolumeOverride m_Shadows; + int m_SetterWarningCount; + + [SetUp] + public void SetUp() + { + m_Asset = ScriptableObject.CreateInstance(); + m_SetterWarningCount = 0; + Application.logMessageReceived += CountSetterWarnings; + } + + [TearDown] + public void TearDown() + { + Application.logMessageReceived -= CountSetterWarnings; + + if (m_Stack != null) + { + VolumeManager.instance.stack = m_PreviousStack; + VolumeManager.instance.DestroyStack(m_Stack); + m_Stack = null; + } + + if (m_InitializedVolumeManager) + { + VolumeManager.instance.Deinitialize(); + m_InitializedVolumeManager = false; + } + + Object.DestroyImmediate(m_Asset); + } + + void UseTestVolumeStack() + { + if (!VolumeManager.instance.isInitialized) + { + VolumeManager.instance.baseComponentTypeArray = new[] { typeof(ShadowsVolumeOverride) }; + VolumeManager.instance.InitializeInternal(); + m_InitializedVolumeManager = true; + } + + m_PreviousStack = VolumeManager.instance.stack; + m_Stack = VolumeManager.instance.CreateStack(); + VolumeManager.instance.stack = m_Stack; + + m_Shadows = m_Stack.GetComponent(); + if (m_Shadows == null) + Assert.Ignore("The volume manager was initialized by a pipeline without the Shadows volume override"); + m_Shadows.maxShadowDistance.value = 33f; + m_Shadows.cascadeCount.value = 3; + m_Shadows.cascadeSplit0.value = 0.125f; + m_Shadows.cascadeSplit1.value = 0.25f; + m_Shadows.cascadeSplit2.value = 0.5f; + m_Shadows.lastCascadeBorder.value = 0.375f; + } + + void CountSetterWarnings(string condition, string stackTrace, LogType type) + { + if (type == LogType.Warning && condition.Contains("ShadowsVolumeOverride")) + m_SetterWarningCount++; + } + +#pragma warning disable 618 // Obsolete warning + [Test] + [Description("The obsolete shadow properties of the URP asset return the values of the Shadows volume override in the current volume stack.")] + public void Getters_ReturnTheCurrentVolumeStackValues() + { + UseTestVolumeStack(); + + Assert.AreEqual(33f, m_Asset.shadowDistance); + Assert.AreEqual(3, m_Asset.shadowCascadeCount); + Assert.AreEqual(0.125f, m_Asset.cascade2Split); + Assert.AreEqual(new Vector2(0.125f, 0.25f), m_Asset.cascade3Split); + Assert.AreEqual(new Vector3(0.125f, 0.25f, 0.5f), m_Asset.cascade4Split); + Assert.AreEqual(0.375f, m_Asset.cascadeBorder); + } + + [Test] + [Description("Before the volume manager is initialized, the obsolete shadow properties return the values serialized in the URP asset.")] + public void Getters_WithoutVolumeManager_ReturnTheSerializedValues() + { + if (VolumeManager.instance.isInitialized) + Assert.Ignore("The volume manager is already initialized by the active render pipeline"); + + m_Asset.m_ObsoleteShadowDistance = 20f; + m_Asset.m_ObsoleteShadowCascadeCount = 2; + m_Asset.m_ObsoleteCascade2Split = 0.3f; + m_Asset.m_ObsoleteCascade3Split = new Vector2(0.2f, 0.4f); + m_Asset.m_ObsoleteCascade4Split = new Vector3(0.1f, 0.2f, 0.4f); + m_Asset.m_ObsoleteCascadeBorder = 0.15f; + + Assert.AreEqual(20f, m_Asset.shadowDistance); + Assert.AreEqual(2, m_Asset.shadowCascadeCount); + Assert.AreEqual(0.3f, m_Asset.cascade2Split); + Assert.AreEqual(new Vector2(0.2f, 0.4f), m_Asset.cascade3Split); + Assert.AreEqual(new Vector3(0.1f, 0.2f, 0.4f), m_Asset.cascade4Split); + Assert.AreEqual(0.15f, m_Asset.cascadeBorder); + } + + [Test] + [Description("Setting an obsolete shadow property of the URP asset changes nothing and warns at most once per session.")] + public void Setters_HaveNoEffectAndWarnAtMostOnce() + { + UseTestVolumeStack(); + + m_Asset.shadowDistance = 1f; + m_Asset.shadowCascadeCount = 4; + m_Asset.cascade2Split = 0.9f; + m_Asset.cascade3Split = new Vector2(0.8f, 0.9f); + m_Asset.cascade4Split = new Vector3(0.7f, 0.8f, 0.9f); + m_Asset.cascadeBorder = 0.9f; + + Assert.AreEqual(33f, m_Asset.shadowDistance); + Assert.AreEqual(3, m_Asset.shadowCascadeCount); + Assert.AreEqual(new Vector3(0.125f, 0.25f, 0.5f), m_Asset.cascade4Split); + Assert.AreEqual(0.375f, m_Asset.cascadeBorder); + Assert.AreEqual(50f, m_Asset.m_ObsoleteShadowDistance); + Assert.LessOrEqual(m_SetterWarningCount, 1); + + m_SetterWarningCount = 0; + m_Asset.shadowDistance = 2f; + Assert.AreEqual(0, m_SetterWarningCount); + } +#pragma warning restore 618 // Obsolete warning + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ObsoleteShadowPropertiesTests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ObsoleteShadowPropertiesTests.cs.meta new file mode 100644 index 00000000000..56dbb014a2d --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ObsoleteShadowPropertiesTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 6cfc90fa89484e9c8c445ca8f1729311 diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/PersistentConstantBufferLayoutTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/PersistentConstantBufferLayoutTests.cs new file mode 100644 index 00000000000..63559ba0b5d --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/PersistentConstantBufferLayoutTests.cs @@ -0,0 +1,102 @@ +using System.Text; +using NUnit.Framework; +using UnityEngine; +using UnityEngine.Rendering; +using UnityEngine.Rendering.Universal; +using UnityEngine.TestTools; + +namespace UnityEditor.Rendering.Universal.Tests +{ + // URP decides in C# whether it fills its light data into persistent constant buffers (RenderingUtils.usePersistentConstantBuffer), + // and the shaders pick the matching layout with URP_PERSISTENT_CONSTANT_BUFFERS_ACTIVE (GlobalShaderVariables.hlsl). + // If the two disagree on a platform, URP uploads one layout while the shaders read another. + // This test compiles Lit for each kind of platform and checks that its light cookie layout is the one + // usePersistentConstantBuffer picks on that platform, which each test case states. + class PersistentConstantBufferLayoutTests + { + const string k_LitShaderName = "Universal Render Pipeline/Lit"; + const string k_ForwardLitPassName = "ForwardLit"; + + // The persistent layout stores the light types in the LightCookies constant buffer as float4 (yzw are padding). + // The field-wise GLES3 layout declares them as float. + const string k_LightCookiesBuffer = "LightCookies"; + const string k_LightTypesField = "_AdditionalLightsLightTypes"; + + static readonly string[] k_Keywords = { ShaderKeywordStrings.AdditionalLightsPixel, ShaderKeywordStrings.LightCookies }; + + // GLES links both stages into one program, whose parameters can be reported with either stage: check both. + static readonly ShaderType[] k_Stages = { ShaderType.Vertex, ShaderType.Fragment }; + + [TestCase(ShaderCompilerPlatform.GLES3x, BuildTarget.WebGL, true)] + [TestCase(ShaderCompilerPlatform.GLES3x, BuildTarget.Android, false)] + [TestCase(ShaderCompilerPlatform.D3D, BuildTarget.StandaloneWindows64, true)] + [UnityPlatform(RuntimePlatform.WindowsEditor)] + public void LightCookieLayoutMatchesRenderingUtils(ShaderCompilerPlatform compilerPlatform, BuildTarget buildTarget, bool expectPersistent) + { + Shader shader = Shader.Find(k_LitShaderName); + Assert.IsNotNull(shader, $"Could not find shader '{k_LitShaderName}'."); + + ShaderData.Pass pass = FindPass(ShaderUtil.GetShaderData(shader), k_ForwardLitPassName); + Assert.IsNotNull(pass, $"Could not find pass '{k_ForwardLitPassName}' in '{k_LitShaderName}'."); + + bool foundField = false; + bool persistentLayout = false; + var reflected = new StringBuilder(); + foreach (var stage in k_Stages) + { + if (!pass.HasShaderStage(stage)) + continue; + + ShaderData.VariantCompileInfo info = pass.CompileVariant(stage, k_Keywords, compilerPlatform, buildTarget); + Assert.IsTrue(info.Success, $"Compiling the {stage} stage of '{k_ForwardLitPassName}' for {compilerPlatform} ({buildTarget}) failed:\n{FormatMessages(info.Messages)}"); + + foreach (var constantBuffer in info.ConstantBuffers) + { + reflected.Append($" {stage} {constantBuffer.Name}:"); + foreach (var field in constantBuffer.Fields) + { + reflected.Append($" {field.Name}"); + if (!field.Name.StartsWith(k_LightTypesField)) + continue; + + foundField = true; + persistentLayout |= constantBuffer.Name == k_LightCookiesBuffer && field.Columns == 4; + } + reflected.AppendLine(); + } + } + + // The field-wise layout can be loose uniforms, which the reflection may not report: only the persistent layout must be found. + if (expectPersistent) + Assert.IsTrue(foundField, $"{k_LightTypesField} not found when compiling for {compilerPlatform} ({buildTarget}). Constant buffers:\n{reflected}"); + + Assert.AreEqual(expectPersistent, persistentLayout, + $"For {compilerPlatform} ({buildTarget}), RenderingUtils.usePersistentConstantBuffer is {expectPersistent}, " + + $"but the shaders use the {(persistentLayout ? "persistent" : "field-wise")} light cookie layout. " + + $"Check URP_PERSISTENT_CONSTANT_BUFFERS_ACTIVE in GlobalShaderVariables.hlsl. Constant buffers:\n{reflected}"); + } + + static ShaderData.Pass FindPass(ShaderData shaderData, string passName) + { + for (int subshaderIndex = 0; subshaderIndex < shaderData.SerializedSubshaderCount; ++subshaderIndex) + { + ShaderData.Subshader subshader = shaderData.GetSerializedSubshader(subshaderIndex); + for (int passIndex = 0; passIndex < subshader.PassCount; ++passIndex) + { + ShaderData.Pass pass = subshader.GetPass(passIndex); + if (pass.Name == passName) + return pass; + } + } + return null; + } + + static string FormatMessages(ShaderMessage[] messages) + { + var builder = new StringBuilder(); + foreach (var message in messages) + builder.AppendLine($" {message.message}"); + return builder.ToString(); + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/PersistentConstantBufferLayoutTests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Editor/PersistentConstantBufferLayoutTests.cs.meta new file mode 100644 index 00000000000..f28d4257c81 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/PersistentConstantBufferLayoutTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 69c81696bf48477ba47b675f69218e65 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/PostProcessDataTests/1.shader b/Packages/com.unity.render-pipelines.universal/Tests/Editor/PostProcessDataTests/1.shader index 86b9da13c16..453a850564d 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Editor/PostProcessDataTests/1.shader +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/PostProcessDataTests/1.shader @@ -1,53 +1,23 @@ -Shader "Hidden/Custom/Test Shader" +Shader "Hidden/Universal/Tests/PostProcessDataTest1" { - Properties - { - _Color ("Color", Color) = (1,1,1,1) - _MainTex ("Albedo (RGB)", 2D) = "white" {} - _Glossiness ("Smoothness", Range(0,1)) = 0.5 - _Metallic ("Metallic", Range(0,1)) = 0.0 - } SubShader { - Tags { "RenderType"="Opaque" } - LOD 200 - - CGPROGRAM - // Physically based Standard lighting model, and enable shadows on all light types - #pragma surface surf Standard fullforwardshadows - - // Use shader model 3.0 target, to get nicer looking lighting - #pragma target 3.0 - - sampler2D _MainTex; - - struct Input + Pass { - float2 uv_MainTex; - }; + HLSLPROGRAM + #pragma vertex vert + #pragma fragment frag - half _Glossiness; - half _Metallic; - fixed4 _Color; + float4 vert(float4 positionOS : POSITION) : SV_POSITION + { + return positionOS; + } - // Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader. - // See https://docs.unity3d.com/Manual/GPUInstancing.html for more information about instancing. - // #pragma instancing_options assumeuniformscaling - UNITY_INSTANCING_BUFFER_START(Props) - // put more per-instance properties here - UNITY_INSTANCING_BUFFER_END(Props) - - void surf (Input IN, inout SurfaceOutputStandard o) - { - // Albedo comes from a texture tinted by color - fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color; - o.Albedo = c.rgb; - // Metallic and smoothness come from slider variables - o.Metallic = _Metallic; - o.Smoothness = _Glossiness; - o.Alpha = c.a; + half4 frag() : SV_Target + { + return 0; + } + ENDHLSL } - ENDCG } - FallBack "Diffuse" } diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/PostProcessDataTests/2.shader b/Packages/com.unity.render-pipelines.universal/Tests/Editor/PostProcessDataTests/2.shader index 86b9da13c16..de459c3f1eb 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Editor/PostProcessDataTests/2.shader +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/PostProcessDataTests/2.shader @@ -1,53 +1,23 @@ -Shader "Hidden/Custom/Test Shader" +Shader "Hidden/Universal/Tests/PostProcessDataTest2" { - Properties - { - _Color ("Color", Color) = (1,1,1,1) - _MainTex ("Albedo (RGB)", 2D) = "white" {} - _Glossiness ("Smoothness", Range(0,1)) = 0.5 - _Metallic ("Metallic", Range(0,1)) = 0.0 - } SubShader { - Tags { "RenderType"="Opaque" } - LOD 200 - - CGPROGRAM - // Physically based Standard lighting model, and enable shadows on all light types - #pragma surface surf Standard fullforwardshadows - - // Use shader model 3.0 target, to get nicer looking lighting - #pragma target 3.0 - - sampler2D _MainTex; - - struct Input + Pass { - float2 uv_MainTex; - }; + HLSLPROGRAM + #pragma vertex vert + #pragma fragment frag - half _Glossiness; - half _Metallic; - fixed4 _Color; + float4 vert(float4 positionOS : POSITION) : SV_POSITION + { + return positionOS; + } - // Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader. - // See https://docs.unity3d.com/Manual/GPUInstancing.html for more information about instancing. - // #pragma instancing_options assumeuniformscaling - UNITY_INSTANCING_BUFFER_START(Props) - // put more per-instance properties here - UNITY_INSTANCING_BUFFER_END(Props) - - void surf (Input IN, inout SurfaceOutputStandard o) - { - // Albedo comes from a texture tinted by color - fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color; - o.Albedo = c.rgb; - // Metallic and smoothness come from slider variables - o.Metallic = _Metallic; - o.Smoothness = _Glossiness; - o.Alpha = c.a; + half4 frag() : SV_Target + { + return 0; + } + ENDHLSL } - ENDCG } - FallBack "Diffuse" } diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/RenderGraphTests.HelperPasses.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/RenderGraphTests.HelperPasses.cs index 5436710aac2..86e268696cd 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Editor/RenderGraphTests.HelperPasses.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/RenderGraphTests.HelperPasses.cs @@ -11,11 +11,24 @@ namespace UnityEngine.Rendering.Tests { internal partial class RenderGraphTests : RenderGraphTestsCore { + UniversalRenderPipelineRuntimeShaders m_URPRuntimeShaders; + [OneTimeSetUp] public void OneTimeSetup() { - if (!(GraphicsSettings.currentRenderPipeline is UniversalRenderPipelineAsset)) - Assert.Ignore("Current pipeline is not URP. Skipping tests..."); + // RenderGraphTestsCore.Setup() has already replaced the project's render pipeline. + var projectRenderPipeline = m_OldQualityRenderPipeline != null ? m_OldQualityRenderPipeline : m_OldDefaultRenderPipeline; + if (!(projectRenderPipeline is UniversalRenderPipelineAsset)) + Assert.Ignore("The project's render pipeline is not URP. Skipping tests..."); + + Assert.IsTrue(EditorGraphicsSettings.TryGetRenderPipelineSettingsForPipeline(out m_URPRuntimeShaders), + "URP project without URP runtime shaders in its URP global settings."); + } + + [TearDown] + public void TearDown() + { + Blitter.Cleanup(); } static GraphicsFormat[] depthBlitTestFormats = @@ -63,13 +76,9 @@ public void UtilityPasses_CopyDepth( const int kWidth = 4; const int kHeight = 4; - // Verify if the test is being executed in a non-URP project (e.g pipeline asset set to null) - if (!EditorGraphicsSettings.TryGetRenderPipelineSettingsForPipeline(out var shaders)) - return; - - if (Blitter.GetBlitMaterial(TextureDimension.Tex2D) == null && shaders != null) + if (Blitter.GetBlitMaterial(TextureDimension.Tex2D) == null) { - Blitter.Initialize(shaders.coreBlitPS, shaders.coreBlitColorAndDepthPS); + Blitter.Initialize(m_URPRuntimeShaders.coreBlitPS, m_URPRuntimeShaders.coreBlitColorAndDepthPS); } float expectedDepthValue = 0.20f; @@ -108,7 +117,6 @@ public void UtilityPasses_CopyDepth( sourceDepth.Release(); destinationDepth.Release(); depthAsColor.Release(); - Blitter.Cleanup(); } [Test] @@ -117,13 +125,9 @@ public void UtilityPasses_CopyDepthWithMaterial([ValueSource(nameof(depthBlitTes const int kWidth = 4; const int kHeight = 4; - // Verify if the test is being executed in a non-URP project (e.g pipeline asset set to null) - if (!EditorGraphicsSettings.TryGetRenderPipelineSettingsForPipeline(out var shaders)) - return; - - if (Blitter.GetBlitMaterial(TextureDimension.Tex2D) == null && shaders != null) + if (Blitter.GetBlitMaterial(TextureDimension.Tex2D) == null) { - Blitter.Initialize(shaders.coreBlitPS, shaders.coreBlitColorAndDepthPS); + Blitter.Initialize(m_URPRuntimeShaders.coreBlitPS, m_URPRuntimeShaders.coreBlitColorAndDepthPS); } float expectedDepthValue = 0.20f; @@ -136,7 +140,7 @@ public void UtilityPasses_CopyDepthWithMaterial([ValueSource(nameof(depthBlitTes var destinationDepth = CreateDepthTexture(kWidth, kHeight, 0.0f, depthFormat, false, true); var depthAsColor = RTHandles.Alloc(kWidth, kHeight, GraphicsFormat.R32_SFloat, - dimension: TextureXR.dimension, + dimension: TextureDimension.Tex2D, useMipMap: false, autoGenerateMips: false, name: "Depth As Color Texture 32 bit"); @@ -156,7 +160,7 @@ public void UtilityPasses_CopyDepthWithMaterial([ValueSource(nameof(depthBlitTes var destination = m_RenderGraph.ImportTexture(depthAsColor); // First do a copy from depth to depth, moving the value of 0.25 depth to the intermediate buffer. - m_RenderGraph.AddBlitPass(new BlitMaterialParameters(source, intermediate, customDepthToColorMaterial, 0)); + m_RenderGraph.AddBlitPass(new BlitMaterialParameters(source, destination, customDepthToColorMaterial, 0) { destinationDepth = intermediate }); m_RenderGraph.AddBlitPass(new BlitMaterialParameters(intermediate, destination, customDepthToColorMaterial, 1)); }; @@ -164,8 +168,8 @@ public void UtilityPasses_CopyDepthWithMaterial([ValueSource(nameof(depthBlitTes CoreUtils.Destroy(customDepthToColorMaterial); sourceDepth.Release(); + destinationDepth.Release(); depthAsColor.Release(); - Blitter.Cleanup(); } void RenderReadbackAndAssert(RTHandle colorBuffer, float expectedDepthValue) diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/RenderPassCullingTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/RenderPassCullingTests.cs index 0aa8ae307b8..b2164e68375 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Editor/RenderPassCullingTests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/RenderPassCullingTests.cs @@ -1,9 +1,10 @@ using System; using System.Collections.Generic; using NUnit.Framework; -using UnityEngine.Profiling; using UnityEngine.Rendering.RenderGraphModule; using UnityEngine.Rendering.Universal; +using UnityEngine.TestTools.Constraints; +using Is = UnityEngine.TestTools.Constraints.Is; namespace UnityEngine.Rendering.Tests { @@ -29,8 +30,6 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer class RenderGraphTestsCulling { - static Recorder gcAllocRecorder = Recorder.Get("GC.Alloc"); - const int kLightCount = 3; CullingTestRenderPass m_TestRenderPass; @@ -136,23 +135,9 @@ void SubmitCameraRenderRequest(Camera camera) void ValidateNoGCAllocs(Action action) { // Warmup - this will catch static c'tors etc. - CountGCAllocs(action); - - // Actual test. - var count = CountGCAllocs(action); - if (count != 0) - throw new AssertionException($"Expected 0 GC allocations but there were {count}"); - } - - int CountGCAllocs(Action action) - { - gcAllocRecorder.FilterToCurrentThread(); - gcAllocRecorder.enabled = true; - action(); - gcAllocRecorder.enabled = false; - return gcAllocRecorder.sampleBlockCount; + Assert.That(() => action(), Is.Not.AllocatingGCMemory()); } } } diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ScalingModeTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ScalingModeTests.cs new file mode 100644 index 00000000000..e0e1871cbc0 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ScalingModeTests.cs @@ -0,0 +1,162 @@ +using NUnit.Framework; +using UnityEngine; +using UnityEngine.Rendering; +using UnityEngine.Rendering.Universal; + +namespace UnityEditor.Rendering.Universal.Tests +{ + // Covers the public UniversalRenderPipelineAsset.scalingMode: ScalingMode.None must leave the pipeline without an + // active upscaler, and a game camera must then render at its native resolution with no upscaling step. + class ScalingModeTests + { + // Records the camera data URP resolved for the test camera, so the tests can inspect it after rendering. + class CaptureCameraDataFeature : ScriptableRendererFeature + { + public Camera targetCamera; + public bool captured; + public ImageScalingMode imageScalingMode; + public float renderScale; + public int targetWidth; + public int targetHeight; + + public override void Create() { } + + public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData renderingData) + { + if (renderingData.cameraData.camera != targetCamera) + return; + + captured = true; + imageScalingMode = renderingData.cameraData.imageScalingMode; + renderScale = renderingData.cameraData.renderScale; + targetWidth = renderingData.cameraData.cameraTargetDescriptor.width; + targetHeight = renderingData.cameraData.cameraTargetDescriptor.height; + } + } + + const int k_TargetSize = 64; + + UniversalRendererData m_RendererData; + UniversalRenderPipelineAsset m_PipelineAsset; + CaptureCameraDataFeature m_CaptureFeature; + RenderPipelineAsset m_PreviousQualityPipeline; + bool m_PipelineOverridden; + GameObject m_CameraGO; + Camera m_Camera; + RenderTexture m_TargetTexture; + + [SetUp] + public void SetUp() + { + if (GraphicsSettings.currentRenderPipeline is not UniversalRenderPipelineAsset) + Assert.Ignore("Requires URP to be the active render pipeline."); + + m_PreviousQualityPipeline = QualitySettings.renderPipeline; + + m_CaptureFeature = ScriptableObject.CreateInstance(); + m_RendererData = ScriptableObject.CreateInstance(); + m_RendererData.rendererFeatures.Add(m_CaptureFeature); + + // Create() populates the default upscaler priority list (STP, then Auto), so the upscaler selection + // depends only on scalingMode. + m_PipelineAsset = UniversalRenderPipelineAsset.Create(m_RendererData); + + m_TargetTexture = new RenderTexture(k_TargetSize, k_TargetSize, 24); + m_CameraGO = new GameObject("ScalingModeTestCamera") { hideFlags = HideFlags.HideAndDontSave }; + m_Camera = m_CameraGO.AddComponent(); + m_Camera.targetTexture = m_TargetTexture; + m_CameraGO.AddComponent(); + m_CaptureFeature.targetCamera = m_Camera; + } + + [TearDown] + public void TearDown() + { + // Restore first: teardown also runs when setup throws part way through. + if (m_PipelineOverridden) + { + QualitySettings.renderPipeline = m_PreviousQualityPipeline; + m_PipelineOverridden = false; + } + + if (m_CameraGO != null) + Object.DestroyImmediate(m_CameraGO); + if (m_TargetTexture != null) + { + m_TargetTexture.Release(); + Object.DestroyImmediate(m_TargetTexture); + } + if (m_PipelineAsset != null) + Object.DestroyImmediate(m_PipelineAsset); + if (m_RendererData != null) + Object.DestroyImmediate(m_RendererData); + if (m_CaptureFeature != null) + Object.DestroyImmediate(m_CaptureFeature); + } + + // The upscaler is resolved once when the pipeline is created, so scalingMode has to be set before the asset + // becomes active. Rendering the camera creates the pipeline from the asset. + UniversalRenderPipeline RenderWithScalingMode(ScalingMode scalingMode) + { + m_PipelineAsset.scalingMode = scalingMode; + QualitySettings.renderPipeline = m_PipelineAsset; + m_PipelineOverridden = true; + + m_Camera.Render(); + + Assert.AreSame(m_PipelineAsset, GraphicsSettings.currentRenderPipeline, "The test asset is not the active pipeline asset."); + var pipeline = RenderPipelineManager.currentPipeline as UniversalRenderPipeline; + Assert.IsNotNull(pipeline, "URP was not created for the test asset."); + Assert.IsTrue(m_CaptureFeature.captured, "The test camera was not rendered by URP."); + return pipeline; + } + + [Test] + public void ScalingModeNone_HasNoActiveUpscaler() + { + var pipeline = RenderWithScalingMode(ScalingMode.None); + + Assert.AreEqual(ScalingMode.None, m_PipelineAsset.scalingMode); + Assert.IsEmpty(pipeline.activeUpscalerName, "ScalingMode.None should leave the pipeline without an active upscaler."); + } + + [Test] + public void ScalingModeNone_CameraRendersAtNativeResolution() + { + RenderWithScalingMode(ScalingMode.None); + + Assert.AreEqual(ImageScalingMode.None, m_CaptureFeature.imageScalingMode, "ScalingMode.None should not upscale the camera."); + Assert.AreEqual(1.0f, m_CaptureFeature.renderScale); + Assert.AreEqual(m_Camera.pixelWidth, m_CaptureFeature.targetWidth); + Assert.AreEqual(m_Camera.pixelHeight, m_CaptureFeature.targetHeight); + } + + // Guards the tests above: with the same asset, Upscaling selects an upscaler, so an empty name under None is + // caused by scalingMode and not by the device lacking upscaler support. + [Test] + public void ScalingModeUpscaling_HasActiveUpscaler() + { + var pipeline = RenderWithScalingMode(ScalingMode.Upscaling); + + Assert.IsNotEmpty(pipeline.activeUpscalerName, "ScalingMode.Upscaling should select an upscaler from the priority list."); + } + + // The upscaler is resolved when the pipeline is created, so setting scalingMode on the already-active asset must + // recreate the pipeline for the change to take effect. This covers the setter path that does not go through the + // inspector. + [Test] + public void ScalingMode_SetAfterPipelineActive_RecreatesPipeline() + { + var upscalingPipeline = RenderWithScalingMode(ScalingMode.Upscaling); + Assert.IsNotEmpty(upscalingPipeline.activeUpscalerName, "ScalingMode.Upscaling should select an upscaler from the priority list."); + + m_PipelineAsset.scalingMode = ScalingMode.None; + m_Camera.Render(); + + var pipeline = RenderPipelineManager.currentPipeline as UniversalRenderPipeline; + Assert.IsNotNull(pipeline, "URP was not created for the test asset."); + Assert.AreNotSame(upscalingPipeline, pipeline, "Setting scalingMode should recreate the current pipeline."); + Assert.IsEmpty(pipeline.activeUpscalerName, "ScalingMode.None should leave the pipeline without an active upscaler after recreation."); + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ScalingModeTests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ScalingModeTests.cs.meta new file mode 100644 index 00000000000..c03fc5c39b0 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ScalingModeTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 91e1fcb5fc9d4d09b12bfcaf786c377f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShaderBuildPreprocessorTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShaderBuildPreprocessorTests.cs index 16cc3355b73..545832330ca 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShaderBuildPreprocessorTests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShaderBuildPreprocessorTests.cs @@ -46,6 +46,9 @@ internal ShaderFeatures defaultURPAssetFeatures if (PlayerSettings.allowHDRDisplaySupport) defaultFeatures |= ShaderFeatures.HdrGrading; + if (ShadowUtils.IsShadowReceiverNormalBiasEnabled()) + defaultFeatures |= ShaderFeatures.ShadowReceiverNormalBias; + return defaultFeatures; } } @@ -434,6 +437,30 @@ public void TestGetSupportedShaderFeaturesFromAsset_LightFalloff() } } + // ShaderFeatures.ShadowReceiverNormalBias - _SHADOW_RECEIVER_NORMAL_BIAS + [Test] + public void TestGetSupportedShaderFeaturesFromAsset_ShadowReceiverNormalBias() + { + var shadowBiasSettings = GraphicsSettings.GetRenderPipelineSettings(); + ShadowNormalBiasMode previousNormalBiasMode = shadowBiasSettings.normalBiasMode; + try + { + shadowBiasSettings.normalBiasMode = ShadowNormalBiasMode.Caster; + ShaderFeatures actual = m_TestHelper.GetSupportedShaderFeaturesFromAsset(); + ShaderFeatures expected = m_TestHelper.defaultURPAssetFeatures & ~ShaderFeatures.ShadowReceiverNormalBias; + m_TestHelper.AssertShaderFeaturesAndReset(expected, actual); + + shadowBiasSettings.normalBiasMode = ShadowNormalBiasMode.Receiver; + actual = m_TestHelper.GetSupportedShaderFeaturesFromAsset(); + expected = m_TestHelper.defaultURPAssetFeatures | ShaderFeatures.ShadowReceiverNormalBias; + m_TestHelper.AssertShaderFeaturesAndReset(expected, actual); + } + finally + { + shadowBiasSettings.normalBiasMode = previousNormalBiasMode; + } + } + [Test] public void TestGetRendererRequirements() { @@ -890,6 +917,29 @@ public void TestStripUnusedPostProcessingVariants_BloomHQDirt() }, VolumeFeatures.BloomHQDirt); } + [Test] + public void TestStripUnusedPostProcessingVariants_ScreenSpaceLensFlare_WithoutBloom() + { + AssertVolumeFeaturesFromProfile(profile => + { + var lensFlare = profile.Add(overrides: true); + lensFlare.intensity.Override(1f); + }, VolumeFeatures.BloomLQ); + } + + [Test] + public void TestStripUnusedPostProcessingVariants_ScreenSpaceLensFlare_WithInactiveBloom() + { + AssertVolumeFeaturesFromProfile(profile => + { + var lensFlare = profile.Add(overrides: true); + lensFlare.intensity.Override(1f); + var bloom = profile.Add(overrides: true); + bloom.intensity.Override(0f); + bloom.highQualityFiltering.Override(true); + }, VolumeFeatures.BloomHQ); + } + [Test] public void TestStripUnusedPostProcessingVariants_InactiveFeatures_AreNotReturned() { @@ -905,6 +955,7 @@ public void TestStripUnusedPostProcessingVariants_InactiveFeatures_AreNotReturne profile.Add(overrides: true); profile.Add(overrides: true); profile.Add(overrides: true); + profile.Add(overrides: true); }, VolumeFeatures.None); } @@ -1041,12 +1092,21 @@ public void TestGetSupportedShaderFeaturesFromRendererFeatures_ScreenSpaceShadow // Initial RendererRequirements rendererRequirements = m_TestHelper.defaultRendererRequirements; + rendererRequirements.needsMainLightShadows = true; ShaderFeatures actual = m_TestHelper.GetSupportedShaderFeaturesFromRendererFeatures(rendererRequirements); ShaderFeatures expected = ShaderFeatures.ScreenSpaceShadows; m_TestHelper.AssertShaderFeaturesAndReset(expected, actual); + // Main light shadows disabled + rendererRequirements = m_TestHelper.defaultRendererRequirements; + rendererRequirements.needsMainLightShadows = false; + actual = m_TestHelper.GetSupportedShaderFeaturesFromRendererFeatures(rendererRequirements); + expected = ShaderFeatures.None; + m_TestHelper.AssertShaderFeaturesAndReset(expected, actual); + m_TestHelper.rendererFeatures[0].SetActive(false); rendererRequirements = m_TestHelper.defaultRendererRequirements; + rendererRequirements.needsMainLightShadows = true; actual = m_TestHelper.GetSupportedShaderFeaturesFromRendererFeatures(rendererRequirements); expected = ShaderFeatures.None; m_TestHelper.AssertShaderFeaturesAndReset(expected, actual); diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShaderPrefilteringTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShaderPrefilteringTests.cs index bdd627294d7..7b60e2e6cb6 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShaderPrefilteringTests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShaderPrefilteringTests.cs @@ -320,6 +320,26 @@ public void TestCreatePrefilteringSettings_LightFalloff() helper.AssertPrefilteringData(expected, actual); } + [Test] + public void TestCreatePrefilteringSettings_ShadowReceiverNormalBias() + { + ShaderPrefilteringData actual; + ShaderPrefilteringData expected; + TestHelper helper = new(); + + // Caster + expected = helper.defaultPrefilteringData; + expected.stripShadowReceiverNormalBias = true; + actual = helper.CreatePrefilteringSettings(ShaderFeatures.None); + helper.AssertPrefilteringData(expected, actual); + + // Receiver + expected = helper.defaultPrefilteringData; + expected.stripShadowReceiverNormalBias = false; + actual = helper.CreatePrefilteringSettings(ShaderFeatures.ShadowReceiverNormalBias); + helper.AssertPrefilteringData(expected, actual); + } + [Test] public void TestCreatePrefilteringSettings_RenderingLayers() { diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShaderScriptableStripperTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShaderScriptableStripperTests.cs index bc50476a3fd..a364e9ecfd6 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShaderScriptableStripperTests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShaderScriptableStripperTests.cs @@ -237,6 +237,7 @@ public void TestStripUnusedPass(string shaderName) TestStripUnusedPass_XR(shader); TestStripUnusedPass_ShadowCaster(shader); TestStripUnusedPass_Decals(shader); + TestStripUnusedPass_RenderingLayerMask2D(shader); } public void TestStripUnusedPass_2D(Shader shader) @@ -298,6 +299,25 @@ public void TestStripUnusedPass_XR(Shader shader) helper.IsTrue(helper.stripper.StripUnusedPass(ref helper.data)); } + public void TestStripUnusedPass_RenderingLayerMask2D(Shader shader) + { + TestHelper helper; + + helper = new TestHelper(shader, ShaderFeatures.None); + helper.data.passName = ShaderScriptableStripper.kPassNameRenderingLayerMask2D; + helper.IsTrue(helper.stripper.StripUnusedPass_RenderingLayerMask2D(ref helper.data)); + helper.IsTrue(helper.stripper.StripUnusedPass(ref helper.data)); + + helper = new TestHelper(shader, ShaderFeatures.LightLayers); + helper.data.passName = ShaderScriptableStripper.kPassNameRenderingLayerMask2D; + helper.IsFalse(helper.stripper.StripUnusedPass_RenderingLayerMask2D(ref helper.data)); + helper.IsFalse(helper.stripper.StripUnusedPass(ref helper.data)); + + helper = new TestHelper(shader, ShaderFeatures.None); + helper.data.passName = ShaderScriptableStripper.kPassNameUniversal2D; + helper.IsFalse(helper.stripper.StripUnusedPass_RenderingLayerMask2D(ref helper.data)); + } + public void TestStripUnusedPass_ShadowCaster(Shader shader) { TestHelper helper; @@ -502,6 +522,7 @@ public void TestStripInvalidVariants(string shaderName, bool expectedTerrainHole StripInvalidVariants_TerrainHoles(shader, expectedTerrainHoles, expectedTerrainHolesWithAlphaTestOn); TestStripInvalidVariants_Shadows(shader, expectedSoftShadows); TestStripInvalidVariants_AdditionalLights(shader); + TestStripInvalidVariants_GTAODepthSource(shader); } public void TestStripInvalidVariants_HDR(Shader shader) @@ -687,6 +708,54 @@ public void TestStripInvalidVariants_AdditionalLights(Shader shader) helper.AreEqual(shader != null, helper.stripper.StripInvalidVariants_AdditionalLights(ref helper.data)); } + public void TestStripInvalidVariants_GTAODepthSource(Shader shader) + { + bool isCorrectShader = shader == Shader.Find("Hidden/Universal Render Pipeline/ScreenSpaceAmbientOcclusion"); + TestHelper helper; + string depthNormalsKeyword = ScreenSpaceAmbientOcclusionKeywords.k_SourceDepthNormalsKeyword; + string[] gtaoKeywords = + { + ScreenSpaceAmbientOcclusionKeywords.k_GTAOModeKeyword, + ScreenSpaceAmbientOcclusionKeywords.k_GTAODepthPyramidKeyword, + }; + string[] reconstructedNormalsKeywords = + { + ScreenSpaceAmbientOcclusionKeywords.k_SourceDepthLowKeyword, + ScreenSpaceAmbientOcclusionKeywords.k_SourceDepthMediumKeyword, + ScreenSpaceAmbientOcclusionKeywords.k_SourceDepthHighKeyword, + }; + + foreach (var gtaoKeyword in gtaoKeywords) + { + // Invalid: GTAO with a reconstructed normals source + foreach (var sourceKeyword in reconstructedNormalsKeywords) + { + helper = new TestHelper(shader, ShaderFeatures.None); + helper.data.IsHDRShaderVariantValid = true; + TestHelper.s_EnabledKeywords = new List { gtaoKeyword, sourceKeyword }; + helper.AreEqual(isCorrectShader, helper.stripper.StripInvalidVariants_GTAODepthSource(ref helper.data)); + helper.AreEqual(isCorrectShader, helper.stripper.StripInvalidVariants(ref helper.data)); + } + + // Valid: GTAO with the normals texture + helper = new TestHelper(shader, ShaderFeatures.None); + helper.data.IsHDRShaderVariantValid = true; + TestHelper.s_EnabledKeywords = new List { gtaoKeyword, depthNormalsKeyword }; + helper.IsFalse(helper.stripper.StripInvalidVariants_GTAODepthSource(ref helper.data)); + helper.IsFalse(helper.stripper.StripInvalidVariants(ref helper.data)); + } + + // Valid: SSAO with a reconstructed normals source + foreach (var sourceKeyword in reconstructedNormalsKeywords) + { + helper = new TestHelper(shader, ShaderFeatures.None); + helper.data.IsHDRShaderVariantValid = true; + TestHelper.s_EnabledKeywords = new List { sourceKeyword }; + helper.IsFalse(helper.stripper.StripInvalidVariants_GTAODepthSource(ref helper.data)); + helper.IsFalse(helper.stripper.StripInvalidVariants(ref helper.data)); + } + } + /***************************************************** * Unsupported Variants *****************************************************/ @@ -817,6 +886,7 @@ public void TestStripUnusedFeatures(string shaderName) TestStripUnusedFeatures_DebugDisplay(shader); TestStripUnusedFeatures_ScreenCoordOverride(shader); + TestStripUnusedFeatures_ReflectionProbeRotation(shader); TestStripUnusedFeatures_PunctualLightShadows(shader); TestStripUnusedFeatures_FoveatedRendering(shader); TestStripUnusedFeatures_DeferredRendering(shader); @@ -824,6 +894,7 @@ public void TestStripUnusedFeatures(string shaderName) TestStripUnusedFeatures_AdditionalLightShadows(shader); TestStripUnusedFeatures_MixedLighting(shader); TestStripUnusedFeatures_SoftShadows(shader); + TestStripUnusedFeatures_PCSS(shader); TestStripUnusedFeatures_HDRGrading(shader); TestStripUnusedFeatures_UseFastSRGBLinearConversion(shader); TestStripUnusedFeatures_LightLayers(shader); @@ -841,6 +912,7 @@ public void TestStripUnusedFeatures(string shaderName) TestStripUnusedFeatures_LightCookies(shader); TestStripUnusedFeatures_VolumetricFog(shader); TestStripUnusedFeatures_LightFalloffQuadratic(shader); + TestStripUnusedFeatures_ShadowReceiverNormalBias(shader); TestStripUnusedFeatures_ProbesVolumes(shader); TestStripUnusedFeatures_SHAuto(shader); TestStripUnusedFeatures_DataDrivenLensFlare(shader); @@ -902,6 +974,50 @@ public void TestStripUnusedFeatures_ScreenCoordOverride(Shader shader) helper.AreEqual(shader != null, helper.stripper.StripUnusedFeatures_ScreenCoordOverride(ref helper.data)); } + public void TestStripUnusedFeatures_ReflectionProbeRotation(Shader shader) + { + TestHelper helper; + + helper = new TestHelper(shader, ShaderFeatures.None); + helper.data.stripReflectionProbeRotationVariants = false; + helper.IsFalse(helper.stripper.StripUnusedFeatures_ReflectionProbeRotation(ref helper.data)); + + helper = new TestHelper(shader, ShaderFeatures.None); + helper.data.stripReflectionProbeRotationVariants = false; + TestHelper.s_EnabledKeywords = new List() {ShaderKeywordStrings.ReflectionProbeRotation}; + TestHelper.s_PassKeywords = new List() {ShaderKeywordStrings.ReflectionProbeRotation}; + helper.IsFalse(helper.stripper.StripUnusedFeatures_ReflectionProbeRotation(ref helper.data)); + + helper = new TestHelper(shader, ShaderFeatures.None); + helper.data.stripReflectionProbeRotationVariants = false; + TestHelper.s_PassKeywords = new List() {ShaderKeywordStrings.ReflectionProbeRotation}; + helper.AreEqual(shader != null, helper.stripper.StripUnusedFeatures_ReflectionProbeRotation(ref helper.data)); + + helper = new TestHelper(shader, ShaderFeatures.None); + helper.data.stripReflectionProbeRotationVariants = true; + TestHelper.s_PassKeywords = new List() {ShaderKeywordStrings.ReflectionProbeRotation}; + helper.IsFalse(helper.stripper.StripUnusedFeatures_ReflectionProbeRotation(ref helper.data)); + + helper = new TestHelper(shader, ShaderFeatures.None); + helper.data.stripReflectionProbeRotationVariants = true; + TestHelper.s_EnabledKeywords = new List() {ShaderKeywordStrings.ReflectionProbeRotation}; + TestHelper.s_PassKeywords = new List() {ShaderKeywordStrings.ReflectionProbeRotation}; + helper.AreEqual(shader != null, helper.stripper.StripUnusedFeatures_ReflectionProbeRotation(ref helper.data)); + + // A dynamic keyword resolves at runtime, so its single variant must be kept + helper = new TestHelper(shader, ShaderFeatures.None); + helper.data.stripReflectionProbeRotationVariants = false; + TestHelper.s_PassKeywords = new List() {ShaderKeywordStrings.ReflectionProbeRotation}; + TestHelper.s_DynamicKeywords = new List() {ShaderKeywordStrings.ReflectionProbeRotation}; + helper.IsFalse(helper.stripper.StripUnusedFeatures_ReflectionProbeRotation(ref helper.data)); + + helper = new TestHelper(shader, ShaderFeatures.None); + helper.data.stripReflectionProbeRotationVariants = true; + TestHelper.s_PassKeywords = new List() {ShaderKeywordStrings.ReflectionProbeRotation}; + TestHelper.s_DynamicKeywords = new List() {ShaderKeywordStrings.ReflectionProbeRotation}; + helper.IsFalse(helper.stripper.StripUnusedFeatures_ReflectionProbeRotation(ref helper.data)); + } + public void TestStripUnusedFeatures_PunctualLightShadows(Shader shader) { TestHelper helper; @@ -1410,6 +1526,52 @@ public void TestStripUnusedFeatures_SoftShadows(Shader shader) helper.IsTrue(helper.stripper.StripUnusedFeatures_SoftShadowsQualityLevels(ref helper.data, ref helper.featureStripTool)); } + public void TestStripUnusedFeatures_PCSS(Shader shader) + { + TestHelper helper; + + helper = new TestHelper(shader, ShaderFeatures.None); + helper.IsFalse(helper.stripper.StripUnusedFeatures_PCSS(ref helper.data, ref helper.featureStripTool)); + + helper = new TestHelper(shader, ShaderFeatures.None); + TestHelper.s_EnabledKeywords = new List() { ShaderKeywordStrings.ShadowsPCSS, ShaderKeywordStrings.SoftShadows }; + helper.AreEqual(shader != null, helper.stripper.StripUnusedFeatures_PCSS(ref helper.data, ref helper.featureStripTool)); + + helper = new TestHelper(shader, ShaderFeatures.ShadowsPCSS); + TestHelper.s_EnabledKeywords = new List() { ShaderKeywordStrings.ShadowsPCSS, ShaderKeywordStrings.SoftShadows }; + helper.IsFalse(helper.stripper.StripUnusedFeatures_PCSS(ref helper.data, ref helper.featureStripTool)); + + helper = new TestHelper(shader, ShaderFeatures.ShadowsPCSS); + TestHelper.s_EnabledKeywords = new List() { ShaderKeywordStrings.SoftShadows }; + helper.IsFalse(helper.stripper.StripUnusedFeatures_PCSS(ref helper.data, ref helper.featureStripTool)); + + // PCSS is only set with the per-light soft shadow keyword + helper = new TestHelper(shader, ShaderFeatures.ShadowsPCSS); + TestHelper.s_EnabledKeywords = new List() { ShaderKeywordStrings.ShadowsPCSS }; + helper.AreEqual(shader != null, helper.stripper.StripUnusedFeatures_PCSS(ref helper.data, ref helper.featureStripTool)); + + helper = new TestHelper(shader, ShaderFeatures.ShadowsPCSS | ShaderFeatures.SoftShadowsHigh); + TestHelper.s_EnabledKeywords = new List() { ShaderKeywordStrings.ShadowsPCSS, ShaderKeywordStrings.SoftShadowsHigh }; + helper.AreEqual(shader != null, helper.stripper.StripUnusedFeatures_PCSS(ref helper.data, ref helper.featureStripTool)); + + // A dynamic soft shadow keyword resolves at runtime + helper = new TestHelper(shader, ShaderFeatures.ShadowsPCSS); + TestHelper.s_EnabledKeywords = new List() { ShaderKeywordStrings.ShadowsPCSS }; + TestHelper.s_DynamicKeywords = new List() { ShaderKeywordStrings.SoftShadows }; + helper.IsFalse(helper.stripper.StripUnusedFeatures_PCSS(ref helper.data, ref helper.featureStripTool)); + + // GL doesn't support PCSS, so only its off variant remains + helper = new TestHelper(shader, ShaderFeatures.ShadowsPCSS); + TestHelper.s_EnabledKeywords = new List() { ShaderKeywordStrings.ShadowsPCSS, ShaderKeywordStrings.SoftShadows }; + helper.data.isGLDevice = true; + helper.AreEqual(shader != null, helper.stripper.StripUnusedFeatures_PCSS(ref helper.data, ref helper.featureStripTool)); + + helper = new TestHelper(shader, ShaderFeatures.ShadowsPCSS); + TestHelper.s_EnabledKeywords = new List() { ShaderKeywordStrings.SoftShadows }; + helper.data.isGLDevice = true; + helper.IsFalse(helper.stripper.StripUnusedFeatures_PCSS(ref helper.data, ref helper.featureStripTool)); + } + public void TestStripUnusedFeatures_HDRGrading(Shader shader) { TestHelper helper; @@ -2464,6 +2626,29 @@ public void TestStripUnusedFeatures_LightFalloffQuadratic(Shader shader) helper.IsFalse(helper.stripper.StripUnusedFeatures_LightFalloffQuadratic(ref helper.featureStripTool)); } + public void TestStripUnusedFeatures_ShadowReceiverNormalBias(Shader shader) + { + TestHelper helper; + + helper = new TestHelper(shader, ShaderFeatures.None); + TestHelper.s_PassKeywords = new List() { ShaderKeywordStrings.ShadowReceiverNormalBias }; + helper.IsFalse(helper.stripper.StripUnusedFeatures_ShadowReceiverNormalBias(ref helper.featureStripTool)); + + helper = new TestHelper(shader, ShaderFeatures.None); + TestHelper.s_EnabledKeywords = new List() { ShaderKeywordStrings.ShadowReceiverNormalBias }; + TestHelper.s_PassKeywords = new List() { ShaderKeywordStrings.ShadowReceiverNormalBias }; + helper.AreEqual(shader != null, helper.stripper.StripUnusedFeatures_ShadowReceiverNormalBias(ref helper.featureStripTool)); + + helper = new TestHelper(shader, ShaderFeatures.ShadowReceiverNormalBias); + TestHelper.s_PassKeywords = new List() { ShaderKeywordStrings.ShadowReceiverNormalBias }; + helper.AreEqual(shader != null, helper.stripper.StripUnusedFeatures_ShadowReceiverNormalBias(ref helper.featureStripTool)); + + helper = new TestHelper(shader, ShaderFeatures.ShadowReceiverNormalBias); + TestHelper.s_EnabledKeywords = new List() { ShaderKeywordStrings.ShadowReceiverNormalBias }; + TestHelper.s_PassKeywords = new List() { ShaderKeywordStrings.ShadowReceiverNormalBias }; + helper.IsFalse(helper.stripper.StripUnusedFeatures_ShadowReceiverNormalBias(ref helper.featureStripTool)); + } + public void TestStripUnusedFeatures_ProbesVolumes(Shader shader) { TestHelper helper; diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowCascadeSplitConversionTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowCascadeSplitConversionTests.cs new file mode 100644 index 00000000000..f420ece8d8b --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowCascadeSplitConversionTests.cs @@ -0,0 +1,122 @@ +using NUnit.Framework; +using UnityEditor.Rendering; +using UnityEditor.Rendering.Universal; + +namespace UnityEngine.Rendering.Universal.Tests +{ + class ShadowCascadeSplitConversionTests + { + const float k_Tolerance = 1e-5f; + + [TestCase(false, 50f, 100f)] + [TestCase(true, 50f, 50f)] + [TestCase(true, 0f, 0f)] + public void SplitScale_IsPercentOrMaxDistance(bool useMetric, float maxDistance, float expected) + { + Assert.AreEqual(expected, ShadowCascadeSplitGUI.SplitScale(useMetric, maxDistance)); + } + + static readonly object[] s_SplitFromSliderValueCases = + { + new object[] { 25f, new Vector4(0.1f, 0.5f, 0.8f, 1f), 1, 3, 100f, 0.25f }, + new object[] { 12.5f, new Vector4(0.1f, 0.5f, 0.8f, 1f), 1, 3, 50f, 0.25f }, + new object[] { 5f, new Vector4(0.2f, 0.5f, 0.8f, 1f), 1, 3, 100f, 0.201f }, + new object[] { 90f, new Vector4(0.2f, 0.5f, 0.8f, 1f), 1, 3, 100f, 0.799f }, + new object[] { 100f, new Vector4(0.2f, 0.5f, 0.8f, 1f), 2, 3, 100f, 1f }, + new object[] { 100f, new Vector4(0.5f, 1f, 0f, 0f), 0, 1, 100f, 1f }, + new object[] { 30f, new Vector4(0.5f, 1f, 0f, 0f), 0, 1, 0f, 0f }, + }; + + [TestCaseSource(nameof(s_SplitFromSliderValueCases))] + public void SplitFromSliderValue_ConvertsAndStaysBetweenNeighbors(float scaledValue, Vector4 splits, int index, int splitCount, float scale, float expected) + { + Assert.AreEqual(expected, ShadowCascadeSplitGUI.SplitFromSliderValue(scaledValue, splits, index, splitCount, scale), k_Tolerance); + } + + static readonly object[] s_LastBorderScaleCases = + { + new object[] { new Vector4(0.1f, 0.3f, 0.6f, 1f), 3, false, 50f, 100f }, + new object[] { new Vector4(0.1f, 0.3f, 0.6f, 1f), 3, true, 50f, 20f }, + new object[] { new Vector4(0.25f, 1f, 0f, 0f), 1, true, 40f, 30f }, + new object[] { new Vector4(1f, 0f, 0f, 0f), 0, true, 50f, 50f }, + }; + + [TestCaseSource(nameof(s_LastBorderScaleCases))] + public void LastBorderScale_IsPercentOrLastCascadeLength(Vector4 splits, int splitCount, bool useMetric, float maxDistance, float expected) + { + Assert.AreEqual(expected, ShadowCascadeSplitGUI.LastBorderScale(splits, splitCount, useMetric, maxDistance), k_Tolerance); + } + + [TestCase(5f, 20f, 0.25f)] + [TestCase(10f, 100f, 0.1f)] + [TestCase(5f, 0f, 0f)] + public void LastBorderFromSliderValue_DividesByScale(float scaledValue, float scale, float expected) + { + Assert.AreEqual(expected, ShadowCascadeSplitGUI.LastBorderFromSliderValue(scaledValue, scale), k_Tolerance); + } + + [Test] + public void ToCascades_GivesCascadeSizesBorderAndHandleStates() + { + var cascades = ShadowCascadeSplitGUI.ToCascades(new Vector4(0.1f, 0.3f, 0.6f, 1f), 0.2f, 4, new[] { true, false, true }, false); + + Assert.AreEqual(4, cascades.Length); + Assert.AreEqual(0.1f, cascades[0].size, k_Tolerance); + Assert.AreEqual(0.2f, cascades[1].size, k_Tolerance); + Assert.AreEqual(0.3f, cascades[2].size, k_Tolerance); + Assert.AreEqual(0.4f, cascades[3].size, k_Tolerance); + Assert.AreEqual(0.2f, cascades[3].borderSize, k_Tolerance); + + Assert.AreEqual(ShadowCascadeGUI.HandleState.Enabled, cascades[0].cascadeHandleState); + Assert.AreEqual(ShadowCascadeGUI.HandleState.Disabled, cascades[1].cascadeHandleState); + Assert.AreEqual(ShadowCascadeGUI.HandleState.Enabled, cascades[2].cascadeHandleState); + Assert.AreEqual(ShadowCascadeGUI.HandleState.Hidden, cascades[3].cascadeHandleState); + Assert.AreEqual(ShadowCascadeGUI.HandleState.Hidden, cascades[0].borderHandleState); + Assert.AreEqual(ShadowCascadeGUI.HandleState.Disabled, cascades[3].borderHandleState); + } + + [Test] + public void ToCascades_WithOneCascade_GivesTheWholeRange() + { + var cascades = ShadowCascadeSplitGUI.ToCascades(new Vector4(0.5f, 0.6f, 0.7f, 1f), 0.3f, 1, new bool[0], true); + + Assert.AreEqual(1, cascades.Length); + Assert.AreEqual(1f, cascades[0].size, k_Tolerance); + Assert.AreEqual(0.3f, cascades[0].borderSize, k_Tolerance); + Assert.AreEqual(ShadowCascadeGUI.HandleState.Enabled, cascades[0].borderHandleState); + } + + [Test] + public void FromCascades_AfterMovingAHandle_GivesCumulativeSplitsAndBorder() + { + var splits = new Vector4(0.1f, 0.3f, 0.6f, 1f); + var cascades = ShadowCascadeSplitGUI.ToCascades(splits, 0.2f, 4, new[] { true, true, true }, true); + cascades[0].size += 0.05f; + cascades[1].size -= 0.05f; + cascades[3].borderSize = 0.35f; + + ShadowCascadeSplitGUI.FromCascades(cascades, ref splits, out float border); + + Assert.AreEqual(0.15f, splits.x, k_Tolerance); + Assert.AreEqual(0.3f, splits.y, k_Tolerance); + Assert.AreEqual(0.6f, splits.z, k_Tolerance); + Assert.AreEqual(0.35f, border, k_Tolerance); + } + + static readonly object[] s_CascadeCountChangeCases = + { + new object[] { new Vector4(0.35f, 0.2f, 0.467f, 0f), 3, new Vector3(0.35f, 0.351f, 0.467f) }, + new object[] { new Vector4(0.15f, 0.45f, 0.467f, 0f), 3, new Vector3(0.15f, 0.45f, 0.467f) }, + new object[] { new Vector4(0.067f, 0.2f, 0.467f, 0f), 1, new Vector3(0.067f, 0.2f, 0.467f) }, + }; + + [TestCaseSource(nameof(s_CascadeCountChangeCases))] + public void SortSplits_AfterCascadeCountChange_KeepsTheNewlyUsedSplitsIncreasing(Vector4 splits, int splitCount, Vector3 expected) + { + Vector4 sorted = ShadowCascadeSplitGUI.SortSplits(splits, splitCount); + + for (int i = 0; i < splitCount; ++i) + Assert.AreEqual(expected[i], sorted[i], k_Tolerance, $"split {i}"); + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowCascadeSplitConversionTests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowCascadeSplitConversionTests.cs.meta new file mode 100644 index 00000000000..acc2d3b020b --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowCascadeSplitConversionTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 19beea07ad2febfde38f7d05c76aab97 diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowCascadeSplitGUITests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowCascadeSplitGUITests.cs new file mode 100644 index 00000000000..a41586e6bcc --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowCascadeSplitGUITests.cs @@ -0,0 +1,31 @@ +using NUnit.Framework; +using UnityEditor.Rendering.Universal; + +namespace UnityEngine.Rendering.Universal.Tests +{ + class ShadowCascadeSplitGUITests + { + const float k_Tolerance = 1e-5f; + + static readonly object[] s_SortSplitsCases = + { + new object[] { new Vector4(0.067f, 0.2f, 0.467f, 0f), 3, new Vector3(0.067f, 0.2f, 0.467f) }, + new object[] { new Vector4(0.1f, 0.3f, 0.467f, 0f), 2, new Vector3(0.1f, 0.3f, 0.467f) }, + new object[] { new Vector4(0.25f, 0.2f, 0.467f, 0f), 1, new Vector3(0.25f, 0.2f, 0.467f) }, + new object[] { new Vector4(0.8f, 0.9f, 0.467f, 0f), 3, new Vector3(0.8f, 0.9f, 0.901f) }, + new object[] { new Vector4(0.5f, 0.5f, 0.5f, 0f), 3, new Vector3(0.5f, 0.501f, 0.502f) }, + new object[] { new Vector4(1f, 1f, 1f, 0f), 3, new Vector3(0.997f, 0.998f, 0.999f) }, + new object[] { new Vector4(1f, 0.2f, 0.467f, 0f), 1, new Vector3(0.999f, 0.2f, 0.467f) }, + }; + + [TestCaseSource(nameof(s_SortSplitsCases))] + public void SortSplits_ReturnsIncreasingSplitsBelowOne(Vector4 splits, int splitCount, Vector3 expected) + { + Vector4 sorted = ShadowCascadeSplitGUI.SortSplits(splits, splitCount); + + for (int i = 0; i < splitCount; ++i) + Assert.AreEqual(expected[i], sorted[i], k_Tolerance, $"split {i}"); + Assert.AreEqual(1f, sorted[splitCount], $"split {splitCount}"); + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowCascadeSplitGUITests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowCascadeSplitGUITests.cs.meta new file mode 100644 index 00000000000..25cb1defa40 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowCascadeSplitGUITests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 14e4bc069776420389b88a56f9de8095 diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowCaster2DCastingSourceTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowCaster2DCastingSourceTests.cs new file mode 100644 index 00000000000..c11654e2588 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowCaster2DCastingSourceTests.cs @@ -0,0 +1,135 @@ +using System.Collections.Generic; +using NUnit.Framework; +using UnityEngine; +using UnityEngine.Rendering.Universal; + +namespace UnityEditor.Rendering.Universal.Tests +{ + // UUM-158120: a ShadowCaster2D added before its Sprite Renderer kept casting the Shape Editor path, + // while the Casting Source dropdown read "Sprite Renderer". Awake picked ShapeEditor on a GameObject + // with no renderer but left m_SelectionSources.selectedHashCode at 0. Once the Sprite Renderer was + // added, the drawer found no entry for hash 0 and fell back to entry 0, which is "Sprite Renderer". + class ShadowCaster2DCastingSourceTests + { + GameObject m_GameObject; + Texture2D m_Texture; + Sprite m_Sprite; + + [SetUp] + public void SetUp() + { + m_GameObject = new GameObject("ShadowCaster2DCastingSourceTests"); + 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); + } + + [TearDown] + public void TearDown() + { + Object.DestroyImmediate(m_GameObject); + Object.DestroyImmediate(m_Sprite); + Object.DestroyImmediate(m_Texture); + } + + // Asks the real Casting Source drawer what it shows, with the Shape Editor entry the inspector adds. + static string CastingSourceShownInInspector(ShadowCaster2D caster) + { + var selectionSources = new SerializedObject(caster).FindProperty("m_SelectionSources"); + var additionalSources = new List + { + new Shadow2DSource_ShapeEditor(new GUIContent("Shape Editor"), int.MinValue), + }; + Shadow2DProviderSources.SetAdditionalSources(selectionSources, additionalSources); + + var drawer = new Shadow2DProviderSources_PropertyDrawer(); + drawer.CollectTargetSources(new Object[] { caster }, new List(), out var shown, out _); + return shown?.text; + } + + [Test] + public void CasterAddedBeforeSpriteRenderer_DropdownShowsTheSourceInUse() + { + var caster = m_GameObject.AddComponent(); + m_GameObject.AddComponent().sprite = m_Sprite; + + Assert.That(caster.shadowCastingSource, Is.EqualTo(ShadowCaster2D.ShadowCastingSources.ShapeEditor), + "With no renderer at Awake, the caster should fall back to the Shape Editor."); + + Assert.AreEqual("Shape Editor", CastingSourceShownInInspector(caster), + "The Casting Source dropdown does not show the source the shadow is built from."); + } + + [Test] + public void CasterWithNoRenderer_StoresShapeEditorHash() + { + var caster = m_GameObject.AddComponent(); + + Assert.AreEqual(ShadowCaster2D.ShadowCastingSources.ShapeEditor, caster.shadowCastingSource); + Assert.AreEqual((int)ShadowCaster2D.ShadowCastingSources.ShapeEditor, caster.m_SelectionSources.selectedHashCode); + Assert.AreEqual("Shape Editor", CastingSourceShownInInspector(caster)); + } + + [Test] + public void CasterAddedAfterSpriteRenderer_StoresProviderHashAndShowsSpriteRenderer() + { + m_GameObject.AddComponent().sprite = m_Sprite; + var caster = m_GameObject.AddComponent(); + + Assert.That(caster.shadowCastingSource, Is.EqualTo(ShadowCaster2D.ShadowCastingSources.ShapeProvider), + "With a renderer at Awake, the caster should use it as the shape provider."); + + Assert.AreEqual(LightUtility.ProviderToHash(caster.shadowShape2DProvider, caster.shadowShape2DComponent), + caster.m_SelectionSources.selectedHashCode); + Assert.AreEqual("SpriteRenderer", CastingSourceShownInInspector(caster)); + } + + [Test] + public void ShapeEditorCasterSavedWithoutHash_IsRepairedOnLoad() + { + var caster = m_GameObject.AddComponent(); + m_GameObject.AddComponent().sprite = m_Sprite; + + // Recreate what the old Awake saved: a Version_8 Shape Editor caster with a selected hash of 0. + var serializedCaster = new SerializedObject(caster); + serializedCaster.FindProperty("m_ComponentVersion").intValue = 8; + serializedCaster.FindProperty("m_SelectionSources.m_SelectedHashCode").intValue = 0; + serializedCaster.ApplyModifiedPropertiesWithoutUndo(); + + Assert.AreEqual((int)ShadowCaster2D.ShadowCastingSources.ShapeEditor, caster.m_SelectionSources.selectedHashCode); + Assert.AreEqual("Shape Editor", CastingSourceShownInInspector(caster)); + } + + [Test] + public void ShapeProviderCasterSavedWithoutHash_IsRepairedOnLoad() + { + m_GameObject.AddComponent().sprite = m_Sprite; + var caster = m_GameObject.AddComponent(); + int providerHash = LightUtility.ProviderToHash(caster.shadowShape2DProvider, caster.shadowShape2DComponent); + + // Recreate what the old Awake saved for a provider caster: a Version_8 caster with a selected hash of 0. + var serializedCaster = new SerializedObject(caster); + serializedCaster.FindProperty("m_ComponentVersion").intValue = 8; + serializedCaster.FindProperty("m_SelectionSources.m_SelectedHashCode").intValue = 0; + serializedCaster.ApplyModifiedPropertiesWithoutUndo(); + + Assert.AreEqual(ShadowCaster2D.ShadowCastingSources.ShapeProvider, caster.shadowCastingSource); + Assert.AreEqual(providerHash, caster.m_SelectionSources.selectedHashCode); + } + + [Test] + public void CasterSavedWithNonZeroHash_KeepsItsHashOnLoad() + { + m_GameObject.AddComponent().sprite = m_Sprite; + var caster = m_GameObject.AddComponent(); + const int storedHash = 12345; + + // The Version_9 repair only touches a hash of 0, so any other stored hash must survive it. + var serializedCaster = new SerializedObject(caster); + serializedCaster.FindProperty("m_ComponentVersion").intValue = 8; + serializedCaster.FindProperty("m_SelectionSources.m_SelectedHashCode").intValue = storedHash; + serializedCaster.ApplyModifiedPropertiesWithoutUndo(); + + Assert.AreEqual(storedHash, caster.m_SelectionSources.selectedHashCode); + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowCaster2DCastingSourceTests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowCaster2DCastingSourceTests.cs.meta new file mode 100644 index 00000000000..b2b185c5be1 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowCaster2DCastingSourceTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2e8a4bb269a0476e93e5171c422c81c8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowShapeExpansionCapsuleRadiiTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowShapeExpansionCapsuleRadiiTests.cs new file mode 100644 index 00000000000..12695f2df93 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowShapeExpansionCapsuleRadiiTests.cs @@ -0,0 +1,104 @@ +using NUnit.Framework; +using Unity.Collections; +using UnityEngine; +using UnityEngine.Rendering.Universal; + +namespace UnityEditor.Rendering.Universal.Tests +{ + /// + /// UUM-161210: a capsule edge must keep each end's radius on its own end, whatever the edge's direction. + /// AddCapsule swapped the endpoints when the edge ran right to left but kept the radii in place, + /// so each cap got the other end's radius. + /// + [TestFixture] + class ShadowShapeExpansionCapsuleRadiiTests + { + const float k_Tolerance = 1e-4f; + + // Measures the cap radius around each end: the largest distance from that end + // of any generated vertex that sits closer to it than to the other end. + static void MeasureCapRadii(Vector3 pt0, Vector3 pt1, float r0, float r1, bool reverseWindingOrder, out float measured0, out float measured1) + { + using var vertices = new NativeArray(new[] { pt0, pt1 }, Allocator.Temp); + using var indices = new NativeArray(new[] { 0, 1 }, Allocator.Temp); + using var radii = new NativeArray(new[] { r0, r1 }, Allocator.Temp); + + ShadowShapeExpansion.GenerateShapeWithRadii(vertices, indices, radii, reverseWindingOrder, out var genVerts, out var genIndices); + using (genVerts) + using (genIndices) + { + measured0 = 0; + measured1 = 0; + var capVertexCount = 2 * (ShadowShapeExpansion.k_CapsuleCapSegments + 1); + for (int i = 0; i < capVertexCount; i++) + { + var d0 = Vector3.Distance(genVerts[i], pt0); + var d1 = Vector3.Distance(genVerts[i], pt1); + if (d0 < d1) + measured0 = Mathf.Max(measured0, d0); + else + measured1 = Mathf.Max(measured1, d1); + } + } + } + + [TestCase(0f, 0f, 1f, 0f, false, TestName = "CapsuleKeepsEndRadii_LeftToRight")] + [TestCase(0f, 0f, 0f, 1f, false, TestName = "CapsuleKeepsEndRadii_BottomToTop")] + [TestCase(1f, 0f, 0f, 0f, false, TestName = "CapsuleKeepsEndRadii_RightToLeft")] + [TestCase(0f, 1f, 0f, 0f, false, TestName = "CapsuleKeepsEndRadii_TopToBottom")] + [TestCase(1f, 1f, 0f, 0f, false, TestName = "CapsuleKeepsEndRadii_DiagonalRightToLeft")] + [TestCase(0f, 0f, 1f, 0f, true, TestName = "CapsuleKeepsEndRadii_LeftToRight_ReverseWinding")] + [TestCase(1f, 0f, 0f, 0f, true, TestName = "CapsuleKeepsEndRadii_RightToLeft_ReverseWinding")] + public void CapsuleKeepsEndRadii(float x0, float y0, float x1, float y1, bool reverseWindingOrder) + { + var pt0 = new Vector3(x0, y0, 0); + var pt1 = new Vector3(x1, y1, 0); + const float r0 = 0.5f; + const float r1 = 0.1f; + + MeasureCapRadii(pt0, pt1, r0, r1, reverseWindingOrder, out var measured0, out var measured1); + + Assert.AreEqual(r0, measured0, k_Tolerance, $"Cap at {pt0} should have radius {r0}."); + Assert.AreEqual(r1, measured1, k_Tolerance, $"Cap at {pt1} should have radius {r1}."); + } + + // Shoelace sum over the generated line list. Positive is counterclockwise. + static float SignedArea(Vector3 pt0, Vector3 pt1, float r0, float r1, bool reverseWindingOrder) + { + using var vertices = new NativeArray(new[] { pt0, pt1 }, Allocator.Temp); + using var indices = new NativeArray(new[] { 0, 1 }, Allocator.Temp); + using var radii = new NativeArray(new[] { r0, r1 }, Allocator.Temp); + + ShadowShapeExpansion.GenerateShapeWithRadii(vertices, indices, radii, reverseWindingOrder, out var genVerts, out var genIndices); + using (genVerts) + using (genIndices) + { + float area = 0; + for (int i = 0; i < genIndices.Length; i += 2) + { + var a = genVerts[genIndices[i]]; + var b = genVerts[genIndices[i + 1]]; + area += a.x * b.y - b.x * a.y; + } + return 0.5f * area; + } + } + + // Without the endpoint swap, an edge and its reverse must still give the same outline and winding. + [TestCase(false, TestName = "CapsuleOutlineIndependentOfEdgeDirection")] + [TestCase(true, TestName = "CapsuleOutlineIndependentOfEdgeDirection_ReverseWinding")] + public void CapsuleOutlineIndependentOfEdgeDirection(bool reverseWindingOrder) + { + var a = new Vector3(0, 0, 0); + var b = new Vector3(1, 0.25f, 0); + const float ra = 0.5f; + const float rb = 0.1f; + + var forward = SignedArea(a, b, ra, rb, reverseWindingOrder); + var backward = SignedArea(b, a, rb, ra, reverseWindingOrder); + + Assert.AreEqual(reverseWindingOrder, forward > 0, "Capsule winding should follow reverseWindingOrder."); + Assert.AreEqual(forward, backward, k_Tolerance, "Reversing the edge should not change the capsule outline."); + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowShapeExpansionCapsuleRadiiTests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowShapeExpansionCapsuleRadiiTests.cs.meta new file mode 100644 index 00000000000..9ee16bc5703 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowShapeExpansionCapsuleRadiiTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f4d9a2754ebb4864c8fa73a5b1576263 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowUtilsEmptyShadowmapTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowUtilsEmptyShadowmapTests.cs index 0f5633f8aca..07316dd2772 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowUtilsEmptyShadowmapTests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowUtilsEmptyShadowmapTests.cs @@ -1,6 +1,9 @@ using System.Collections; using NUnit.Framework; +using UnityEngine; +using UnityEngine.Rendering; using UnityEngine.Rendering.Universal; +using UnityEngine.Rendering.Universal.Internal; namespace UnityEditor.Rendering.Universal.Tests { @@ -137,4 +140,184 @@ public void DecideEmptyShadowmapParams(EmptyShadowmapParamsCase testCase) $"ShouldComputeEmptyShadowmapParams(strip: {testCase.stripShadowsOffVariants}, shadowsEnabled: {testCase.shadowsEnabled}, bakedShadows: {testCase.lightCastsBakedShadows}) returned the wrong decision."); } } + + [TestFixture] + sealed class MainLightEmptyShadowmapFadeTests + { + GameObject m_LightObject; + + [SetUp] + public void SetUp() + { + m_LightObject = new GameObject("EmptyShadowmapFadeLight", typeof(Light)); + } + + [TearDown] + public void TearDown() + { + Object.DestroyImmediate(m_LightObject); + } + + static float ReceiverShadowFade(Vector4 shadowParams, float distanceToCamera) + { + return Mathf.Clamp01(distanceToCamera * distanceToCamera * shadowParams.z + shadowParams.w); + } + + [TestCase(0.2f)] + [TestCase(0f)] + public void GivenNoShadowsRendered_WhenComputingEmptyShadowmapParams_ThenFadeCompletesAtMaxShadowDistance(float cascadeBorder) + { + const float k_MaxShadowDistance = 50f; + var cameraData = new UniversalCameraData { maxShadowDistance = k_MaxShadowDistance }; + var shadowData = new UniversalShadowData { mainLightShadowCascadeBorder = cascadeBorder }; + + Vector4 shadowParams = MainLightShadowCasterPass.ComputeShadowParamsForEmptyRendering(m_LightObject.GetComponent(), cameraData, shadowData); + + Assert.That(ReceiverShadowFade(shadowParams, 0.5f * k_MaxShadowDistance), Is.EqualTo(0f), + "Half way to the max shadow distance, the realtime shadow must not have started fading."); + Assert.That(ReceiverShadowFade(shadowParams, 0.99f * k_MaxShadowDistance), Is.LessThan(1f), + "Just inside the max shadow distance, the realtime shadow must not be fully faded."); + Assert.That(ReceiverShadowFade(shadowParams, 1.01f * k_MaxShadowDistance), Is.EqualTo(1f), + "Just past the max shadow distance, the realtime shadow must be fully faded."); + } + } + + [TestFixture] + sealed class TransparentsNotReceivingShadowsParamsTests + { + const float k_ShadowDistance = 50f; + const float k_LightShadowStrength = 0.6f; + static readonly int k_MainLightShadowParamsId = Shader.PropertyToID("_MainLightShadowParams"); + + RenderPipelineAsset m_PreviousQualityPipeline; + bool m_PipelineOverridden; + UniversalRenderPipelineAsset m_PipelineAsset; + UniversalRendererData m_RendererData; + VolumeProfile m_VolumeProfile; + Material m_TransparentMaterial; + RenderTexture m_ColorTarget; + RenderTexture m_DepthOnlyTarget; + GameObject m_LightObject; + GameObject m_CasterObject; + GameObject m_TransparentObject; + Camera m_ColorCamera; + Camera m_DepthOnlyCamera; + + [SetUp] + public void SetUp() + { + if (GraphicsSettings.currentRenderPipeline is not UniversalRenderPipelineAsset) + Assert.Ignore("Requires URP to be the active render pipeline."); + + m_PreviousQualityPipeline = QualitySettings.renderPipeline; + m_RendererData = ScriptableObject.CreateInstance(); + m_RendererData.shadowTransparentReceive = false; + m_PipelineAsset = ScriptableObject.CreateInstance(); + m_PipelineAsset.m_RendererDataList[0] = m_RendererData; + m_PipelineAsset.mainLightRenderingMode = LightRenderingMode.PerPixel; + m_PipelineAsset.supportsMainLightShadows = true; + m_VolumeProfile = ScriptableObject.CreateInstance(); + var shadowsVolume = m_VolumeProfile.Add(overrides: true); + shadowsVolume.maxShadowDistance.value = k_ShadowDistance; + shadowsVolume.cascadeCount.value = 1; + m_PipelineAsset.volumeProfile = m_VolumeProfile; + QualitySettings.renderPipeline = m_PipelineAsset; + m_PipelineOverridden = true; + + m_LightObject = new GameObject("TransparentShadowParamsLight") { hideFlags = HideFlags.HideAndDontSave }; + m_LightObject.transform.rotation = Quaternion.Euler(50f, -30f, 0f); + var light = m_LightObject.AddComponent(); + light.type = LightType.Directional; + light.shadows = LightShadows.Soft; + light.shadowStrength = k_LightShadowStrength; + + m_CasterObject = GameObject.CreatePrimitive(PrimitiveType.Plane); + m_CasterObject.hideFlags = HideFlags.HideAndDontSave; + + m_TransparentMaterial = new Material(Shader.Find("Universal Render Pipeline/Unlit")) { renderQueue = (int)RenderQueue.Transparent }; + m_TransparentObject = GameObject.CreatePrimitive(PrimitiveType.Sphere); + m_TransparentObject.hideFlags = HideFlags.HideAndDontSave; + m_TransparentObject.transform.position = new Vector3(0f, 1f, 0f); + m_TransparentObject.GetComponent().sharedMaterial = m_TransparentMaterial; + + m_ColorTarget = new RenderTexture(64, 64, 24); + m_DepthOnlyTarget = new RenderTexture(64, 64, 24, RenderTextureFormat.Depth); + m_ColorCamera = CreateCamera("TransparentShadowParamsColorCamera", m_ColorTarget); + m_DepthOnlyCamera = CreateCamera("TransparentShadowParamsDepthOnlyCamera", m_DepthOnlyTarget); + } + + static Camera CreateCamera(string name, RenderTexture target) + { + var cameraObject = new GameObject(name) { hideFlags = HideFlags.HideAndDontSave }; + cameraObject.transform.SetPositionAndRotation(new Vector3(0f, 10f, -10f), Quaternion.Euler(45f, 0f, 0f)); + var camera = cameraObject.AddComponent(); + camera.enabled = false; + camera.targetTexture = target; + cameraObject.AddComponent(); + return camera; + } + + [TearDown] + public void TearDown() + { + if (m_PipelineOverridden) + { + QualitySettings.renderPipeline = m_PreviousQualityPipeline; + m_PipelineOverridden = false; + } + + if (m_ColorCamera != null) + Object.DestroyImmediate(m_ColorCamera.gameObject); + if (m_DepthOnlyCamera != null) + Object.DestroyImmediate(m_DepthOnlyCamera.gameObject); + if (m_ColorTarget != null) + { + m_ColorTarget.Release(); + Object.DestroyImmediate(m_ColorTarget); + } + if (m_DepthOnlyTarget != null) + { + m_DepthOnlyTarget.Release(); + Object.DestroyImmediate(m_DepthOnlyTarget); + } + if (m_TransparentObject != null) + Object.DestroyImmediate(m_TransparentObject); + if (m_TransparentMaterial != null) + Object.DestroyImmediate(m_TransparentMaterial); + if (m_CasterObject != null) + Object.DestroyImmediate(m_CasterObject); + if (m_LightObject != null) + Object.DestroyImmediate(m_LightObject); + if (m_PipelineAsset != null) + Object.DestroyImmediate(m_PipelineAsset); + if (m_RendererData != null) + Object.DestroyImmediate(m_RendererData); + if (m_VolumeProfile != null) + { + foreach (var component in m_VolumeProfile.components) + Object.DestroyImmediate(component); + Object.DestroyImmediate(m_VolumeProfile); + } + } + + Vector4 RenderAfterDepthOnlyCameraAndReadShadowParams(float depthOnlyCameraFarPlane) + { + m_DepthOnlyCamera.farClipPlane = depthOnlyCameraFarPlane; + m_DepthOnlyCamera.Render(); + m_ColorCamera.Render(); + return Shader.GetGlobalVector(k_MainLightShadowParamsId); + } + + [Test] + public void GivenShadowsRendered_WhenTransparentsDoNotReceiveShadows_ThenMainLightShadowStrengthIsZeroWhateverRenderedBefore() + { + Vector4 afterNearDepthOnlyCamera = RenderAfterDepthOnlyCameraAndReadShadowParams(10f); + Vector4 afterFarDepthOnlyCamera = RenderAfterDepthOnlyCameraAndReadShadowParams(1000f); + + Assert.That(afterNearDepthOnlyCamera, Is.EqualTo(afterFarDepthOnlyCamera), + "The shadow params for transparents must not depend on a camera that rendered earlier."); + Assert.That(afterFarDepthOnlyCamera.x, Is.EqualTo(0f), + "Transparents that do not receive shadows must get zero main light shadow strength, so no main light shadow applies to them."); + } + } } \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowmapDepthStencilFormatTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowmapDepthStencilFormatTests.cs new file mode 100644 index 00000000000..186dfe8dacc --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowmapDepthStencilFormatTests.cs @@ -0,0 +1,153 @@ +using System.Collections; +using System.Collections.Generic; +using NUnit.Framework; +using UnityEngine.Experimental.Rendering; +using UnityEngine.Rendering; +using UnityEngine.Rendering.Universal; + +namespace UnityEditor.Rendering.Universal.Tests +{ + [TestFixture] + sealed class ShadowmapDepthStencilFormatTests + { + static readonly GraphicsFormat[] s_AllDepthFormats = + { + GraphicsFormat.D16_UNorm, + GraphicsFormat.D24_UNorm, + GraphicsFormat.D32_SFloat, + GraphicsFormat.D16_UNorm_S8_UInt, + GraphicsFormat.D24_UNorm_S8_UInt, + GraphicsFormat.D32_SFloat_S8_UInt, + }; + + static readonly GraphicsFormat[] s_StencilFormats = + { + GraphicsFormat.D16_UNorm_S8_UInt, + GraphicsFormat.D24_UNorm_S8_UInt, + GraphicsFormat.D32_SFloat_S8_UInt, + }; + + internal class FormatSelectionCase + { + internal string name; + internal DepthBits depthBits; + internal bool stencilBuffer; + internal GraphicsFormat[] unsupportedFormats; + internal GraphicsFormat expectedFormat; + + public override string ToString() + { + return name; + } + } + + static FormatSelectionCase Case(string name, DepthBits depthBits, bool stencilBuffer, GraphicsFormat[] unsupportedFormats, GraphicsFormat expectedFormat) + { + return new FormatSelectionCase + { + name = name, + depthBits = depthBits, + stencilBuffer = stencilBuffer, + unsupportedFormats = unsupportedFormats, + expectedFormat = expectedFormat + }; + } + + static GraphicsFormat[] AllSupported() + { + return new GraphicsFormat[0]; + } + + static GraphicsFormat[] Unsupported(params GraphicsFormat[] formats) + { + return formats; + } + + static IEnumerable FormatSelectionCases() + { + yield return Case("GivenAllFormatsSupported_When16BitWithoutStencil_ThenD16", DepthBits.Depth16, false, AllSupported(), GraphicsFormat.D16_UNorm); + yield return Case("GivenAllFormatsSupported_When24BitWithoutStencil_ThenD24", DepthBits.Depth24, false, AllSupported(), GraphicsFormat.D24_UNorm); + yield return Case("GivenAllFormatsSupported_When32BitWithoutStencil_ThenD32", DepthBits.Depth32, false, AllSupported(), GraphicsFormat.D32_SFloat); + yield return Case("GivenAllFormatsSupported_When16BitWithStencil_ThenD16S8", DepthBits.Depth16, true, AllSupported(), GraphicsFormat.D16_UNorm_S8_UInt); + yield return Case("GivenAllFormatsSupported_When24BitWithStencil_ThenD24S8", DepthBits.Depth24, true, AllSupported(), GraphicsFormat.D24_UNorm_S8_UInt); + yield return Case("GivenAllFormatsSupported_When32BitWithStencil_ThenD32S8", DepthBits.Depth32, true, AllSupported(), GraphicsFormat.D32_SFloat_S8_UInt); + + yield return Case("GivenD16Unsupported_When16BitWithoutStencil_ThenD24", + DepthBits.Depth16, false, Unsupported(GraphicsFormat.D16_UNorm), GraphicsFormat.D24_UNorm); + yield return Case("GivenD16AndD24Unsupported_When16BitWithoutStencil_ThenD32", + DepthBits.Depth16, false, Unsupported(GraphicsFormat.D16_UNorm, GraphicsFormat.D24_UNorm), GraphicsFormat.D32_SFloat); + yield return Case("GivenD24Unsupported_When24BitWithoutStencil_ThenD32", + DepthBits.Depth24, false, Unsupported(GraphicsFormat.D24_UNorm), GraphicsFormat.D32_SFloat); + yield return Case("GivenD16Unsupported_When32BitWithoutStencil_ThenD32", + DepthBits.Depth32, false, Unsupported(GraphicsFormat.D16_UNorm), GraphicsFormat.D32_SFloat); + yield return Case("GivenD24AndD32Unsupported_When24BitWithoutStencil_ThenD24S8", + DepthBits.Depth24, false, Unsupported(GraphicsFormat.D24_UNorm, GraphicsFormat.D32_SFloat), GraphicsFormat.D24_UNorm_S8_UInt); + yield return Case("GivenOnlyD16AndD32S8Supported_When32BitWithoutStencil_ThenD32S8", + DepthBits.Depth32, false, Unsupported(GraphicsFormat.D24_UNorm, GraphicsFormat.D32_SFloat, GraphicsFormat.D16_UNorm_S8_UInt, GraphicsFormat.D24_UNorm_S8_UInt), GraphicsFormat.D32_SFloat_S8_UInt); + yield return Case("GivenDepthOnlyAndD16S8Unsupported_When16BitWithoutStencil_ThenD24S8", + DepthBits.Depth16, false, Unsupported(GraphicsFormat.D16_UNorm, GraphicsFormat.D24_UNorm, GraphicsFormat.D32_SFloat, GraphicsFormat.D16_UNorm_S8_UInt), GraphicsFormat.D24_UNorm_S8_UInt); + + yield return Case("GivenD16S8Unsupported_When16BitWithStencil_ThenD24S8", + DepthBits.Depth16, true, Unsupported(GraphicsFormat.D16_UNorm_S8_UInt), GraphicsFormat.D24_UNorm_S8_UInt); + yield return Case("GivenD16S8AndD24S8Unsupported_When16BitWithStencil_ThenD32S8", + DepthBits.Depth16, true, Unsupported(GraphicsFormat.D16_UNorm_S8_UInt, GraphicsFormat.D24_UNorm_S8_UInt), GraphicsFormat.D32_SFloat_S8_UInt); + yield return Case("GivenD32S8Unsupported_When32BitWithStencil_ThenD32", + DepthBits.Depth32, true, Unsupported(GraphicsFormat.D32_SFloat_S8_UInt), GraphicsFormat.D32_SFloat); + yield return Case("GivenStencilFormatsUnsupported_When16BitWithStencil_ThenD16", + DepthBits.Depth16, true, s_StencilFormats, GraphicsFormat.D16_UNorm); + yield return Case("GivenStencilFormatsUnsupported_When24BitWithStencil_ThenD24", + DepthBits.Depth24, true, s_StencilFormats, GraphicsFormat.D24_UNorm); + yield return Case("GivenStencilFormatsAndD16Unsupported_When16BitWithStencil_ThenD24", + DepthBits.Depth16, true, Unsupported(GraphicsFormat.D16_UNorm_S8_UInt, GraphicsFormat.D24_UNorm_S8_UInt, GraphicsFormat.D32_SFloat_S8_UInt, GraphicsFormat.D16_UNorm), GraphicsFormat.D24_UNorm); + + yield return Case("GivenNoFormatSupported_When16BitWithoutStencil_ThenRequestedD16", DepthBits.Depth16, false, s_AllDepthFormats, GraphicsFormat.D16_UNorm); + yield return Case("GivenNoFormatSupported_When32BitWithoutStencil_ThenRequestedD32", DepthBits.Depth32, false, s_AllDepthFormats, GraphicsFormat.D32_SFloat); + yield return Case("GivenNoFormatSupported_When32BitWithStencil_ThenRequestedD32S8", DepthBits.Depth32, true, s_AllDepthFormats, GraphicsFormat.D32_SFloat_S8_UInt); + + yield return Case("GivenAllFormatsSupported_WhenNoDepthBitsWithoutStencil_ThenD16", DepthBits.None, false, AllSupported(), GraphicsFormat.D16_UNorm); + yield return Case("GivenAllFormatsSupported_WhenNoDepthBitsWithStencil_ThenD16S8", DepthBits.None, true, AllSupported(), GraphicsFormat.D16_UNorm_S8_UInt); + yield return Case("GivenD16Unsupported_WhenNoDepthBitsWithoutStencil_ThenD24", + DepthBits.None, false, Unsupported(GraphicsFormat.D16_UNorm), GraphicsFormat.D24_UNorm); + } + + [Test] + [Description("The shadow map format is the requested precision when supported, otherwise the first supported format with at least that precision, keeping stencil before dropping it.")] + [TestCaseSource(nameof(FormatSelectionCases))] + public void SelectShadowmapDepthStencilFormat(FormatSelectionCase testCase) + { + var unsupported = new HashSet(testCase.unsupportedFormats); + GraphicsFormat format = ShadowUtils.SelectShadowmapDepthStencilFormat(testCase.depthBits, testCase.stencilBuffer, f => !unsupported.Contains(f)); + Assert.That(format, Is.EqualTo(testCase.expectedFormat), + $"SelectShadowmapDepthStencilFormat(depthBits: {testCase.depthBits}, stencil: {testCase.stencilBuffer}) with {testCase.unsupportedFormats.Length} unsupported formats returned the wrong format."); + } + + [Test] + [Description("A 16-bit request picks the same format as the stencil selection that shipped before the precision option, for every combination of supported stencil formats.")] + public void Given16BitRequest_WhenStencilFormatSupportVaries_ThenMatchesPreviousSelection() + { + for (int mask = 0; mask < (1 << s_StencilFormats.Length); ++mask) + { + var unsupported = new HashSet(); + for (int i = 0; i < s_StencilFormats.Length; ++i) + { + if ((mask & (1 << i)) != 0) + unsupported.Add(s_StencilFormats[i]); + } + + GraphicsFormat expected = GraphicsFormat.D16_UNorm; + foreach (GraphicsFormat stencilFormat in s_StencilFormats) + { + if (!unsupported.Contains(stencilFormat)) + { + expected = stencilFormat; + break; + } + } + + GraphicsFormat format = ShadowUtils.SelectShadowmapDepthStencilFormat(DepthBits.Depth16, true, f => !unsupported.Contains(f)); + Assert.That(format, Is.EqualTo(expected), + $"With {unsupported.Count} unsupported stencil formats (mask {mask}), the 16-bit stencil shadow map must keep the smallest supported depth-stencil format, or depth-only D16 when none is supported."); + } + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowmapDepthStencilFormatTests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowmapDepthStencilFormatTests.cs.meta new file mode 100644 index 00000000000..7120499ccbc --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowmapDepthStencilFormatTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 31fbba01b47e4925828fd7bd27bd6436 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowsVolumeOverrideTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowsVolumeOverrideTests.cs new file mode 100644 index 00000000000..142cda51523 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowsVolumeOverrideTests.cs @@ -0,0 +1,76 @@ +using NUnit.Framework; +using UnityEngine; +using UnityEngine.Rendering.Universal; + +namespace UnityEditor.Rendering.Universal.Tests +{ + class ShadowsVolumeOverrideTests + { + ShadowsVolumeOverride m_Shadows; + + [SetUp] + public void SetUp() + { + m_Shadows = ScriptableObject.CreateInstance(); + } + + [TearDown] + public void TearDown() + { + Object.DestroyImmediate(m_Shadows); + } + + [Test] + [Description("The component defaults match the URP asset defaults, so an asset left at its defaults needs no migrated override.")] + public void Defaults_MatchUniversalRenderPipelineAssetDefaults() + { + var asset = ScriptableObject.CreateInstance(); + try + { +#pragma warning disable 618 // Obsolete warning + Assert.AreEqual(asset.m_ObsoleteShadowDistance, m_Shadows.maxShadowDistance.value); + Assert.AreEqual(asset.m_ObsoleteShadowCascadeCount, m_Shadows.cascadeCount.value); + Assert.AreEqual(asset.m_ObsoleteCascade4Split.x, m_Shadows.cascadeSplit0.value); + Assert.AreEqual(asset.m_ObsoleteCascade4Split.y, m_Shadows.cascadeSplit1.value); + Assert.AreEqual(asset.m_ObsoleteCascade4Split.z, m_Shadows.cascadeSplit2.value); + Assert.AreEqual(asset.m_ObsoleteCascadeBorder, m_Shadows.lastCascadeBorder.value); +#pragma warning restore 618 // Obsolete warning + } + finally + { + Object.DestroyImmediate(asset); + } + + Assert.AreEqual(50f, m_Shadows.maxShadowDistance.value); + Assert.AreEqual(1, m_Shadows.cascadeCount.value); + Assert.AreEqual(0.067f, m_Shadows.cascadeSplit0.value); + Assert.AreEqual(0.2f, m_Shadows.cascadeSplit1.value); + Assert.AreEqual(0.467f, m_Shadows.cascadeSplit2.value); + Assert.AreEqual(0.2f, m_Shadows.lastCascadeBorder.value); + } + + static readonly object[] k_CascadeSplitCases = + { + new object[] { 1, new Vector3(0.125f, 0.25f, 0.5f), new Vector3(1f, 0f, 0f) }, + new object[] { 2, new Vector3(0.125f, 0.25f, 0.5f), new Vector3(0.125f, 1f, 0f) }, + new object[] { 3, new Vector3(0.125f, 0.25f, 0.5f), new Vector3(0.125f, 0.25f, 0f) }, + new object[] { 4, new Vector3(0.125f, 0.25f, 0.5f), new Vector3(0.125f, 0.25f, 0.5f) }, + new object[] { 1, new Vector3(0.5f, 0.25f, 0.125f), new Vector3(1f, 0f, 0f) }, + new object[] { 2, new Vector3(0.5f, 0.25f, 0.125f), new Vector3(0.5f, 1f, 0f) }, + new object[] { 3, new Vector3(0.5f, 0.25f, 0.125f), new Vector3(0.5f, 0.5f, 0f) }, + new object[] { 4, new Vector3(0.5f, 0.25f, 0.125f), new Vector3(0.5f, 0.5f, 0.5f) }, + }; + + [Test, TestCaseSource(nameof(k_CascadeSplitCases))] + [Description("GetCascadeSplit returns the split vector the URP asset produced for each cascade count and keeps the splits in ascending order.")] + public void GetCascadeSplit_MatchesAssetLayoutForCascadeCount(int cascadeCount, Vector3 splits, Vector3 expected) + { + m_Shadows.cascadeCount.value = cascadeCount; + m_Shadows.cascadeSplit0.value = splits.x; + m_Shadows.cascadeSplit1.value = splits.y; + m_Shadows.cascadeSplit2.value = splits.z; + + Assert.AreEqual(expected, m_Shadows.GetCascadeSplit()); + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowsVolumeOverrideTests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowsVolumeOverrideTests.cs.meta new file mode 100644 index 00000000000..82da21e8139 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowsVolumeOverrideTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 6f7433fdd64747fb9f1f857584e7ed74 diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/SurfaceCacheGIDebugShaderTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/SurfaceCacheGIDebugShaderTests.cs new file mode 100644 index 00000000000..07a702efecf --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/SurfaceCacheGIDebugShaderTests.cs @@ -0,0 +1,33 @@ +using System.Linq; +using NUnit.Framework; +using UnityEditor; + +namespace UnityEngine.Rendering.Tests +{ + class SurfaceCacheGIDebugShaderTests + { + const string k_ShaderPath = "Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGIRendererFeature/Debug.compute"; + + [Test] + public void SurfaceCacheGIDebugShader_WhenCompiledForMetal_CompilesWithoutWarnings( + [Values("VisualizeMonoCompute", "VisualizeSinglePassStereoInstancingCompute")] string kernelName, + [Values("SURFACE_CACHE_PATH_TRACING_TRANSPARENCY_MODE_OPAQUES_ONLY", "SURFACE_CACHE_PATH_TRACING_TRANSPARENCY_MODE_CUTOUTS")] string transparencyKeyword) + { + var shader = AssetDatabase.LoadAssetAtPath(k_ShaderPath); + Assert.IsNotNull(shader, $"Could not load compute shader at {k_ShaderPath}."); + + var result = ShaderUtil.CompileComputeShaderVariant( + shader, + shader.FindKernel(kernelName), + new[] { transparencyKeyword }, + GraphicsDeviceType.Metal, + BuildTarget.StandaloneOSX); + + Assert.IsTrue(result.Success, $"{kernelName} failed to compile for Metal."); + + // Messages without a source line come from the host toolchain, not from the shader code + var messages = (result.Messages ?? new ShaderMessage[0]).Where(m => m.line > 0).ToArray(); + Assert.IsEmpty(messages, $"{kernelName} has compiler messages on Metal:\n" + string.Join("\n", messages.Select(m => $"{m.severity}: {m.message} ({m.file}:{m.line})"))); + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/SurfaceCacheGIDebugShaderTests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Editor/SurfaceCacheGIDebugShaderTests.cs.meta new file mode 100644 index 00000000000..b441ed3cf9d --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/SurfaceCacheGIDebugShaderTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 60c620ab2cb548cc9eeb391486ec0c85 diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/SurfaceCacheGIRendererFeatureMigrationTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/SurfaceCacheGIRendererFeatureMigrationTests.cs new file mode 100644 index 00000000000..083e4292c58 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/SurfaceCacheGIRendererFeatureMigrationTests.cs @@ -0,0 +1,98 @@ +using System.Text.RegularExpressions; +using NUnit.Framework; +using UnityEditor; +using UnityEditor.Rendering; +using UnityEngine; +using UnityEngine.Rendering.Universal; + +namespace UnityEditor.Rendering.Universal.Tests +{ + class SurfaceCacheGIRendererFeatureMigrationTests + { + const int k_LatestVersion = 1; + + SurfaceCacheGIRendererFeature m_Feature; + BuildTarget m_BuildTarget; + bool m_PreviousStaticBatching; + DefaultMeshBufferTarget m_PreviousMeshBufferTarget; + + // Creating the feature under URP validates these project settings and logs an error when they are unmet. + [SetUp] + public void Setup() + { + m_BuildTarget = EditorUserBuildSettings.activeBuildTarget; + m_PreviousStaticBatching = PlayerSettings.GetStaticBatchingForPlatform(m_BuildTarget); + m_PreviousMeshBufferTarget = EditorGraphicsSettings.defaultMeshBufferTarget; + PlayerSettings.SetStaticBatchingForPlatform(m_BuildTarget, false); + EditorGraphicsSettings.defaultMeshBufferTarget = DefaultMeshBufferTarget.Raw; + + m_Feature = ScriptableObject.CreateInstance(); + } + + [TearDown] + public void TearDown() + { + m_Feature.Dispose(); + Object.DestroyImmediate(m_Feature); + EditorGraphicsSettings.defaultMeshBufferTarget = m_PreviousMeshBufferTarget; + PlayerSettings.SetStaticBatchingForPlatform(m_BuildTarget, m_PreviousStaticBatching); + } + + static int GetSerializedVersion(Object feature) + { + using var serializedObject = new SerializedObject(feature); + return serializedObject.FindProperty("m_Version").intValue; + } + + [Test] + public void NewFeature_DefaultsToMediumAndLatestVersion() + { + EditorJsonUtility.ToJson(m_Feature); + + Assert.AreEqual(SurfaceCacheGIRendererFeature.MaterialResolution.Medium, m_Feature.materialResolution); + Assert.AreEqual(k_LatestVersion, GetSerializedVersion(m_Feature)); + } + + [Test] + public void FeatureSerializedBeforeMaterialResolution_MigratesToVeryHigh() + { + var json = EditorJsonUtility.ToJson(m_Feature); + json = Regex.Replace(json, "\"m_MaterialResolution\":\\s*-?\\d+,?", ""); + json = Regex.Replace(json, "\"m_Version\":\\s*-?\\d+,?", ""); + json = Regex.Replace(json, ",\\s*}", "}"); + + var legacyFeature = ScriptableObject.CreateInstance(); + try + { + EditorJsonUtility.FromJsonOverwrite(json, legacyFeature); + + Assert.AreEqual(SurfaceCacheGIRendererFeature.MaterialResolution.VeryHigh, legacyFeature.materialResolution); + Assert.AreEqual(k_LatestVersion, GetSerializedVersion(legacyFeature)); + } + finally + { + legacyFeature.Dispose(); + Object.DestroyImmediate(legacyFeature); + } + } + + [Test] + public void FeatureAtLatestVersion_KeepsMaterialResolution() + { + m_Feature.materialResolution = SurfaceCacheGIRendererFeature.MaterialResolution.Low; + var json = EditorJsonUtility.ToJson(m_Feature); + + var copy = ScriptableObject.CreateInstance(); + try + { + EditorJsonUtility.FromJsonOverwrite(json, copy); + Assert.AreEqual(SurfaceCacheGIRendererFeature.MaterialResolution.Low, copy.materialResolution); + } + finally + { + copy.Dispose(); + Object.DestroyImmediate(copy); + } + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/SurfaceCacheGIRendererFeatureMigrationTests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Editor/SurfaceCacheGIRendererFeatureMigrationTests.cs.meta new file mode 100644 index 00000000000..247e1fabe73 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/SurfaceCacheGIRendererFeatureMigrationTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: df06f50e72094476a947cce97e716648 diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/Tools/Converters/ConvertersTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/Tools/Converters/ConvertersTests.cs index dc147c596e6..7c3bc99eec2 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Editor/Tools/Converters/ConvertersTests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/Tools/Converters/ConvertersTests.cs @@ -606,6 +606,182 @@ public void Convert_SceneOpenedByEarlierConversion_DoesNotSaveUnrelatedEdits() } } + // Moves each object it converts to another layer, which unlike the name of a prefab root is kept on import + class LayerAssetsConverter : NoQueriesAssetsConverter + { + public const int convertedLayer = 4; + + protected override Status ConvertObject(UnityEngine.Object obj, StringBuilder message) + { + ((GameObject)obj).layer = convertedLayer; + EditorUtility.SetDirty(obj); + return Status.Success; + } + } + + // Returns the id of the prefab without keeping a reference to it, so that it can be unloaded + static string CreatePrefabAsset(string path) + { + var go = new GameObject("Prefab"); + var prefab = PrefabUtility.SaveAsPrefabAsset(go, path); + UnityEngine.Object.DestroyImmediate(go); + return GlobalObjectId.GetGlobalObjectIdSlow(prefab).ToString(); + } + + // Opening a scene, to convert an object in it or after the conversion, unloads converted prefabs that are not saved + [TestCase(true, TestName = "{m}(Prefab converted first)")] + [TestCase(false, TestName = "{m}(Prefab converted last)")] + public void Convert_PrefabAndObjectInClosedScene_KeepsThePrefabConversion(bool prefabFirst) + { + const string prefabPath = "Assets/ConverterPrefabBeforeClosedSceneTest.prefab"; + const string scenePath = "Assets/ConverterPrefabBeforeClosedSceneTest.unity"; + + try + { + var prefabGidString = CreatePrefabAsset(prefabPath); + + var scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); + var go = new GameObject("Cube"); + Assert.IsTrue(EditorSceneManager.SaveScene(scene, scenePath)); + var sceneObjectGidString = GlobalObjectId.GetGlobalObjectIdSlow(go).ToString(); + + EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); + + var converter = new LayerAssetsConverter(); + var prefabItem = new RenderPipelineConverterAssetItem(prefabGidString); + var sceneObjectItem = AssetsConverter.CreateAssetItem(new SearchItem(sceneObjectGidString) { label = "/Cube" }); + + converter.BeforeConvert(); + if (prefabFirst) + Assert.AreEqual(Status.Success, converter.Convert(prefabItem, out _)); + Assert.AreEqual(Status.Success, converter.Convert(sceneObjectItem, out _)); + if (!prefabFirst) + Assert.AreEqual(Status.Success, converter.Convert(prefabItem, out _)); + converter.AfterConvert(); + + // Like returning to the scene the conversion started from + EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); + + Assert.AreEqual(LayerAssetsConverter.convertedLayer, AssetDatabase.LoadAssetAtPath(prefabPath).layer, + "Opening a scene during or after the conversion must not discard the conversion of a prefab."); + } + finally + { + EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); + AssetDatabase.DeleteAsset(prefabPath); + AssetDatabase.DeleteAsset(scenePath); + } + } + + [Test] + public void ParametricToFreeformLightUpgraderCreateItem_ObjectInClosedScene_CreatesItemFromSearchResult() + { + const string scenePath = "Assets/LightUpgraderClosedSceneTest.unity"; + + try + { + var scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); + var go = new GameObject("Light"); + Assert.IsTrue(EditorSceneManager.SaveScene(scene, scenePath)); + var gidString = GlobalObjectId.GetGlobalObjectIdSlow(go).ToString(); + + EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); + + var lightItem = ParametricToFreeformLightUpgrader.CreateItem(new SearchItem(gidString) { label = "/Light" }); + + Assert.IsNotNull(lightItem, "An object in a closed scene must not be skipped."); + Assert.AreEqual(gidString, lightItem.GlobalObjectId); + Assert.AreEqual(scenePath, lightItem.assetPath); + Assert.AreEqual($"Scene: {scenePath}", lightItem.info); + Assert.AreEqual(GlobalObjectIdentifierType.SceneObject, lightItem.type); + } + finally + { + AssetDatabase.DeleteAsset(scenePath); + } + } + + [Test] + public void PixelPerfectCameraConverterCreateItem_ObjectInClosedScene_CreatesItemFromSearchResult() + { + const string scenePath = "Assets/PixelPerfectCameraClosedSceneTest.unity"; + + try + { + var scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); + var go = new GameObject("Camera"); + Assert.IsTrue(EditorSceneManager.SaveScene(scene, scenePath)); + var gidString = GlobalObjectId.GetGlobalObjectIdSlow(go).ToString(); + + EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); + + var ppCameraItem = BuiltInPixelPerfectCameraConverter.CreateItem(new SearchItem(gidString) { label = "/Camera" }); + + Assert.IsNotNull(ppCameraItem, "An object in a closed scene must not be skipped."); + Assert.AreEqual(gidString, ppCameraItem.GlobalObjectId); + Assert.AreEqual("Camera (SceneObject)", ppCameraItem.name); + Assert.AreEqual(scenePath, ppCameraItem.info); + } + finally + { + AssetDatabase.DeleteAsset(scenePath); + } + } + + [Test] + public void PixelPerfectCameraConverterCreateItem_NestedObject_HasSameNameWhetherSceneIsOpenOrClosed() + { + const string scenePath = "Assets/PixelPerfectCameraNestedNameTest.unity"; + + try + { + var scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); + var root = new GameObject("Root"); + var go = new GameObject("Camera"); + go.transform.SetParent(root.transform); + Assert.IsTrue(EditorSceneManager.SaveScene(scene, scenePath)); + var gidString = GlobalObjectId.GetGlobalObjectIdSlow(go).ToString(); + var label = UnityEditor.Search.SearchUtils.GetTransformPath(go.transform); + + var openSceneItem = BuiltInPixelPerfectCameraConverter.CreateItem(new SearchItem(gidString) { label = label, provider = k_LoadingSearchProvider }); + + EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); + + var closedSceneItem = BuiltInPixelPerfectCameraConverter.CreateItem(new SearchItem(gidString) { label = label, provider = k_LoadingSearchProvider }); + + Assert.AreEqual("Root/Camera (SceneObject)", openSceneItem.name); + Assert.AreEqual(openSceneItem.name, closedSceneItem.name); + } + finally + { + AssetDatabase.DeleteAsset(scenePath); + } + } + + // An object that is gone from an open scene has nothing left to convert + [Test] + public void ConverterCreateItem_ObjectDeletedFromOpenScene_IsSkipped() + { + const string scenePath = "Assets/ConverterDeletedObjectTest.unity"; + + try + { + var scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); + var go = new GameObject("Deleted"); + Assert.IsTrue(EditorSceneManager.SaveScene(scene, scenePath)); + var gidString = GlobalObjectId.GetGlobalObjectIdSlow(go).ToString(); + UnityEngine.Object.DestroyImmediate(go); + + Assert.IsNull(ParametricToFreeformLightUpgrader.CreateItem(new SearchItem(gidString) { label = "/Deleted" })); + Assert.IsNull(BuiltInPixelPerfectCameraConverter.CreateItem(new SearchItem(gidString) { label = "/Deleted" })); + } + finally + { + EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); + AssetDatabase.DeleteAsset(scenePath); + } + } + [Test] public void BatchModeFails() { diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/Tools/Converters/MaterialUpgrader/StandardMaterialUpgraderTest.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/Tools/Converters/MaterialUpgrader/StandardMaterialUpgraderTest.cs index 6de6707690a..2c67cc048ff 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Editor/Tools/Converters/MaterialUpgrader/StandardMaterialUpgraderTest.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/Tools/Converters/MaterialUpgrader/StandardMaterialUpgraderTest.cs @@ -290,5 +290,81 @@ private static IEnumerable MaterialUpgradeCases() Assert.IsFalse(material.IsKeywordEnabled("_EMISSION")); } }; + + foreach (var testCase in EmissionUpgradeCases()) + yield return testCase; + } + + internal static IEnumerable EmissionUpgradeCases() + { + yield return new MaterialUpgradeTestCase() + { + name = "Given_BakedEmissionBuiltInMaterial_When_Upgrading_Then_TheMaterialURPDirectEmissionEnabled", + setup = material => + { + material.SetColor("_EmissionColor", Color.white); + material.globalIlluminationFlags = MaterialGlobalIlluminationFlags.BakedEmission; + material.EnableKeyword("_EMISSION"); + }, + verify = material => + { + Assert.IsTrue((material.globalIlluminationFlags & MaterialGlobalIlluminationFlags.BakedEmission) != 0); + Assert.IsTrue((material.globalIlluminationFlags & MaterialGlobalIlluminationFlags.RealtimeDirectEmission) != 0); + Assert.IsTrue(material.IsKeywordEnabled("_EMISSION")); + } + }; + + yield return new MaterialUpgradeTestCase() + { + name = "Given_RealtimeEmissionBuiltInMaterial_When_Upgrading_Then_TheMaterialURPDirectEmissionEnabled", + setup = material => + { + material.SetColor("_EmissionColor", Color.white); + material.globalIlluminationFlags = MaterialGlobalIlluminationFlags.RealtimeIndirectEmission; + material.EnableKeyword("_EMISSION"); + }, + verify = material => + { + Assert.IsTrue((material.globalIlluminationFlags & MaterialGlobalIlluminationFlags.RealtimeIndirectEmission) != 0); + Assert.IsTrue((material.globalIlluminationFlags & MaterialGlobalIlluminationFlags.RealtimeDirectEmission) != 0); + Assert.IsTrue(material.IsKeywordEnabled("_EMISSION")); + } + }; + + yield return new MaterialUpgradeTestCase() + { + name = "Given_NoEmissionBuiltInMaterial_When_Upgrading_Then_TheMaterialURPDirectEmissionDisabled", + setup = material => + { + material.globalIlluminationFlags = MaterialGlobalIlluminationFlags.EmissiveIsBlack; + material.DisableKeyword("_EMISSION"); + }, + verify = material => + { + Assert.IsTrue((material.globalIlluminationFlags & MaterialGlobalIlluminationFlags.RealtimeDirectEmission) == 0); + Assert.IsFalse(material.IsKeywordEnabled("_EMISSION")); + } + }; + } +} + +[Category("Graphics Tools")] +class StandardSpecularMaterialUpgraderTest : MaterialUpgraderTestBase +{ + [OneTimeSetUp] + public override void OneTimeSetUp() + { + m_Upgrader = new StandardUpgrader("Standard (Specular setup)"); + } + + public StandardSpecularMaterialUpgraderTest() : base("Standard (Specular setup)", "Universal Render Pipeline/Lit") + { + } + + [Test] + [TestCaseSource(typeof(StandardMaterialUpgraderTest), nameof(StandardMaterialUpgraderTest.EmissionUpgradeCases))] + public void UpgradeStandardSpecularMaterial(MaterialUpgradeTestCase testCase) + { + UpgradeMaterial(testCase); } } diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/Tools/Converters/RenderSettingsConverterTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/Tools/Converters/RenderSettingsConverterTests.cs index 5095daa028d..e26e70b2a7c 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Editor/Tools/Converters/RenderSettingsConverterTests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/Tools/Converters/RenderSettingsConverterTests.cs @@ -1,9 +1,11 @@ using System.Collections.Generic; +using System.Text.RegularExpressions; using NUnit.Framework; using UnityEditor.Rendering.Converter; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Rendering.Universal; +using UnityEngine.TestTools; namespace UnityEditor.Rendering.Universal.Tools { @@ -97,12 +99,17 @@ void OnScanFinished(List scanItems) // ---------- SETTINGS FORWARDING CHECK ---------- var targetGrp = BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget); +#pragma warning disable CS0618 // Type or member is obsolete var tier = EditorGraphicsSettings.GetTierSettings(targetGrp, GraphicsTier.Tier3); +#pragma warning restore CS0618 +#pragma warning disable CS0618 // Type or member is obsolete Assert.AreEqual(QualitySettings.softParticles, urpAsset.supportsCameraDepthTexture, "supportsCameraDepthTexture mismatch"); +#pragma warning restore CS0618 Assert.AreEqual(tier.hdr, urpAsset.supportsHDR, "supportsHDR mismatch"); Assert.AreEqual(QualitySettings.antiAliasing == 0 ? 1 : QualitySettings.antiAliasing, urpAsset.msaaSampleCount, "msaaSampleCount mismatch"); +#pragma warning disable CS0618 // Type or member is obsolete var expectedMainLightMode = QualitySettings.pixelLightCount == 0 ? LightRenderingMode.Disabled : LightRenderingMode.PerPixel; Assert.AreEqual(expectedMainLightMode, urpAsset.mainLightRenderingMode, "mainLightRenderingMode mismatch"); @@ -118,12 +125,17 @@ void OnScanFinished(List scanItems) Assert.AreEqual(tier.reflectionProbeBlending, urpAsset.reflectionProbeBlending, "reflectionProbeBlending mismatch"); Assert.AreEqual(tier.reflectionProbeBoxProjection, urpAsset.reflectionProbeBoxProjection, "reflectionProbeBoxProjection mismatch"); - Assert.AreEqual(QualitySettings.shadowDistance, urpAsset.shadowDistance, "shadowDistance mismatch"); + ShadowsVolumeOverride shadows = null; + Assert.IsTrue(urpAsset.volumeProfile != null && urpAsset.volumeProfile.TryGet(out shadows), "The quality volume profile has no Shadows override"); + Assert.AreEqual(QualitySettings.shadowDistance, shadows.maxShadowDistance.value, "maxShadowDistance mismatch"); var expectedCascadeCount = tier.cascadedShadowMaps ? QualitySettings.shadowCascades : 1; - Assert.AreEqual(expectedCascadeCount, urpAsset.shadowCascadeCount, "shadowCascadeCount mismatch"); - Assert.AreEqual(QualitySettings.shadowCascade2Split, urpAsset.cascade2Split, "cascade2Split mismatch"); - Assert.AreEqual(QualitySettings.shadowCascade4Split, urpAsset.cascade4Split, "cascade4Split mismatch"); + Assert.AreEqual(expectedCascadeCount, shadows.cascadeCount.value, "cascadeCount mismatch"); + var expectedSplit0 = expectedCascadeCount == 2 ? QualitySettings.shadowCascade2Split : QualitySettings.shadowCascade4Split.x; + Assert.AreEqual(expectedSplit0, shadows.cascadeSplit0.value, "cascadeSplit0 mismatch"); + Assert.AreEqual(QualitySettings.shadowCascade4Split.y, shadows.cascadeSplit1.value, "cascadeSplit1 mismatch"); + Assert.AreEqual(QualitySettings.shadowCascade4Split.z, shadows.cascadeSplit2.value, "cascadeSplit2 mismatch"); Assert.AreEqual(QualitySettings.shadows == UnityEngine.ShadowQuality.All, urpAsset.supportsSoftShadows, "supportsSoftShadows mismatch"); +#pragma warning restore CS0618 // ---------- RENDERER FORWARDING CHECK ---------- Assert.AreEqual(1, urpAsset.m_RendererDataList.Length); @@ -133,6 +145,145 @@ void OnScanFinished(List scanItems) renderSettingsConverter.Scan(OnScanFinished); } + [Test] + public void WhenRunningBuiltInToURP3DRenderSettingsConverter_Again_TheShadowsOverride_FollowsTheCurrentQualitySettings() + { + var renderSettingsConverter = new BuiltInToURP3DRenderSettingsConverter(); +#pragma warning disable CS0618 // Type or member is obsolete + float originalShadowDistance = QualitySettings.shadowDistance; + + void OnScanFinished(List scanItems) + { + IFolderRenderPipelineConverterItem qualityFolder = null; + foreach (var item in scanItems) + { + if (item is IFolderRenderPipelineConverterItem folder && folder.name == "Quality") + { + qualityFolder = folder; + break; + } + } + + Assert.IsNotNull(qualityFolder, "Quality folder not found in scan results"); + var qualityItem = qualityFolder.children[m_QualityLevel]; + + VolumeProfile firstProfile; + try + { + QualitySettings.shadowDistance = 30f; + Assert.IsTrue(renderSettingsConverter.Convert(qualityItem, out string firstMessage) != Status.Error, firstMessage); + firstProfile = ((UniversalRenderPipelineAsset)QualitySettings.renderPipeline).volumeProfile; + + QualitySettings.shadowDistance = 70f; + QualitySettings.renderPipeline = null; + LogAssert.Expect(LogType.Warning, new Regex(Regex.Escape($"a copy of '{Link(firstProfile)}', so later changes to '{Link(firstProfile)}' no longer apply to it"))); + Assert.IsTrue(renderSettingsConverter.Convert(qualityItem, out string secondMessage) != Status.Error, secondMessage); + } + finally + { + QualitySettings.shadowDistance = originalShadowDistance; +#pragma warning restore CS0618 + } + + var urpAsset = QualitySettings.renderPipeline as UniversalRenderPipelineAsset; + Assert.IsNotNull(urpAsset, "URP asset is not assigned"); + Assert.AreNotSame(firstProfile, urpAsset.volumeProfile, "The second conversion must give the pipeline asset a copy of its volume profile"); + Assert.AreEqual(30f, ShadowDistanceIn(firstProfile), "The second conversion must not change the previous volume profile"); + + ShadowsVolumeOverride shadows = null; + Assert.IsTrue(urpAsset.volumeProfile != null && urpAsset.volumeProfile.TryGet(out shadows), "The quality volume profile has no Shadows override"); + Assert.AreEqual(70f, shadows.maxShadowDistance.value, "The second conversion must use the current shadow distance"); + Assert.IsTrue(shadows.maxShadowDistance.overrideState); + } + + renderSettingsConverter.Scan(OnScanFinished); + } + + static string Link(Object asset) => + $"{asset.name}"; + + static float ShadowDistanceIn(VolumeProfile profile) + { + Assert.IsTrue(profile.TryGet(out ShadowsVolumeOverride shadows), $"'{profile.name}' has no Shadows override"); + return shadows.maxShadowDistance.value; + } + + IRenderPipelineConverterItem FindCurrentQualityItem(BuiltInToURP3DRenderSettingsConverter converter) + { + IRenderPipelineConverterItem qualityItem = null; + converter.Scan(scanItems => + { + foreach (var item in scanItems) + { + if (item is IFolderRenderPipelineConverterItem folder && folder.name == "Quality") + qualityItem = folder.children[m_QualityLevel]; + } + }); + + Assert.IsNotNull(qualityItem, "The current quality level was not found in the scan results"); + return qualityItem; + } + + UniversalRenderPipelineAsset ConvertCurrentQualityLevel(BuiltInToURP3DRenderSettingsConverter converter, IRenderPipelineConverterItem qualityItem, float shadowDistance) + { +#pragma warning disable CS0618 // Type or member is obsolete + float originalShadowDistance = QualitySettings.shadowDistance; + try + { + QualitySettings.shadowDistance = shadowDistance; + QualitySettings.renderPipeline = null; + Assert.IsTrue(converter.Convert(qualityItem, out string message) != Status.Error, message); + } + finally + { + QualitySettings.shadowDistance = originalShadowDistance; +#pragma warning restore CS0618 + } + + return QualitySettings.renderPipeline as UniversalRenderPipelineAsset; + } + + [Test] + public void WhenRunningBuiltInToURP3DRenderSettingsConverter_Again_AVolumeProfileSharedWithAnotherPipelineAsset_IsNotChanged() + { + var renderSettingsConverter = new BuiltInToURP3DRenderSettingsConverter(); + var qualityItem = FindCurrentQualityItem(renderSettingsConverter); + + var urpAsset = ConvertCurrentQualityLevel(renderSettingsConverter, qualityItem, 30f); + var sharedProfile = urpAsset.volumeProfile; + + var otherAsset = ScriptableObject.CreateInstance(); + otherAsset.volumeProfile = sharedProfile; + AssetDatabase.CreateAsset(otherAsset, $"Assets/{UniversalProjectSettings.projectSettingsFolderPath}/Other.asset"); + + LogAssert.Expect(LogType.Warning, new Regex(Regex.Escape($"a copy of '{Link(sharedProfile)}', so later changes to '{Link(sharedProfile)}' no longer apply to it. '{Link(sharedProfile)}' is still used by '{Link(otherAsset)}'."))); + urpAsset = ConvertCurrentQualityLevel(renderSettingsConverter, qualityItem, 70f); + + Assert.AreSame(sharedProfile, otherAsset.volumeProfile, "The other pipeline asset must keep the shared volume profile"); + Assert.AreEqual(30f, ShadowDistanceIn(sharedProfile), "The conversion must not change a volume profile that another pipeline asset uses"); + Assert.AreNotSame(sharedProfile, urpAsset.volumeProfile, "The converted pipeline asset must use its own copy"); + Assert.AreEqual(70f, ShadowDistanceIn(urpAsset.volumeProfile), "The converted pipeline asset must use the current shadow distance"); + } + + [Test] + public void WhenRunningBuiltInToURP3DRenderSettingsConverter_Again_OnTheDefaultRenderPipeline_ItWarnsThatTheDefaultRenderPipelineChanged() + { + var renderSettingsConverter = new BuiltInToURP3DRenderSettingsConverter(); + var qualityItem = FindCurrentQualityItem(renderSettingsConverter); + + var urpAsset = ConvertCurrentQualityLevel(renderSettingsConverter, qualityItem, 30f); + GraphicsSettings.defaultRenderPipeline = urpAsset; + try + { + LogAssert.Expect(LogType.Warning, new Regex(Regex.Escape($"'{Link(urpAsset)}' is also used as the default render pipeline in Graphics settings"))); + ConvertCurrentQualityLevel(renderSettingsConverter, qualityItem, 70f); + } + finally + { + GraphicsSettings.defaultRenderPipeline = m_DefaultRenderPipeline; + } + } + [Test] public void WhenRunningBuiltInToURP3DRenderSettingsConverter_WithoutAnActiveURP_TheLightFalloffMode_IsQuadratic() { diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/Tools/ProjectAuditor/URPSettingsAnalyzerTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/Tools/ProjectAuditor/URPSettingsAnalyzerTests.cs index 3b9ecda04b4..7a4987f5ff0 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Editor/Tools/ProjectAuditor/URPSettingsAnalyzerTests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/Tools/ProjectAuditor/URPSettingsAnalyzerTests.cs @@ -18,6 +18,8 @@ namespace UnityEditor.Rendering.Universal.ProjectAuditor.Tests [TestFixture] class URPSettingsAnalyzerTests { + const string k_ShadowSettingsFolder = "Assets/URPSettingsAnalyzerTests"; + private UniversalRenderPipelineAsset m_PreviousDefaultRenderPipeline; private RenderPipelineAsset[] m_PreviousQualitySettings; private int m_PreviousQualityLevel; @@ -64,6 +66,9 @@ public void TearDown() QualitySettings.renderPipeline = m_PreviousQualitySettings[i]; } QualitySettings.SetQualityLevel(m_PreviousQualityLevel); + + if (AssetDatabase.IsValidFolder(k_ShadowSettingsFolder)) + AssetDatabase.DeleteAsset(k_ShadowSettingsFolder); } #region URP Assets Tests (0001-0100) @@ -315,6 +320,146 @@ public void URP0005_MSAA2x_NoIssue() UnityEngine.Object.DestroyImmediate(urpAsset); } + static UniversalRenderPipelineAsset CreateShadowSettingsAsset(string name, float shadowDistance, bool migrationPending) + { + string path = $"{k_ShadowSettingsFolder}/{name}.asset"; + UnityEngine.Rendering.CoreUtils.EnsureFolderTreeInAssetFilePath(path); + + var rendererData = ScriptableObject.CreateInstance(); + AssetDatabase.CreateAsset(rendererData, $"{k_ShadowSettingsFolder}/{name}_Renderer.asset"); + + var urpAsset = ScriptableObject.CreateInstance(); + urpAsset.m_RendererDataList = new ScriptableRendererData[] { rendererData }; + urpAsset.m_DefaultRendererIndex = 0; +#pragma warning disable 618 // Type or member is obsolete + urpAsset.m_ObsoleteShadowDistance = shadowDistance; +#pragma warning restore 618 + AssetDatabase.CreateAsset(urpAsset, path); + + // Set after the import, which would otherwise migrate a pending asset right away + urpAsset.m_ShadowSettingsMigrationPending = migrationPending; + return urpAsset; + } + + void UseInAllRenderPipelineSlots(UniversalRenderPipelineAsset urpAsset) + { + GraphicsSettings.defaultRenderPipeline = urpAsset; + for (int i = 0; i < QualitySettings.names.Length && i < m_PreviousQualitySettings.Length; i++) + { + QualitySettings.SetQualityLevel(i); + QualitySettings.renderPipeline = urpAsset; + } + } + + [Test] + public void URP0006_PendingShadowSettings_DetectsIssue() + { + UseInAllRenderPipelineSlots(CreateShadowSettingsAsset("Pending", 150f, migrationPending: true)); + var analyzer = new ShadowSettingsMigrationValidation(); + + var issues = analyzer.EnumerateIssues().ToList(); + + Assert.AreEqual(1 + QualitySettings.count, issues.Count, "Should detect shadow settings that are not migrated"); + Assert.AreEqual("URP0006", analyzer.Descriptor.Id); + Assert.IsNotNull(analyzer.Descriptor.Fixer); + } + + [Test] + public void URP0006_PendingDefaultShadowSettings_NoIssue() + { + var defaults = ScriptableObject.CreateInstance(); + float defaultDistance = defaults.maxShadowDistance.value; + UnityEngine.Object.DestroyImmediate(defaults); + UseInAllRenderPipelineSlots(CreateShadowSettingsAsset("PendingDefault", defaultDistance, migrationPending: true)); + + var issues = new ShadowSettingsMigrationValidation().EnumerateIssues().ToList(); + + Assert.AreEqual(0, issues.Count, "Should not detect default shadow settings, which render the same without a Shadows override"); + } + + [Test] + public void URP0006_MigratedShadowSettings_NoIssue() + { + UseInAllRenderPipelineSlots(CreateShadowSettingsAsset("Migrated", 150f, migrationPending: false)); + + var issues = new ShadowSettingsMigrationValidation().EnumerateIssues().ToList(); + + Assert.AreEqual(0, issues.Count, "Should not detect shadow settings that are already migrated"); + } + + [Test] + public void URP0006_Fix_MigratesShadowSettings() + { + var urpAsset = CreateShadowSettingsAsset("Fixed", 150f, migrationPending: true); + UseInAllRenderPipelineSlots(urpAsset); + + bool fixedIssue = ShadowSettingsMigrationValidation.FixShadowSettings(urpAsset); + + Assert.IsTrue(fixedIssue, "The fixer should report that it migrated the asset"); + Assert.IsFalse(urpAsset.m_ShadowSettingsMigrationPending, "The asset should no longer be pending"); + Assert.IsNotNull(urpAsset.volumeProfile, "The asset should get a volume profile"); + Assert.IsTrue(urpAsset.volumeProfile.TryGet(out ShadowsVolumeOverride shadows), "The volume profile should have a Shadows override"); + Assert.AreEqual(150f, shadows.maxShadowDistance.value); + Assert.AreEqual(0, new ShadowSettingsMigrationValidation().EnumerateIssues().Count(), "Should not detect an issue after the fix"); + } + + [Test] + public void URP0006_Fix_ReportsOnlyTheIssueAssetAsFixed() + { + var locked = CreateShadowSettingsAsset("FixLocked", 150f, migrationPending: true); + var editable = CreateShadowSettingsAsset("FixEditable", 80f, migrationPending: true); + UseInAllRenderPipelineSlots(editable); + GraphicsSettings.defaultRenderPipeline = locked; + var notEditablePaths = UnityEditor.Rendering.Universal.Test.GlobalSettingsMigration.ShadowSettingsMigrationTest.NotEditablePaths.s_Paths; + notEditablePaths.Add(AssetDatabase.GetAssetPath(locked)); + LogAssert.Expect(LogType.Warning, new Regex("FixLocked.*is not editable")); + LogAssert.Expect(LogType.Warning, new Regex("FixLocked.*is not editable")); + try + { + Assert.IsTrue(ShadowSettingsMigrationValidation.FixShadowSettings(editable), "The issue of the editable asset should be fixed"); + Assert.IsFalse(ShadowSettingsMigrationValidation.FixShadowSettings(locked), "The issue of the locked asset should not be fixed when another asset migrates"); + Assert.IsTrue(locked.m_ShadowSettingsMigrationPending, "The locked asset should stay pending"); + Assert.IsFalse(editable.m_ShadowSettingsMigrationPending, "The editable asset should be migrated"); + } + finally + { + notEditablePaths.Clear(); + } + } + + [Test] + public void URP0007_PendingShadowSettingsInReadOnlyPackage_DetectsIssue() + { + var urpAsset = CreateShadowSettingsAsset("ReadOnly", 150f, migrationPending: true); + UseInAllRenderPipelineSlots(urpAsset); + string packagePath = AssetDatabase.GetAssetPath(urpAsset); + var previousIsInReadOnlyPackage = UniversalRenderPipelineGlobalSettings.isInReadOnlyPackage; + UniversalRenderPipelineGlobalSettings.isInReadOnlyPackage = path => path == packagePath; + try + { + var analyzer = new ReadOnlyShadowSettingsMigrationValidation(); + + Assert.AreEqual(1 + QualitySettings.count, analyzer.EnumerateIssues().Count(), "Should detect shadow settings in a read-only package that are not migrated"); + Assert.AreEqual("URP0007", analyzer.Descriptor.Id); + Assert.IsNull(analyzer.Descriptor.Fixer, "A read-only package cannot be fixed in place"); + Assert.AreEqual(0, new ShadowSettingsMigrationValidation().EnumerateIssues().Count(), "URP0006 should not report an asset in a read-only package"); + } + finally + { + UniversalRenderPipelineGlobalSettings.isInReadOnlyPackage = previousIsInReadOnlyPackage; + } + } + + [Test] + public void URP0007_PendingShadowSettingsOutsideReadOnlyPackage_NoIssue() + { + UseInAllRenderPipelineSlots(CreateShadowSettingsAsset("Editable", 150f, migrationPending: true)); + + var issues = new ReadOnlyShadowSettingsMigrationValidation().EnumerateIssues().ToList(); + + Assert.AreEqual(0, issues.Count, "Should not detect shadow settings that URP0006 can fix"); + } + #endregion #region Renderer Tests (0101-0200) diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/UILitShaderRemapTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/UILitShaderRemapTests.cs new file mode 100644 index 00000000000..b26f3486c18 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/UILitShaderRemapTests.cs @@ -0,0 +1,45 @@ +using System.IO; +using System.Text.RegularExpressions; +using NUnit.Framework; +using UnityEditor; + +namespace UnityEngine.Rendering.Universal.Tests +{ + [TestFixture] + class UILitShaderRemapTests + { + const string k_MaterialPath = "Assets/UILitShaderRemapTest.mat"; + const string k_PlaceholderShader = "Universal Render Pipeline/Unlit"; + static readonly Regex k_ShaderReference = new Regex(@"m_Shader: \{[^}]*\}"); + + [TearDown] + public void TearDown() + { + AssetDatabase.DeleteAsset(k_MaterialPath); + } + + [TestCase(10764, "UI/Lit/Transparent")] + [TestCase(10765, "UI/Lit/Bumped")] + [TestCase(10766, "UI/Lit/Detail")] + [TestCase(10767, "UI/Lit/Refraction")] + [TestCase(10768, "UI/Lit/Refraction Detail")] + public void MaterialReferencingBuiltinUILitShader_LoadsPackageShader(int builtinFileID, string shaderName) + { + AssetDatabase.CreateAsset(new Material(Shader.Find(k_PlaceholderShader)), k_MaterialPath); + + // Point the saved material at the shader as it was referenced when UI/Lit was a built-in resource + string text = File.ReadAllText(k_MaterialPath); + string builtinReference = $"m_Shader: {{fileID: {builtinFileID}, guid: 0000000000000000f000000000000000, type: 0}}"; + if (!k_ShaderReference.IsMatch(text)) + Assert.Ignore("The test material was not saved as text, so its shader reference cannot be rewritten."); + File.WriteAllText(k_MaterialPath, k_ShaderReference.Replace(text, builtinReference, 1)); + AssetDatabase.ImportAsset(k_MaterialPath, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport); + + var material = AssetDatabase.LoadAssetAtPath(k_MaterialPath); + + Assert.IsNotNull(material, "Could not load the test material."); + Assert.IsNotNull(material.shader, "The material has no shader."); + Assert.AreEqual(shaderName, material.shader.name); + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/UILitShaderRemapTests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Editor/UILitShaderRemapTests.cs.meta new file mode 100644 index 00000000000..a47e2c32551 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/UILitShaderRemapTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9ad0e73b1e2046aeb94a5ad6ef236603 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/URPGlobalSettingsMigrationTests/ScreenSpaceAmbientOcclusionMigrationTest.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/URPGlobalSettingsMigrationTests/ScreenSpaceAmbientOcclusionMigrationTest.cs index 3fe6e9ee6b0..80c9dda436c 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Editor/URPGlobalSettingsMigrationTests/ScreenSpaceAmbientOcclusionMigrationTest.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/URPGlobalSettingsMigrationTests/ScreenSpaceAmbientOcclusionMigrationTest.cs @@ -1,8 +1,10 @@ using System.Linq; +using System.Text.RegularExpressions; using NUnit.Framework; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Rendering.Universal; +using UnityEngine.TestTools; namespace UnityEditor.Rendering.Universal.Test.GlobalSettingsMigration { @@ -30,6 +32,11 @@ static ScreenSpaceAmbientOcclusion AddFeature(UniversalRenderPipelineAsset rende if (!renderPipelineAsset.TryGetRendererData(renderPipelineAsset.m_DefaultRendererIndex, out rendererData)) return null; + return AddFeature(rendererData, active); + } + + static ScreenSpaceAmbientOcclusion AddFeature(ScriptableRendererData rendererData, bool active) + { var feature = ScriptableObject.CreateInstance(); feature.SetActive(active); @@ -147,6 +154,97 @@ public bool IsMigrationCorrect(URPDefaultVolumeProfileSettings settings, out str } } + class ActiveRendererFeatureOnNonDefaultRenderer : IRenderPipelineGraphicsSettingsTestCase + { + private ScriptableRendererData[] m_PreviousRendererDataList; + private UniversalRendererData m_RendererData; + private ScreenSpaceAmbientOcclusion m_Feature; + + public void SetUp(UniversalRenderPipelineGlobalSettings globalSettingsAsset, UniversalRenderPipelineAsset renderPipelineAsset) + { + m_RendererData = ScriptableObject.CreateInstance(); + m_Feature = AddFeature(m_RendererData, active: true); + + m_PreviousRendererDataList = renderPipelineAsset.m_RendererDataList; + renderPipelineAsset.m_RendererDataList = m_PreviousRendererDataList.Append(m_RendererData).ToArray(); + + SeedGlobalSettings(globalSettingsAsset, CreateProfileAsset(k_ProfilePath)); + } + + public void TearDown(UniversalRenderPipelineGlobalSettings globalSettingsAsset, UniversalRenderPipelineAsset renderPipelineAsset) + { + renderPipelineAsset.m_RendererDataList = m_PreviousRendererDataList; + RemoveFeature(m_RendererData, m_Feature); + Object.DestroyImmediate(m_RendererData); + AssetDatabase.DeleteAsset(k_ProfilePath); + } + + public bool IsMigrationCorrect(URPDefaultVolumeProfileSettings settings, out string message) + { + if (!TryGetMigratedOverride(settings, out var ssao)) + { + message = "The default volume profile has no ambient occlusion override"; + return false; + } + + return HasCopiedFeatureSettings(ssao, out message); + } + } + + class ActiveRendererFeaturesWithDifferentSettings : IRenderPipelineGraphicsSettingsTestCase + { + const string k_FirstRendererName = "FirstSSAORenderer"; + const string k_SecondRendererName = "SecondSSAORenderer"; + const float k_SecondIntensity = 1.5f; + + private ScriptableRendererData[] m_PreviousRendererDataList; + private UniversalRendererData m_FirstRendererData; + private UniversalRendererData m_SecondRendererData; + private ScreenSpaceAmbientOcclusion m_FirstFeature; + private ScreenSpaceAmbientOcclusion m_SecondFeature; + + public void SetUp(UniversalRenderPipelineGlobalSettings globalSettingsAsset, UniversalRenderPipelineAsset renderPipelineAsset) + { + m_FirstRendererData = ScriptableObject.CreateInstance(); + m_FirstRendererData.name = k_FirstRendererName; + m_FirstFeature = AddFeature(m_FirstRendererData, active: true); + + m_SecondRendererData = ScriptableObject.CreateInstance(); + m_SecondRendererData.name = k_SecondRendererName; + m_SecondFeature = AddFeature(m_SecondRendererData, active: true); +#pragma warning disable CS0618 // Type or member is obsolete + m_SecondFeature.settings.Intensity = k_SecondIntensity; +#pragma warning restore CS0618 + + m_PreviousRendererDataList = renderPipelineAsset.m_RendererDataList; + renderPipelineAsset.m_RendererDataList = m_PreviousRendererDataList.Append(m_FirstRendererData).Append(m_SecondRendererData).ToArray(); + + SeedGlobalSettings(globalSettingsAsset, CreateProfileAsset(k_ProfilePath)); + LogAssert.Expect(LogType.Warning, new Regex($"Only the settings of '{k_FirstRendererName}' were migrated.*\nNot migrated: '{k_SecondRendererName}'$")); + } + + public void TearDown(UniversalRenderPipelineGlobalSettings globalSettingsAsset, UniversalRenderPipelineAsset renderPipelineAsset) + { + renderPipelineAsset.m_RendererDataList = m_PreviousRendererDataList; + RemoveFeature(m_FirstRendererData, m_FirstFeature); + RemoveFeature(m_SecondRendererData, m_SecondFeature); + Object.DestroyImmediate(m_FirstRendererData); + Object.DestroyImmediate(m_SecondRendererData); + AssetDatabase.DeleteAsset(k_ProfilePath); + } + + public bool IsMigrationCorrect(URPDefaultVolumeProfileSettings settings, out string message) + { + if (!TryGetMigratedOverride(settings, out var ssao)) + { + message = "The default volume profile has no ambient occlusion override"; + return false; + } + + return HasCopiedFeatureSettings(ssao, out message); + } + } + class OverrideAlreadyAuthored : IRenderPipelineGraphicsSettingsTestCase { const float k_AuthoredIntensity = 9f; @@ -330,6 +428,10 @@ public override bool IsMigrationCorrect(URPDefaultVolumeProfileSettings settings .SetName("When migrating an active ambient occlusion renderer feature, its settings are being transferred correctly"), new TestCaseData(new InactiveRendererFeature()) .SetName("When migrating an inactive ambient occlusion renderer feature, the override is added without overriding anything"), + new TestCaseData(new ActiveRendererFeatureOnNonDefaultRenderer()) + .SetName("When the active ambient occlusion renderer feature is on a non-default renderer, its settings are being transferred correctly"), + new TestCaseData(new ActiveRendererFeaturesWithDifferentSettings()) + .SetName("When several renderers have active ambient occlusion renderer features with different settings, the first one is transferred and a warning names the others"), new TestCaseData(new OverrideAlreadyAuthored()) .SetName("When the default volume profile already has an ambient occlusion override, the migration leaves it untouched"), new TestCaseData(new QualityProfileOfActiveRendererFeature()) @@ -343,7 +445,21 @@ public override bool IsMigrationCorrect(URPDefaultVolumeProfileSettings settings [Test, TestCaseSource(nameof(s_TestCaseDatas))] public void PerformMigration(IRenderPipelineGraphicsSettingsTestCase testCase) { - base.DoTest(testCase); + // The migration reads every renderer of the asset, so keep only the default one to control what it finds + var previousRendererDataList = m_Asset.m_RendererDataList; + var previousDefaultRendererIndex = m_Asset.m_DefaultRendererIndex; + m_Asset.m_RendererDataList = new[] { previousRendererDataList[previousDefaultRendererIndex] }; + m_Asset.m_DefaultRendererIndex = 0; + + try + { + base.DoTest(testCase); + } + finally + { + m_Asset.m_RendererDataList = previousRendererDataList; + m_Asset.m_DefaultRendererIndex = previousDefaultRendererIndex; + } } } } diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/URPGlobalSettingsMigrationTests/ShadowSettingsImportMigrationTest.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/URPGlobalSettingsMigrationTests/ShadowSettingsImportMigrationTest.cs new file mode 100644 index 00000000000..59f24300687 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/URPGlobalSettingsMigrationTests/ShadowSettingsImportMigrationTest.cs @@ -0,0 +1,225 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.RegularExpressions; +using NUnit.Framework; +using UnityEngine; +using UnityEngine.Rendering; +using UnityEngine.Rendering.Universal; +using UnityEngine.TestTools; + +namespace UnityEditor.Rendering.Universal.Test.GlobalSettingsMigration +{ + class ShadowSettingsImportMigrationTest + { + const string k_Folder = "Assets/URP/MigrationTests/ShadowSettingsImport"; + + static string AssetPath(string name) => $"{k_Folder}/{name}.asset"; + + [SetUp] + public void SetUp() + { + if (GraphicsSettings.GetSettingsForRenderPipeline() is not UniversalRenderPipelineGlobalSettings globalSettings + || globalSettings.m_AssetVersion < UniversalRenderPipelineGlobalSettings.k_LastVersion) + { + Assert.Ignore("This test needs URP global settings at the last version"); + return; + } + + CoreUtils.EnsureFolderTreeInAssetFilePath(AssetPath("Folder")); + } + + [TearDown] + public void TearDown() + { + AssetDatabase.DeleteAsset(k_Folder); + } + + static void WriteVersion15PipelineAsset(string name, float shadowDistance, int cascadeCount, float cascade2Split, Vector3 cascade4Split, + float cascadeBorder, VolumeProfile profile) + { + string profileReference = profile == null + ? "{fileID: 0}" + : $"{{fileID: 11400000, guid: {AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(profile))}, type: 2}}"; + + File.WriteAllText(AssetPath(name), FormattableString.Invariant($@"%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!114 &11400000 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {{fileID: 0}} + m_PrefabInstance: {{fileID: 0}} + m_PrefabAsset: {{fileID: 0}} + m_GameObject: {{fileID: 0}} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {{fileID: 11500000, guid: bf2edee5c58d82540a51f03df9d42094, type: 3}} + m_Name: {name} + m_EditorClassIdentifier: + k_AssetVersion: 15 + k_AssetPreviousVersion: 15 + m_ShadowDistance: {shadowDistance} + m_ShadowCascadeCount: {cascadeCount} + m_Cascade2Split: {cascade2Split} + m_Cascade3Split: {{x: 0.1, y: 0.3}} + m_Cascade4Split: {{x: {cascade4Split.x}, y: {cascade4Split.y}, z: {cascade4Split.z}}} + m_CascadeBorder: {cascadeBorder} + m_VolumeProfile: {profileReference} +")); + } + + static string Link(string name) => + Regex.Escape("{name}"); + + static string CopyLine(string asset, string source) => + $"'{Link(asset)}' now uses '{Link($"{asset}_VolumeProfile")}', a copy of '{Link(source)}'\\."; + + static string RemainingLine(string source, string user) => $"'{Link(source)}' is still used by '{Link(user)}'\\."; + + static void AssertMigrated(UniversalRenderPipelineAsset urpAsset, float shadowDistance, int cascadeCount, Vector3 splits, float cascadeBorder) + { + Assert.IsNotNull(urpAsset, "The pipeline asset was not imported"); + Assert.IsFalse(urpAsset.m_ShadowSettingsMigrationPending, $"'{urpAsset.name}' must be marked as migrated after its import"); + string savedAsset = File.ReadAllText(AssetDatabase.GetAssetPath(urpAsset)); + StringAssert.Contains("k_AssetVersion: 16", savedAsset, $"'{urpAsset.name}' must be saved at the last version"); + StringAssert.Contains("m_ShadowSettingsMigrationPending: 0", savedAsset, $"'{urpAsset.name}' must be saved as migrated"); + + Assert.IsNotNull(urpAsset.volumeProfile, $"'{urpAsset.name}' has no volume profile"); + Assert.IsTrue(urpAsset.volumeProfile.TryGet(out ShadowsVolumeOverride shadows), $"The volume profile of '{urpAsset.name}' has no Shadows override"); + Assert.IsTrue(EditorUtility.IsPersistent(shadows) && AssetDatabase.GetAssetPath(shadows) == AssetDatabase.GetAssetPath(urpAsset.volumeProfile), + "The Shadows override must be saved inside the volume profile asset"); + + foreach (var parameter in shadows.parameters) + Assert.IsTrue(parameter.overrideState, "The migrated Shadows override must override every parameter"); + + Assert.AreEqual(shadowDistance, shadows.maxShadowDistance.value, 1e-5f, "maxShadowDistance"); + Assert.AreEqual(cascadeCount, shadows.cascadeCount.value, "cascadeCount"); + Assert.AreEqual(splits.x, shadows.cascadeSplit0.value, 1e-5f, "cascadeSplit0"); + Assert.AreEqual(splits.y, shadows.cascadeSplit1.value, 1e-5f, "cascadeSplit1"); + Assert.AreEqual(splits.z, shadows.cascadeSplit2.value, 1e-5f, "cascadeSplit2"); + Assert.AreEqual(cascadeBorder, shadows.lastCascadeBorder.value, 1e-5f, "lastCascadeBorder"); + } + + [Test] + [Description("A pipeline asset from before the Shadows volume override that is imported after the global settings migration gets its shadow settings in a volume profile.")] + public void ImportedVersion15AssetIsMigrated() + { + var splits = new Vector3(0.067f, 0.2f, 0.467f); + WriteVersion15PipelineAsset("Imported", 20f, 4, 0.25f, splits, 0.2f, null); + AssetDatabase.ImportAsset(AssetPath("Imported"), ImportAssetOptions.ForceSynchronousImport); + + var urpAsset = AssetDatabase.LoadAssetAtPath(AssetPath("Imported")); + AssertMigrated(urpAsset, 20f, 4, splits, 0.2f); + Assert.AreEqual(AssetPath("Imported_VolumeProfile"), AssetDatabase.GetAssetPath(urpAsset.volumeProfile)); + } + + [Test] + [Description("Two pipeline assets from before the Shadows volume override that share a volume profile and are imported together each keep their own shadow settings.")] + public void ImportedVersion15AssetsSharingAProfileGetTheirOwnValues() + { + var shared = ScriptableObject.CreateInstance(); + AssetDatabase.CreateAsset(shared, AssetPath("Shared")); + + var splits = new Vector3(0.1f, 0.3f, 0.6f); + WriteVersion15PipelineAsset("SharedA", 30f, 4, 0.25f, splits, 0.1f, shared); + WriteVersion15PipelineAsset("SharedB", 80f, 2, 0.4f, splits, 0.15f, shared); + LogAssert.Expect(LogType.Warning, new Regex(CopyLine("SharedA", "Shared") + "\n" + CopyLine("SharedB", "Shared"))); + AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport); + + var first = AssetDatabase.LoadAssetAtPath(AssetPath("SharedA")); + var second = AssetDatabase.LoadAssetAtPath(AssetPath("SharedB")); + + Assert.AreEqual(AssetPath("SharedA_VolumeProfile"), AssetDatabase.GetAssetPath(first.volumeProfile), "The first asset must use its own copy"); + Assert.AreEqual(AssetPath("SharedB_VolumeProfile"), AssetDatabase.GetAssetPath(second.volumeProfile), "The second asset must use its own copy"); + Assert.IsFalse(shared.Has(), "The shared profile must not get a Shadows override"); + AssertMigrated(first, 30f, 4, splits, 0.1f); + AssertMigrated(second, 80f, 2, new Vector3(0.4f, splits.y, splits.z), 0.15f); + } + + [Test] + [Description("Pipeline assets from before the Shadows volume override that share a volume profile and have the same shadow settings share one copy when they are imported together.")] + public void ImportedVersion15AssetsWithTheSameValuesShareOneCopy() + { + var shared = ScriptableObject.CreateInstance(); + AssetDatabase.CreateAsset(shared, AssetPath("Shared")); + + var splits = new Vector3(0.1f, 0.3f, 0.6f); + WriteVersion15PipelineAsset("SameA", 30f, 4, 0.25f, splits, 0.1f, shared); + WriteVersion15PipelineAsset("SameB", 30f, 4, 0.25f, splits, 0.1f, shared); + LogAssert.Expect(LogType.Warning, new Regex($"'{Link("SameA")}', '{Link("SameB")}' now use '{Link("Shared_Shadows")}', a copy of '{Link("Shared")}'\\.")); + AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport); + + var first = AssetDatabase.LoadAssetAtPath(AssetPath("SameA")); + var second = AssetDatabase.LoadAssetAtPath(AssetPath("SameB")); + + Assert.AreEqual(AssetPath("Shared_Shadows"), AssetDatabase.GetAssetPath(first.volumeProfile), "The first asset must use the shared copy"); + Assert.AreSame(first.volumeProfile, second.volumeProfile, "Both assets must use the same copy"); + Assert.AreEqual(2, AssetDatabase.FindAssets("t:VolumeProfile", new[] { k_Folder }).Length, "The import must create exactly one copy"); + AssertMigrated(first, 30f, 4, splits, 0.1f); + AssertMigrated(second, 30f, 4, splits, 0.1f); + } + + [Test] + [Description("A pipeline asset from before the Shadows volume override that shares a volume profile with an already migrated pipeline asset gets its own copy, and the warning names the migrated asset.")] + public void ImportedVersion15AssetSharingAProfileWithAMigratedAssetGetsACopy() + { + var shared = ScriptableObject.CreateInstance(); + AssetDatabase.CreateAsset(shared, AssetPath("Shared")); + + var migrated = ScriptableObject.CreateInstance(); + migrated.volumeProfile = shared; + AssetDatabase.CreateAsset(migrated, AssetPath("Migrated")); + + var splits = new Vector3(0.1f, 0.3f, 0.6f); + WriteVersion15PipelineAsset("Imported", 30f, 4, 0.25f, splits, 0.1f, shared); + LogAssert.Expect(LogType.Warning, new Regex(CopyLine("Imported", "Shared") + "\n" + RemainingLine("Shared", "Migrated"))); + AssetDatabase.ImportAsset(AssetPath("Imported"), ImportAssetOptions.ForceSynchronousImport); + + var imported = AssetDatabase.LoadAssetAtPath(AssetPath("Imported")); + Assert.AreEqual(AssetPath("Imported_VolumeProfile"), AssetDatabase.GetAssetPath(imported.volumeProfile), "The imported asset must use its own copy"); + Assert.AreSame(shared, migrated.volumeProfile, "The migrated asset must keep its volume profile"); + Assert.IsFalse(shared.Has(), "The shared profile must not get a Shadows override"); + AssertMigrated(imported, 30f, 4, splits, 0.1f); + } + + [Test] + [Description("A pipeline asset from before the Shadows volume override that the migration cannot process is still at the last version, so that builds accept it.")] + public void UnprocessedVersion15AssetIsAtLastVersion() + { + var globalSettings = GraphicsSettings.GetSettingsForRenderPipeline() as UniversalRenderPipelineGlobalSettings; + int previousVersion = globalSettings.m_AssetVersion; + globalSettings.m_AssetVersion = 16; + try + { + WriteVersion15PipelineAsset("Unprocessed", 20f, 4, 0.25f, new Vector3(0.067f, 0.2f, 0.467f), 0.2f, null); + AssetDatabase.ImportAsset(AssetPath("Unprocessed"), ImportAssetOptions.ForceSynchronousImport); + } + finally + { + globalSettings.m_AssetVersion = previousVersion; + } + + var urpAsset = AssetDatabase.LoadAssetAtPath(AssetPath("Unprocessed")); + Assert.IsTrue(urpAsset.IsAtLastVersion(), "An asset loaded from version 15 must be at the last version"); + Assert.IsTrue(urpAsset.m_ShadowSettingsMigrationPending, "An asset that was not migrated must stay pending"); + Assert.IsNull(urpAsset.volumeProfile, "An asset that was not migrated must not get a volume profile"); + } + + [Test] + [Description("A new pipeline asset is at the last version and has no shadow settings to migrate.")] + public void NewAssetHasNoPendingMigration() + { + var urpAsset = ScriptableObject.CreateInstance(); + try + { + Assert.IsTrue(urpAsset.IsAtLastVersion(), "A new asset must be at the last version"); + Assert.IsFalse(urpAsset.m_ShadowSettingsMigrationPending, "A new asset must not wait for a shadow settings migration"); + } + finally + { + UnityEngine.Object.DestroyImmediate(urpAsset); + } + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/URPGlobalSettingsMigrationTests/ShadowSettingsImportMigrationTest.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Editor/URPGlobalSettingsMigrationTests/ShadowSettingsImportMigrationTest.cs.meta new file mode 100644 index 00000000000..dea0cb63e6f --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/URPGlobalSettingsMigrationTests/ShadowSettingsImportMigrationTest.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 5326f89909ff46d69ea8d830d74ae85e diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/URPGlobalSettingsMigrationTests/ShadowSettingsMigrationTest.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/URPGlobalSettingsMigrationTests/ShadowSettingsMigrationTest.cs new file mode 100644 index 00000000000..532b6158cbb --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/URPGlobalSettingsMigrationTests/ShadowSettingsMigrationTest.cs @@ -0,0 +1,841 @@ +using System.Collections.Generic; +using System.Text.RegularExpressions; +using NUnit.Framework; +using UnityEngine; +using UnityEngine.Rendering; +using UnityEngine.Rendering.Universal; +using UnityEngine.TestTools; + +namespace UnityEditor.Rendering.Universal.Test.GlobalSettingsMigration +{ + class ShadowSettingsMigrationTest : RenderPipelineGraphicsSettingsMigrationTestBase + { + const string k_Folder = "Assets/URP/MigrationTests/ShadowSettings"; + + static readonly Vector3 k_Cascade4Split = new Vector3(0.1f, 0.3f, 0.6f); + + static string AssetPath(string name) => $"{k_Folder}/{name}.asset"; + static string MigratedProfilePath(string name) => $"{k_Folder}/{name}_VolumeProfile.asset"; + + static UniversalRenderPipelineAsset CreatePipelineAsset(string name, float shadowDistance, int cascadeCount, float cascadeBorder, + float cascade2Split = 0.25f, Vector2 cascade3Split = default, VolumeProfile profile = null) + { + var urpAsset = ScriptableObject.CreateInstance(); + urpAsset.m_ShadowSettingsMigrationPending = true; +#pragma warning disable 618 // Type or member is obsolete + urpAsset.m_ObsoleteShadowDistance = shadowDistance; + urpAsset.m_ObsoleteShadowCascadeCount = cascadeCount; + urpAsset.m_ObsoleteCascade2Split = cascade2Split; + urpAsset.m_ObsoleteCascade3Split = cascade3Split == default ? new Vector2(0.1f, 0.3f) : cascade3Split; + urpAsset.m_ObsoleteCascade4Split = k_Cascade4Split; + urpAsset.m_ObsoleteCascadeBorder = cascadeBorder; +#pragma warning restore 618 + urpAsset.volumeProfile = profile; + + string path = AssetPath(name); + CoreUtils.EnsureFolderTreeInAssetFilePath(path); + AssetDatabase.CreateAsset(urpAsset, path); + return urpAsset; + } + + static UniversalRenderPipelineAsset CreateDefaultPipelineAsset(string name, VolumeProfile profile = null) + { + var urpAsset = ScriptableObject.CreateInstance(); + urpAsset.m_ShadowSettingsMigrationPending = true; + urpAsset.volumeProfile = profile; + + string path = AssetPath(name); + CoreUtils.EnsureFolderTreeInAssetFilePath(path); + AssetDatabase.CreateAsset(urpAsset, path); + return urpAsset; + } + + static VolumeProfile CreateProfileAsset(string name) + { + var profile = ScriptableObject.CreateInstance(); + string path = AssetPath(name); + CoreUtils.EnsureFolderTreeInAssetFilePath(path); + AssetDatabase.CreateAsset(profile, path); + return profile; + } + + static T AddPersistedOverride(VolumeProfile profile) where T : VolumeComponent + { + var volumeOverride = profile.Add(overrides: true); + AssetDatabase.AddObjectToAsset(volumeOverride, profile); + return volumeOverride; + } + + static bool AllParametersOverridden(VolumeComponent component) + { + foreach (var parameter in component.parameters) + { + if (!parameter.overrideState) + return false; + } + return true; + } + + // AssetDatabase.IsSubAsset is false for volume components, which are hidden in the hierarchy + static bool IsSavedInProfile(VolumeComponent component, VolumeProfile profile) + { + return EditorUtility.IsPersistent(component) && AssetDatabase.GetAssetPath(component) == AssetDatabase.GetAssetPath(profile); + } + + static bool HasMigratedValues(VolumeProfile profile, float shadowDistance, int cascadeCount, Vector3 splits, float cascadeBorder, out string message) + { + if (profile == null || !profile.TryGet(out ShadowsVolumeOverride shadows)) + { + message = "The pipeline asset has no volume profile with a Shadows override"; + return false; + } + + if (!AllParametersOverridden(shadows)) + { + message = "The migrated Shadows override must override every parameter"; + return false; + } + + if (!Mathf.Approximately(shadows.maxShadowDistance.value, shadowDistance) || + shadows.cascadeCount.value != cascadeCount || + !Mathf.Approximately(shadows.cascadeSplit0.value, splits.x) || + !Mathf.Approximately(shadows.cascadeSplit1.value, splits.y) || + !Mathf.Approximately(shadows.cascadeSplit2.value, splits.z) || + !Mathf.Approximately(shadows.lastCascadeBorder.value, cascadeBorder)) + { + message = $"Values were not copied: distance {shadows.maxShadowDistance.value}, count {shadows.cascadeCount.value}, " + + $"splits ({shadows.cascadeSplit0.value}, {shadows.cascadeSplit1.value}, {shadows.cascadeSplit2.value}), border {shadows.lastCascadeBorder.value}"; + return false; + } + + if (!IsSavedInProfile(shadows, profile)) + { + message = "The Shadows override must be saved inside the volume profile asset"; + return false; + } + + message = string.Empty; + return true; + } + + static bool UsesCopyWithBloom(UniversalRenderPipelineAsset urpAsset, out string message) => + UsesCopyWithBloom(urpAsset, MigratedProfilePath(urpAsset.name), out message); + + static bool UsesCopyWithBloom(UniversalRenderPipelineAsset urpAsset, string copyPath, out string message) + { + if (AssetDatabase.GetAssetPath(urpAsset.volumeProfile) != copyPath) + { + message = $"'{urpAsset.name}' must use a copy at {copyPath}, got '{AssetDatabase.GetAssetPath(urpAsset.volumeProfile)}'"; + return false; + } + + if (!urpAsset.volumeProfile.TryGet(out Bloom copiedBloom) || !IsSavedInProfile(copiedBloom, urpAsset.volumeProfile)) + { + message = $"The copy of '{urpAsset.name}' must keep the other overrides of the original volume profile"; + return false; + } + + message = string.Empty; + return true; + } + + static string Link(string path) => + Regex.Escape("{System.IO.Path.GetFileNameWithoutExtension(path)}"); + + static string Links(string[] names) => string.Join(", ", System.Array.ConvertAll(names, name => $"'{Link(AssetPath(name))}'")); + + static string CopyLine(string asset, string source, bool sourceIsDefaultProfile = false) => + SharedCopyLine(new[] { asset }, $"{asset}_VolumeProfile", source, sourceIsDefaultProfile); + + static string SharedCopyLine(string[] assets, string copy, string source, bool sourceIsDefaultProfile = false) => + $"{Links(assets)} now {(assets.Length == 1 ? "uses" : "use")} '{Link(AssetPath(copy))}', a copy of " + + (sourceIsDefaultProfile ? "the default volume profile " : string.Empty) + $"'{Link(AssetPath(source))}'\\."; + + static string RemainingLine(string source, params string[] users) => $"'{Link(AssetPath(source))}' is still used by {Links(users)}\\."; + + static Regex CopyWarning(params string[] lines) => new Regex(string.Join("\n", lines)); + + static int CountAssetsInFolder() + { + return AssetDatabase.FindAssets(string.Empty, new[] { k_Folder }).Length; + } + + // Version 16 lets only the shadow settings step run + abstract class ShadowTestCase : IRenderPipelineGraphicsSettingsTestCase + { + protected UniversalRenderPipelineGlobalSettings m_GlobalSettings; + + public void SetUp(UniversalRenderPipelineGlobalSettings globalSettingsAsset, UniversalRenderPipelineAsset renderPipelineAsset) + { + m_GlobalSettings = globalSettingsAsset; + globalSettingsAsset.m_AssetVersion = 16; + CreateAssets(); + } + + public virtual void TearDown(UniversalRenderPipelineGlobalSettings globalSettingsAsset, UniversalRenderPipelineAsset renderPipelineAsset) + { + AssetDatabase.DeleteAsset(k_Folder); + } + + protected abstract void CreateAssets(); + + public abstract bool IsMigrationCorrect(URPDefaultVolumeProfileSettings settings, out string message); + } + + class NonDefaultAssetWithoutProfile : ShadowTestCase + { + UniversalRenderPipelineAsset m_Asset; + + protected override void CreateAssets() + { + m_Asset = CreatePipelineAsset("NonDefault", 150f, 4, 0.1f); + } + + public override bool IsMigrationCorrect(URPDefaultVolumeProfileSettings settings, out string message) + { + if (m_Asset.volumeProfile == null || AssetDatabase.GetAssetPath(m_Asset.volumeProfile) != MigratedProfilePath("NonDefault")) + { + message = $"Expected a new volume profile at {MigratedProfilePath("NonDefault")}, got '{AssetDatabase.GetAssetPath(m_Asset.volumeProfile)}'"; + return false; + } + + if (m_Asset.m_ShadowSettingsMigrationPending) + { + message = "A migrated pipeline asset must be marked as migrated"; + return false; + } + + return HasMigratedValues(m_Asset.volumeProfile, 150f, 4, k_Cascade4Split, 0.1f, out message); + } + } + + class DefaultAsset : ShadowTestCase + { + UniversalRenderPipelineAsset m_Asset; + + protected override void CreateAssets() + { + m_Asset = CreateDefaultPipelineAsset("Default"); + } + + public override bool IsMigrationCorrect(URPDefaultVolumeProfileSettings settings, out string message) + { + if (m_Asset.volumeProfile != null || AssetDatabase.AssetPathExists(MigratedProfilePath("Default"))) + { + message = "A pipeline asset with default shadow settings must not get a volume profile"; + return false; + } + + message = "A pipeline asset with default shadow settings must still be marked as migrated, so that importing it again does not migrate it"; + return !m_Asset.m_ShadowSettingsMigrationPending; + } + } + + class SharedProfileWithDifferentValues : ShadowTestCase + { + UniversalRenderPipelineAsset m_First; + UniversalRenderPipelineAsset m_Second; + VolumeProfile m_SharedProfile; + + protected override void CreateAssets() + { + m_SharedProfile = CreateProfileAsset("Shared"); + AddPersistedOverride(m_SharedProfile); + + m_First = CreatePipelineAsset("SharedA", 80f, 2, 0.15f, cascade2Split: 0.4f, profile: m_SharedProfile); + m_Second = CreatePipelineAsset("SharedB", 120f, 4, 0.1f, profile: m_SharedProfile); + + LogAssert.Expect(LogType.Warning, CopyWarning(CopyLine("SharedA", "Shared"), CopyLine("SharedB", "Shared"))); + } + + public override bool IsMigrationCorrect(URPDefaultVolumeProfileSettings settings, out string message) + { + if (m_SharedProfile.Has()) + { + message = "The shared volume profile must not get a Shadows override"; + return false; + } + + if (!UsesCopyWithBloom(m_First, out message) || !UsesCopyWithBloom(m_Second, out message)) + return false; + + if (!HasMigratedValues(m_First.volumeProfile, 80f, 2, new Vector3(0.4f, k_Cascade4Split.y, k_Cascade4Split.z), 0.15f, out message)) + return false; + + return HasMigratedValues(m_Second.volumeProfile, 120f, 4, k_Cascade4Split, 0.1f, out message); + } + } + + class SharedProfileWithDefaultAsset : ShadowTestCase + { + UniversalRenderPipelineAsset m_Default; + UniversalRenderPipelineAsset m_NonDefault; + VolumeProfile m_SharedProfile; + + protected override void CreateAssets() + { + m_SharedProfile = CreateProfileAsset("Shared"); + m_Default = CreateDefaultPipelineAsset("Mobile", m_SharedProfile); + m_NonDefault = CreatePipelineAsset("PC", 120f, 4, 0.1f, profile: m_SharedProfile); + + LogAssert.Expect(LogType.Warning, CopyWarning(CopyLine("PC", "Shared"), RemainingLine("Shared", "Mobile"))); + } + + public override bool IsMigrationCorrect(URPDefaultVolumeProfileSettings settings, out string message) + { + if (m_Default.volumeProfile != m_SharedProfile || m_SharedProfile.Has()) + { + message = "A default pipeline asset must keep its shared volume profile without a Shadows override"; + return false; + } + + if (m_NonDefault.volumeProfile == m_SharedProfile) + { + message = "A pipeline asset that shares its profile with a default one must use a copy"; + return false; + } + + return HasMigratedValues(m_NonDefault.volumeProfile, 120f, 4, k_Cascade4Split, 0.1f, out message); + } + } + + class OverrideAlreadyAuthored : ShadowTestCase + { + const float k_AuthoredDistance = 7f; + + UniversalRenderPipelineAsset m_Asset; + VolumeProfile m_Profile; + + protected override void CreateAssets() + { + m_Profile = CreateProfileAsset("Authored"); + AddPersistedOverride(m_Profile).maxShadowDistance.value = k_AuthoredDistance; + m_Asset = CreatePipelineAsset("WithAuthoredOverride", 150f, 4, 0.1f, profile: m_Profile); + } + + public override bool IsMigrationCorrect(URPDefaultVolumeProfileSettings settings, out string message) + { + if (m_Asset.volumeProfile != m_Profile || !m_Profile.TryGet(out ShadowsVolumeOverride shadows)) + { + message = "The pipeline asset lost its authored Shadows override"; + return false; + } + + message = $"An override that was already on the profile must keep its authored distance, got {shadows.maxShadowDistance.value}"; + return Mathf.Approximately(shadows.maxShadowDistance.value, k_AuthoredDistance); + } + } + + class SplitSetOfCascadeCount : ShadowTestCase + { + UniversalRenderPipelineAsset m_TwoCascades; + UniversalRenderPipelineAsset m_ThreeCascades; + UniversalRenderPipelineAsset m_OneCascade; + + protected override void CreateAssets() + { + m_TwoCascades = CreatePipelineAsset("TwoCascades", 60f, 2, 0.2f, cascade2Split: 0.35f); + m_ThreeCascades = CreatePipelineAsset("ThreeCascades", 60f, 3, 0.2f, cascade3Split: new Vector2(0.15f, 0.45f)); + m_OneCascade = CreatePipelineAsset("OneCascade", 60f, 1, 0.2f); + } + + public override bool IsMigrationCorrect(URPDefaultVolumeProfileSettings settings, out string message) + { + if (!HasMigratedValues(m_TwoCascades.volumeProfile, 60f, 2, new Vector3(0.35f, k_Cascade4Split.y, k_Cascade4Split.z), 0.2f, out message)) + { + message = $"Two cascades: {message}"; + return false; + } + + if (!HasMigratedValues(m_ThreeCascades.volumeProfile, 60f, 3, new Vector3(0.15f, 0.45f, k_Cascade4Split.z), 0.2f, out message)) + { + message = $"Three cascades: {message}"; + return false; + } + + if (!HasMigratedValues(m_OneCascade.volumeProfile, 60f, 1, k_Cascade4Split, 0.2f, out message)) + { + message = $"One cascade: {message}"; + return false; + } + + return true; + } + } + + class DefaultProfileAsQualityProfile : ShadowTestCase + { + URPDefaultVolumeProfileSettings m_Settings; + VolumeProfile m_PreviousDefaultProfile; + VolumeProfile m_DefaultProfile; + UniversalRenderPipelineAsset m_DefaultAsset; + UniversalRenderPipelineAsset m_NonDefaultAsset; + + protected override void CreateAssets() + { + m_DefaultProfile = CreateProfileAsset("DefaultProfile"); + AddPersistedOverride(m_DefaultProfile); + + m_Settings = GraphicsSettings.GetRenderPipelineSettings(); + Assert.IsNotNull(m_Settings, "The global settings have no default volume profile settings"); + m_PreviousDefaultProfile = m_Settings.volumeProfile; + m_Settings.volumeProfile = m_DefaultProfile; + + m_DefaultAsset = CreateDefaultPipelineAsset("DefaultValues", m_DefaultProfile); + m_NonDefaultAsset = CreatePipelineAsset("NonDefaultValues", 150f, 4, 0.1f, profile: m_DefaultProfile); + + LogAssert.Expect(LogType.Warning, CopyWarning(CopyLine("NonDefaultValues", "DefaultProfile", sourceIsDefaultProfile: true), + RemainingLine("DefaultProfile", "DefaultValues"))); + } + + public override void TearDown(UniversalRenderPipelineGlobalSettings globalSettingsAsset, UniversalRenderPipelineAsset renderPipelineAsset) + { + m_Settings.volumeProfile = m_PreviousDefaultProfile; + base.TearDown(globalSettingsAsset, renderPipelineAsset); + } + + public override bool IsMigrationCorrect(URPDefaultVolumeProfileSettings settings, out string message) + { + if (m_DefaultProfile.Has()) + { + message = "The default volume profile must not get a Shadows override, because every quality level inherits it"; + return false; + } + + if (m_DefaultAsset.volumeProfile != m_DefaultProfile) + { + message = "A pipeline asset with default shadow settings must keep the default volume profile as its quality profile"; + return false; + } + + if (!UsesCopyWithBloom(m_NonDefaultAsset, out message)) + return false; + + return HasMigratedValues(m_NonDefaultAsset.volumeProfile, 150f, 4, k_Cascade4Split, 0.1f, out message); + } + } + + class MigratingTwice : ShadowTestCase + { + UniversalRenderPipelineAsset m_First; + UniversalRenderPipelineAsset m_Second; + + protected override void CreateAssets() + { + var shared = CreateProfileAsset("Shared"); + m_First = CreatePipelineAsset("SharedA", 80f, 2, 0.15f, profile: shared); + m_Second = CreatePipelineAsset("SharedB", 120f, 4, 0.1f, profile: shared); + + LogAssert.Expect(LogType.Warning, CopyWarning(CopyLine("SharedA", "Shared"), CopyLine("SharedB", "Shared"))); + } + + public override bool IsMigrationCorrect(URPDefaultVolumeProfileSettings settings, out string message) + { + int assetCount = CountAssetsInFolder(); + var firstProfile = m_First.volumeProfile; + var secondProfile = m_Second.volumeProfile; + + m_GlobalSettings.m_AssetVersion = 16; + UniversalRenderPipelineGlobalSettings.UpgradeAsset(m_GlobalSettings.GetEntityId()); + + if (CountAssetsInFolder() != assetCount || m_First.volumeProfile != firstProfile || m_Second.volumeProfile != secondProfile) + { + message = "Running the migration again must not create or reassign volume profiles"; + return false; + } + + if (firstProfile.components.Count != 1 || secondProfile.components.Count != 1) + { + message = $"Running the migration again must not add overrides, got {firstProfile.components.Count} and {secondProfile.components.Count}"; + return false; + } + + message = string.Empty; + return true; + } + } + + internal class NotEditablePaths : AssetModificationProcessor + { + internal static readonly HashSet s_Paths = new HashSet(); + + static bool MakeEditable(string[] paths, string prompt, List outNotEditablePaths) + { + bool editable = true; + foreach (var path in paths) + { + if (!s_Paths.Contains(path)) + continue; + + outNotEditablePaths.Add(path); + editable = false; + } + return editable; + } + } + + class NotEditableProfile : ShadowTestCase + { + UniversalRenderPipelineAsset m_Asset; + VolumeProfile m_Profile; + + protected override void CreateAssets() + { + m_Profile = CreateProfileAsset("Locked"); + m_Asset = CreatePipelineAsset("WithLockedProfile", 150f, 4, 0.1f, profile: m_Profile); + NotEditablePaths.s_Paths.Add(AssetPath("Locked")); + + LogAssert.Expect(LogType.Warning, CopyWarning(CopyLine("WithLockedProfile", "Locked"))); + } + + public override void TearDown(UniversalRenderPipelineGlobalSettings globalSettingsAsset, UniversalRenderPipelineAsset renderPipelineAsset) + { + NotEditablePaths.s_Paths.Clear(); + base.TearDown(globalSettingsAsset, renderPipelineAsset); + } + + public override bool IsMigrationCorrect(URPDefaultVolumeProfileSettings settings, out string message) + { + if (m_Profile.Has()) + { + message = "The locked volume profile must stay unchanged"; + return false; + } + + if (m_Asset.m_ShadowSettingsMigrationPending) + { + message = "A pipeline asset whose volume profile is locked must still migrate to a copy"; + return false; + } + + return HasMigratedValues(m_Asset.volumeProfile, 150f, 4, k_Cascade4Split, 0.1f, out message); + } + } + + class NotEditableAsset : ShadowTestCase + { + UniversalRenderPipelineAsset m_Asset; + + protected override void CreateAssets() + { + m_Asset = CreatePipelineAsset("Locked", 150f, 4, 0.1f); + NotEditablePaths.s_Paths.Add(AssetPath("Locked")); + + LogAssert.Expect(LogType.Warning, new Regex($"'{Link(AssetPath("Locked"))}' is not editable")); + } + + public override void TearDown(UniversalRenderPipelineGlobalSettings globalSettingsAsset, UniversalRenderPipelineAsset renderPipelineAsset) + { + NotEditablePaths.s_Paths.Clear(); + base.TearDown(globalSettingsAsset, renderPipelineAsset); + } + + public override bool IsMigrationCorrect(URPDefaultVolumeProfileSettings settings, out string message) + { + if (m_Asset.volumeProfile != null || AssetDatabase.AssetPathExists(MigratedProfilePath("Locked"))) + { + message = "A pipeline asset that is not editable must not get a volume profile"; + return false; + } + + message = "A pipeline asset that is not editable must stay pending, so that a later migration can retry"; + return m_Asset.m_ShadowSettingsMigrationPending; + } + } + + class ProfileOfOneAsset : ShadowTestCase + { + UniversalRenderPipelineAsset m_Asset; + VolumeProfile m_Profile; + + protected override void CreateAssets() + { + m_Profile = CreateProfileAsset("Own"); + AddPersistedOverride(m_Profile); + m_Asset = CreatePipelineAsset("WithOwnProfile", 150f, 4, 0.1f, profile: m_Profile); + + LogAssert.Expect(LogType.Warning, CopyWarning(CopyLine("WithOwnProfile", "Own"))); + } + + public override bool IsMigrationCorrect(URPDefaultVolumeProfileSettings settings, out string message) + { + if (m_Profile.Has()) + { + message = "Scenes and prefabs can also use the volume profile, so it must not get a Shadows override"; + return false; + } + + if (!UsesCopyWithBloom(m_Asset, out message)) + return false; + + return HasMigratedValues(m_Asset.volumeProfile, 150f, 4, k_Cascade4Split, 0.1f, out message); + } + } + + class SharedProfileWithSameValues : ShadowTestCase + { + UniversalRenderPipelineAsset m_First; + UniversalRenderPipelineAsset m_Second; + VolumeProfile m_SharedProfile; + + protected override void CreateAssets() + { + m_SharedProfile = CreateProfileAsset("Shared"); + AddPersistedOverride(m_SharedProfile); + + m_First = CreatePipelineAsset("SameA", 120f, 4, 0.1f, profile: m_SharedProfile); + m_Second = CreatePipelineAsset("SameB", 120f, 4, 0.1f, profile: m_SharedProfile); + + LogAssert.Expect(LogType.Warning, CopyWarning("share one new profile\\.", SharedCopyLine(new[] { "SameA", "SameB" }, "Shared_Shadows", "Shared"))); + } + + public override bool IsMigrationCorrect(URPDefaultVolumeProfileSettings settings, out string message) + { + if (m_SharedProfile.Has()) + { + message = "The shared volume profile must not get a Shadows override"; + return false; + } + + if (m_First.volumeProfile != m_Second.volumeProfile) + { + message = "Pipeline assets with the same volume profile and shadow settings must share one copy"; + return false; + } + + if (!UsesCopyWithBloom(m_First, AssetPath("Shared_Shadows"), out message)) + return false; + + return HasMigratedValues(m_First.volumeProfile, 120f, 4, k_Cascade4Split, 0.1f, out message); + } + } + + class SharedProfileWithMixedValues : ShadowTestCase + { + UniversalRenderPipelineAsset m_SameA; + UniversalRenderPipelineAsset m_SameB; + UniversalRenderPipelineAsset m_Other; + UniversalRenderPipelineAsset m_Default; + VolumeProfile m_SharedProfile; + + protected override void CreateAssets() + { + m_SharedProfile = CreateProfileAsset("Shared"); + AddPersistedOverride(m_SharedProfile); + + m_SameA = CreatePipelineAsset("MixedA", 120f, 4, 0.1f, profile: m_SharedProfile); + m_SameB = CreatePipelineAsset("MixedB", 120f, 4, 0.1f, profile: m_SharedProfile); + m_Other = CreatePipelineAsset("MixedC", 80f, 2, 0.15f, profile: m_SharedProfile); + m_Default = CreateDefaultPipelineAsset("MixedD", m_SharedProfile); + + LogAssert.Expect(LogType.Warning, CopyWarning( + SharedCopyLine(new[] { "MixedA", "MixedB" }, "Shared_Shadows", "Shared"), + CopyLine("MixedC", "Shared"), + RemainingLine("Shared", "MixedD"))); + } + + public override bool IsMigrationCorrect(URPDefaultVolumeProfileSettings settings, out string message) + { + if (m_Default.volumeProfile != m_SharedProfile || m_SharedProfile.Has()) + { + message = "A default pipeline asset must keep the shared volume profile without a Shadows override"; + return false; + } + + if (m_SameA.volumeProfile != m_SameB.volumeProfile || !UsesCopyWithBloom(m_SameA, AssetPath("Shared_Shadows"), out message)) + { + message = "Pipeline assets with the same shadow settings must share one copy"; + return false; + } + + if (!UsesCopyWithBloom(m_Other, out message)) + return false; + + if (!HasMigratedValues(m_SameA.volumeProfile, 120f, 4, k_Cascade4Split, 0.1f, out message)) + return false; + + return HasMigratedValues(m_Other.volumeProfile, 80f, 2, new Vector3(0.25f, k_Cascade4Split.y, k_Cascade4Split.z), 0.15f, out message); + } + } + + class SameValuesWithoutProfile : ShadowTestCase + { + UniversalRenderPipelineAsset m_First; + UniversalRenderPipelineAsset m_Second; + + protected override void CreateAssets() + { + m_First = CreatePipelineAsset("NoProfileA", 150f, 4, 0.1f); + m_Second = CreatePipelineAsset("NoProfileB", 150f, 4, 0.1f); + } + + public override bool IsMigrationCorrect(URPDefaultVolumeProfileSettings settings, out string message) + { + if (AssetDatabase.GetAssetPath(m_First.volumeProfile) != MigratedProfilePath("NoProfileA") + || AssetDatabase.GetAssetPath(m_Second.volumeProfile) != MigratedProfilePath("NoProfileB")) + { + message = "Pipeline assets without a volume profile must each get their own profile, even with the same shadow settings"; + return false; + } + + return HasMigratedValues(m_First.volumeProfile, 150f, 4, k_Cascade4Split, 0.1f, out message) + && HasMigratedValues(m_Second.volumeProfile, 150f, 4, k_Cascade4Split, 0.1f, out message); + } + } + + class SameValuesWithDifferentProfiles : ShadowTestCase + { + UniversalRenderPipelineAsset m_First; + UniversalRenderPipelineAsset m_Second; + + protected override void CreateAssets() + { + m_First = CreatePipelineAsset("OnProfileA", 150f, 4, 0.1f, profile: CreateProfileAsset("ProfileA")); + m_Second = CreatePipelineAsset("OnProfileB", 150f, 4, 0.1f, profile: CreateProfileAsset("ProfileB")); + + LogAssert.Expect(LogType.Warning, CopyWarning(CopyLine("OnProfileA", "ProfileA"), CopyLine("OnProfileB", "ProfileB"))); + } + + public override bool IsMigrationCorrect(URPDefaultVolumeProfileSettings settings, out string message) + { + if (AssetDatabase.GetAssetPath(m_First.volumeProfile) != MigratedProfilePath("OnProfileA") + || AssetDatabase.GetAssetPath(m_Second.volumeProfile) != MigratedProfilePath("OnProfileB")) + { + message = "Pipeline assets with different volume profiles must get their own copies, even with the same shadow settings"; + return false; + } + + return HasMigratedValues(m_First.volumeProfile, 150f, 4, k_Cascade4Split, 0.1f, out message) + && HasMigratedValues(m_Second.volumeProfile, 150f, 4, k_Cascade4Split, 0.1f, out message); + } + } + + class NotEditableAssetWithSameValues : ShadowTestCase + { + UniversalRenderPipelineAsset m_Locked; + UniversalRenderPipelineAsset m_Editable; + VolumeProfile m_SharedProfile; + + protected override void CreateAssets() + { + m_SharedProfile = CreateProfileAsset("Shared"); + m_Locked = CreatePipelineAsset("GroupA", 120f, 4, 0.1f, profile: m_SharedProfile); + m_Editable = CreatePipelineAsset("GroupB", 120f, 4, 0.1f, profile: m_SharedProfile); + NotEditablePaths.s_Paths.Add(AssetPath("GroupA")); + + LogAssert.Expect(LogType.Warning, new Regex($"'{Link(AssetPath("GroupA"))}' is not editable")); + LogAssert.Expect(LogType.Warning, CopyWarning(CopyLine("GroupB", "Shared"), RemainingLine("Shared", "GroupA"))); + } + + public override void TearDown(UniversalRenderPipelineGlobalSettings globalSettingsAsset, UniversalRenderPipelineAsset renderPipelineAsset) + { + NotEditablePaths.s_Paths.Clear(); + base.TearDown(globalSettingsAsset, renderPipelineAsset); + } + + public override bool IsMigrationCorrect(URPDefaultVolumeProfileSettings settings, out string message) + { + if (m_Locked.volumeProfile != m_SharedProfile || !m_Locked.m_ShadowSettingsMigrationPending) + { + message = "A pipeline asset that is not editable must keep its volume profile and stay pending"; + return false; + } + + if (AssetDatabase.GetAssetPath(m_Editable.volumeProfile) != MigratedProfilePath("GroupB")) + { + message = $"The editable pipeline asset must use a copy named after itself, got '{AssetDatabase.GetAssetPath(m_Editable.volumeProfile)}'"; + return false; + } + + return HasMigratedValues(m_Editable.volumeProfile, 120f, 4, k_Cascade4Split, 0.1f, out message); + } + } + + class AssetInReadOnlyPackage : ShadowTestCase + { + System.Predicate m_PreviousIsInReadOnlyPackage; + UniversalRenderPipelineAsset m_InPackage; + UniversalRenderPipelineAsset m_InProject; + + protected override void CreateAssets() + { + m_InPackage = CreatePipelineAsset("InReadOnlyPackage", 150f, 4, 0.1f); + m_InProject = CreatePipelineAsset("InProject", 80f, 2, 0.15f); + + m_PreviousIsInReadOnlyPackage = UniversalRenderPipelineGlobalSettings.isInReadOnlyPackage; + string packagePath = AssetPath("InReadOnlyPackage"); + UniversalRenderPipelineGlobalSettings.isInReadOnlyPackage = path => path == packagePath; + + LogAssert.Expect(LogType.Warning, new Regex($"'{Link(packagePath)}' is in a read-only package")); + } + + public override void TearDown(UniversalRenderPipelineGlobalSettings globalSettingsAsset, UniversalRenderPipelineAsset renderPipelineAsset) + { + UniversalRenderPipelineGlobalSettings.isInReadOnlyPackage = m_PreviousIsInReadOnlyPackage; + base.TearDown(globalSettingsAsset, renderPipelineAsset); + } + + public override bool IsMigrationCorrect(URPDefaultVolumeProfileSettings settings, out string message) + { + if (m_InPackage.volumeProfile != null || AssetDatabase.AssetPathExists(MigratedProfilePath("InReadOnlyPackage"))) + { + message = "A pipeline asset in a read-only package must not get a volume profile"; + return false; + } + + if (!m_InPackage.m_ShadowSettingsMigrationPending) + { + message = "A pipeline asset in a read-only package must stay pending"; + return false; + } + + return HasMigratedValues(m_InProject.volumeProfile, 80f, 2, new Vector3(0.25f, k_Cascade4Split.y, k_Cascade4Split.z), 0.15f, out message); + } + } + + static TestCaseData[] s_TestCaseDatas = + { + new TestCaseData(new NonDefaultAssetWithoutProfile()) + .SetName("When a pipeline asset with custom shadow settings has no volume profile, a profile with the Shadows override is created next to it"), + new TestCaseData(new DefaultAsset()) + .SetName("When a pipeline asset has default shadow settings, no volume profile is created"), + new TestCaseData(new SharedProfileWithDifferentValues()) + .SetName("When two pipeline assets share a volume profile with different shadow settings, each gets its own copy and the shared profile is unchanged"), + new TestCaseData(new SharedProfileWithDefaultAsset()) + .SetName("When a default pipeline asset shares its volume profile, the other pipeline asset gets a copy"), + new TestCaseData(new OverrideAlreadyAuthored()) + .SetName("When the volume profile already has a Shadows override, the migration leaves it untouched"), + new TestCaseData(new SplitSetOfCascadeCount()) + .SetName("When migrating, the cascade splits come from the split set of the cascade count"), + new TestCaseData(new DefaultProfileAsQualityProfile()) + .SetName("When a pipeline asset uses the default volume profile as its quality profile, it gets a copy and the default profile gets no Shadows override"), + new TestCaseData(new MigratingTwice()) + .SetName("When the migration runs twice, the second run changes nothing"), + new TestCaseData(new NotEditableProfile()) + .SetName("When the volume profile is not editable, the pipeline asset still migrates to a copy and the profile is unchanged"), + new TestCaseData(new NotEditableAsset()) + .SetName("When the pipeline asset is not editable, it stays pending and gets no volume profile"), + new TestCaseData(new ProfileOfOneAsset()) + .SetName("When a pipeline asset with custom shadow settings has its own volume profile, it gets a copy and the original profile is unchanged"), + new TestCaseData(new SharedProfileWithSameValues()) + .SetName("When pipeline assets share a volume profile and have the same shadow settings, they share one copy and the profile is unchanged"), + new TestCaseData(new SharedProfileWithMixedValues()) + .SetName("When pipeline assets share a volume profile, the ones with the same shadow settings share a copy, the others get their own and default ones keep the profile"), + new TestCaseData(new SameValuesWithoutProfile()) + .SetName("When pipeline assets without a volume profile have the same shadow settings, each gets its own new profile"), + new TestCaseData(new SameValuesWithDifferentProfiles()) + .SetName("When pipeline assets with the same shadow settings use different volume profiles, each gets a copy of its own profile"), + new TestCaseData(new NotEditableAssetWithSameValues()) + .SetName("When one of two pipeline assets with the same profile and shadow settings is not editable, the other gets its own copy and the locked one stays pending"), + new TestCaseData(new AssetInReadOnlyPackage()) + .SetName("When a pipeline asset with custom shadow settings is in a read-only package, it is skipped with a warning and other assets still migrate"), + }; + + [Test, TestCaseSource(nameof(s_TestCaseDatas))] + public void PerformMigration(IRenderPipelineGraphicsSettingsTestCase testCase) + { + base.DoTest(testCase); + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/URPGlobalSettingsMigrationTests/ShadowSettingsMigrationTest.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Editor/URPGlobalSettingsMigrationTests/ShadowSettingsMigrationTest.cs.meta new file mode 100644 index 00000000000..e1abf66e6d4 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/URPGlobalSettingsMigrationTests/ShadowSettingsMigrationTest.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: ad30d45101794c459fd4212a0489bbed diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/UniversalRenderPipelineAssetShadowmapDepthBitsTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/UniversalRenderPipelineAssetShadowmapDepthBitsTests.cs new file mode 100644 index 00000000000..e77329abaff --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/UniversalRenderPipelineAssetShadowmapDepthBitsTests.cs @@ -0,0 +1,47 @@ +using NUnit.Framework; +using UnityEngine; +using UnityEngine.Rendering; +using UnityEngine.Rendering.Universal; + +namespace UnityEditor.Rendering.Universal.Tests +{ + [TestFixture] + sealed class UniversalRenderPipelineAssetShadowmapDepthBitsTests + { + UniversalRenderPipelineAsset m_Asset; + + [SetUp] + public void SetUp() + { + m_Asset = ScriptableObject.CreateInstance(); + } + + [TearDown] + public void TearDown() + { + Object.DestroyImmediate(m_Asset); + } + + [Test] + [Description("A newly created asset renders both shadow maps with 16-bit depth.")] + public void GivenNewAsset_WhenCreated_ThenBothShadowmapsUse16BitDepth() + { + Assert.That(m_Asset.mainLightShadowmapDepthBits, Is.EqualTo(DepthBits.Depth16), "A new asset must default the main light shadow map to 16-bit depth."); + Assert.That(m_Asset.additionalLightsShadowmapDepthBits, Is.EqualTo(DepthBits.Depth16), "A new asset must default the additional lights shadow map atlas to 16-bit depth."); + } + + [Test] + [Description("An asset already at the last version keeps the precision it was saved with.")] + public void GivenAssetAtLastVersion_WhenDeserialized_ThenShadowmapDepthBitsAreUnchanged() + { + Assume.That(m_Asset.IsAtLastVersion(), Is.True, "A new asset must start at the last version."); + m_Asset.mainLightShadowmapDepthBits = DepthBits.Depth32; + m_Asset.additionalLightsShadowmapDepthBits = DepthBits.Depth32; + + m_Asset.OnAfterDeserialize(); + + Assert.That(m_Asset.mainLightShadowmapDepthBits, Is.EqualTo(DepthBits.Depth32), "Deserializing an asset at the last version must not change the main light shadow map precision."); + Assert.That(m_Asset.additionalLightsShadowmapDepthBits, Is.EqualTo(DepthBits.Depth32), "Deserializing an asset at the last version must not change the additional lights shadow map precision."); + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/UniversalRenderPipelineAssetShadowmapDepthBitsTests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Editor/UniversalRenderPipelineAssetShadowmapDepthBitsTests.cs.meta new file mode 100644 index 00000000000..30624ab1472 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/UniversalRenderPipelineAssetShadowmapDepthBitsTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 1558b3a309954f6aa0c1e88d8777eff7 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/ClusteringRecordingTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/ClusteringRecordingTests.cs new file mode 100644 index 00000000000..67bc680c425 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/ClusteringRecordingTests.cs @@ -0,0 +1,116 @@ +using System; +using System.Text.RegularExpressions; +using NUnit.Framework; +using UnityEngine.Rendering.RenderGraphModule; +using UnityEngine.TestTools; + +namespace UnityEngine.Rendering.Universal.Tests +{ + [TestFixture] + class ClusteringRecordingTests + { + RenderPipelineAsset m_PreviousQualityRenderPipelineAsset; + UniversalRenderPipelineAsset m_Asset; + UniversalRendererData m_RendererData; + ThrowingRendererFeature m_Feature; + RenderTexture m_Target; + Camera m_Camera; + GameObject m_Light; + + [SetUp] + public void SetUp() + { + m_PreviousQualityRenderPipelineAsset = QualitySettings.renderPipeline; + + m_Feature = ScriptableObject.CreateInstance(); + m_RendererData = ScriptableObject.CreateInstance(); + m_RendererData.renderingMode = RenderingMode.ForwardPlus; + m_RendererData.postProcessData = null; + m_RendererData.rendererFeatures.Add(m_Feature); + + m_Asset = ScriptableObject.CreateInstance(); + m_Asset.m_RendererDataList[0] = m_RendererData; + QualitySettings.renderPipeline = m_Asset; + + m_Target = new RenderTexture(64, 64, 24); + var gameObject = new GameObject("Clustering Recording Test Camera"); + m_Camera = gameObject.AddComponent(); + gameObject.AddComponent().SetRenderer(0); + m_Camera.enabled = false; + m_Camera.targetTexture = m_Target; + + m_Light = new GameObject("Clustering Recording Test Light"); + m_Light.AddComponent().type = LightType.Point; + } + + [TearDown] + public void TearDown() + { + Object.DestroyImmediate(m_Light); + m_Camera.targetTexture = null; + Object.DestroyImmediate(m_Camera.gameObject); + m_Target.Release(); + Object.DestroyImmediate(m_Target); + + QualitySettings.renderPipeline = m_PreviousQualityRenderPipelineAsset; + Object.DestroyImmediate(m_Asset); + Object.DestroyImmediate(m_RendererData); + Object.DestroyImmediate(m_Feature); + } + + [Description("A camera renders cleanly after a previous render graph recording was aborted after the clustering jobs were scheduled, and the aborted frame's job data does not outlive the frame.")] + [Test] + public void Clustering_RenderAfterAbortedRecording_DoesNotThrow() + { + m_Camera.Render(); + Assume.That(GraphicsSettings.currentRenderPipeline, Is.SameAs(m_Asset), "The test URP asset is not the active pipeline."); + LogAssert.NoUnexpectedReceived(); + + m_Feature.throwOnNextRecord = true; + LogAssert.Expect(LogType.Error, new Regex("Render Graph Execution error")); + LogAssert.Expect(LogType.Exception, new Regex(ThrowingRendererFeature.k_Message)); + m_Camera.Render(); + var forwardLights = ((UniversalRenderer)m_Asset.scriptableRenderer).forwardLights; + Assert.IsFalse(forwardLights.hasPendingClusteringData, "The aborted frame's clustering data outlived the frame."); + + m_Camera.Render(); + m_Camera.Render(); + LogAssert.NoUnexpectedReceived(); + } + + [HideInInspector] + class ThrowingRendererFeature : ScriptableRendererFeature + { + internal const string k_Message = "Recording aborted by the test"; + + internal bool throwOnNextRecord; + ThrowingPass m_Pass; + + public override void Create() + { + m_Pass = new ThrowingPass(this) { renderPassEvent = RenderPassEvent.BeforeRenderingShadows }; + } + + public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData renderingData) + { + renderer.EnqueuePass(m_Pass); + } + + class ThrowingPass : ScriptableRenderPass + { + readonly ThrowingRendererFeature m_Feature; + + public ThrowingPass(ThrowingRendererFeature feature) => m_Feature = feature; + + public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) + { + if (!m_Feature.throwOnNextRecord) + return; + + m_Feature.throwOnNextRecord = false; + throw new InvalidOperationException(k_Message); + } + } + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/ClusteringRecordingTests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/ClusteringRecordingTests.cs.meta new file mode 100644 index 00000000000..ca9854b03d1 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/ClusteringRecordingTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 7f2223098edf94097ad704659d37e343 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/DecalTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/DecalTests.cs index 7229ef933f1..8ebe7c40813 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/DecalTests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/DecalTests.cs @@ -1,4 +1,7 @@ +using System.Collections; +using System.Collections.Generic; using NUnit.Framework; +using UnityEngine.TestTools; namespace UnityEngine.Rendering.Universal.Tests { @@ -51,4 +54,109 @@ public void DecalDestroyEmptyChunk() Assert.AreEqual(1, m_EntityManager.chunkCount); } } + + // The DBuffer technique requires a prepass, which URP skips when the camera can't see any prepass layer. + class DecalDBufferSkippedPrepassTests + { + static readonly RenderingMode[] k_RenderingModes = { RenderingMode.Forward, RenderingMode.Deferred }; + + RenderPipelineAsset m_PreviousRenderPipelineAsset; + UniversalRenderPipelineAsset m_Asset; + readonly List m_Objects = new(); + Camera m_Camera; + UniversalAdditionalCameraData m_CameraData; + RenderTexture m_Destination; + + [UnityOneTimeSetUp] + public IEnumerator OneTimeSetUp() + { + m_PreviousRenderPipelineAsset = QualitySettings.renderPipeline; + + if (GraphicsSettings.currentRenderPipeline is not UniversalRenderPipelineAsset) + Assert.Ignore("These tests only run when URP is the active render pipeline."); + if (DecalRendererFeature.isGLDevice) + Assert.Ignore("The DBuffer technique is not supported with OpenGL."); + + // One renderer per rendering mode and decal layers setting, so the tests only need a single pipeline switch + var rendererDataList = new ScriptableRendererData[k_RenderingModes.Length * 2]; + for (int i = 0; i < rendererDataList.Length; ++i) + { + var decalFeature = ScriptableObject.CreateInstance(); + decalFeature.settings.technique = DecalTechniqueOption.DBuffer; + decalFeature.settings.dBufferSettings = new DBufferSettings(); + decalFeature.settings.decalLayers = i % 2 == 1; + m_Objects.Add(decalFeature); + + var rendererData = ScriptableObject.CreateInstance(); + rendererData.renderingMode = k_RenderingModes[i / 2]; + rendererData.rendererFeatures.Add(decalFeature); + m_Objects.Add(rendererData); + rendererDataList[i] = rendererData; + } + + m_Asset = ScriptableObject.CreateInstance(); + m_Asset.m_RendererDataList = rendererDataList; + m_Objects.Add(m_Asset); + QualitySettings.renderPipeline = m_Asset; + + var cameraGameObject = new GameObject("DBuffer Skipped Prepass Camera"); + m_Objects.Add(cameraGameObject); + m_Camera = cameraGameObject.AddComponent(); + m_Camera.enabled = false; + m_Camera.cullingMask = 0; + m_CameraData = cameraGameObject.AddComponent(); + + m_Destination = new RenderTexture(64, 64, 24); + m_Objects.Add(m_Destination); + + // Let the pipeline switch to the test asset + yield return null; + } + + [OneTimeTearDown] + public void OneTimeTearDown() + { + QualitySettings.renderPipeline = m_PreviousRenderPipelineAsset; + + foreach (var obj in m_Objects) + { + if (obj != null) + Object.DestroyImmediate(obj); + } + m_Objects.Clear(); + } + + static IEnumerable RenderCases() + { + foreach (var renderingMode in k_RenderingModes) + { + foreach (var depthPrimingMode in new[] { DepthPrimingMode.Disabled, DepthPrimingMode.Forced }) + { + foreach (bool decalLayers in new[] { false, true }) + { + string layers = decalLayers ? "Yes" : "No"; + yield return new TestCaseData(renderingMode, depthPrimingMode, decalLayers) + .SetName($"RenderWithEmptyCullingMask_DoesNotLogErrors({renderingMode}, DepthPriming:{depthPrimingMode}, DecalLayers:{layers})") + .Returns(null); + } + } + } + } + + [UnityTest, TestCaseSource(nameof(RenderCases))] + public IEnumerator RenderWithEmptyCullingMask_DoesNotLogErrors(RenderingMode renderingMode, DepthPrimingMode depthPrimingMode, bool decalLayers) + { + int rendererIndex = System.Array.IndexOf(k_RenderingModes, renderingMode) * 2 + (decalLayers ? 1 : 0); + ((UniversalRenderer)m_Asset.GetRenderer(rendererIndex)).depthPrimingMode = depthPrimingMode; + m_CameraData.SetRenderer(rendererIndex); + + RenderPipeline.SubmitRenderRequest(m_Camera, new RenderPipeline.StandardRequest { destination = m_Destination }); + + // Validation errors are logged from the render thread, so give it time to process the frame + yield return null; + yield return null; + + LogAssert.NoUnexpectedReceived(); + } + } } diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/LayerShadowCullDistanceTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/LayerShadowCullDistanceTests.cs new file mode 100644 index 00000000000..fb1862d6f15 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/LayerShadowCullDistanceTests.cs @@ -0,0 +1,155 @@ +using System.Collections; +using System.Collections.Generic; +using NUnit.Framework; +using UnityEngine.Rendering.RenderGraphModule; +using UnityEngine.TestTools; + +namespace UnityEngine.Rendering.Universal.Tests +{ + class LayerShadowCullDistanceTests + { + class ShadowCasterBoundsFeature : ScriptableRendererFeature + { + internal readonly ShadowCasterBoundsPass boundsPass = new ShadowCasterBoundsPass(); + + public override void Create() + { + } + + public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData renderingData) + { + renderer.EnqueuePass(boundsPass); + } + } + + class ShadowCasterBoundsPass : ScriptableRenderPass + { + internal bool hasCasters; + internal Bounds casterBounds; + + public ShadowCasterBoundsPass() + { + renderPassEvent = RenderPassEvent.AfterRenderingOpaques; + } + + public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) + { + var renderingData = frameData.Get(); + int mainLightIndex = frameData.Get().mainLightIndex; + hasCasters = mainLightIndex >= 0 && + renderingData.cullResults.GetShadowCasterBounds(mainLightIndex, out casterBounds); + } + } + + const int k_LayerCount = 32; + const int k_NearLayer = 29; + const int k_FarLayer = 30; + const float k_ShadowDistance = 50f; + const float k_FarLayerShadowCullDistance = 100f; + const float k_SunElevation = 8f; + const float k_FarCasterDistanceBehindCamera = 150f; + static readonly Vector3 k_NearCasterPosition = new Vector3(0f, 0f, 10f); + + RenderPipelineAsset m_PreviousRenderPipelineAsset; + Light m_PreviousSun; + ShadowCasterBoundsFeature m_Feature; + readonly List m_Objects = new(); + Camera m_Camera; + RenderTexture m_Destination; + + [UnityOneTimeSetUp] + public IEnumerator OneTimeSetUp() + { + m_PreviousRenderPipelineAsset = QualitySettings.renderPipeline; + m_PreviousSun = RenderSettings.sun; + + if (GraphicsSettings.currentRenderPipeline is not UniversalRenderPipelineAsset) + Assert.Ignore("These tests only run when URP is the active render pipeline."); + + m_Feature = ScriptableObject.CreateInstance(); + m_Objects.Add(m_Feature); + + var rendererData = ScriptableObject.CreateInstance(); + rendererData.rendererFeatures.Add(m_Feature); + m_Objects.Add(rendererData); + + var asset = ScriptableObject.CreateInstance(); + asset.m_RendererDataList = new ScriptableRendererData[] { rendererData }; + var volumeProfile = ScriptableObject.CreateInstance(); + var shadowsVolume = volumeProfile.Add(overrides: true); + shadowsVolume.maxShadowDistance.value = k_ShadowDistance; + m_Objects.Add(shadowsVolume); + m_Objects.Add(volumeProfile); + asset.volumeProfile = volumeProfile; + m_Objects.Add(asset); + QualitySettings.renderPipeline = asset; + + var cameraGameObject = new GameObject("Layer Shadow Cull Camera"); + m_Objects.Add(cameraGameObject); + m_Camera = cameraGameObject.AddComponent(); + m_Camera.enabled = false; + m_Camera.cullingMask = (1 << k_NearLayer) | (1 << k_FarLayer); + cameraGameObject.AddComponent(); + + var lightGameObject = new GameObject("Low Sun Behind Camera"); + m_Objects.Add(lightGameObject); + lightGameObject.transform.rotation = Quaternion.Euler(k_SunElevation, 0f, 0f); + var sun = lightGameObject.AddComponent(); + sun.type = LightType.Directional; + sun.shadows = LightShadows.Hard; + var shadowCullDistances = new float[k_LayerCount]; + shadowCullDistances[k_FarLayer] = k_FarLayerShadowCullDistance; + sun.layerShadowCullDistances = shadowCullDistances; + RenderSettings.sun = sun; + + CreateCaster(k_NearCasterPosition, k_NearLayer); + CreateCaster(k_NearCasterPosition - lightGameObject.transform.forward * k_FarCasterDistanceBehindCamera, k_FarLayer); + + m_Destination = new RenderTexture(64, 64, 24); + m_Objects.Add(m_Destination); + + yield return null; + } + + [OneTimeTearDown] + public void OneTimeTearDown() + { + QualitySettings.renderPipeline = m_PreviousRenderPipelineAsset; + RenderSettings.sun = m_PreviousSun; + + foreach (var obj in m_Objects) + { + Object.DestroyImmediate(obj); + } + m_Objects.Clear(); + } + + void CreateCaster(Vector3 position, int layer) + { + var caster = GameObject.CreatePrimitive(PrimitiveType.Cube); + m_Objects.Add(caster); + caster.layer = layer; + caster.transform.position = position; + } + + float RenderAndCaptureShadowCasterBoundsMinZ() + { + var boundsPass = m_Feature.boundsPass; + boundsPass.hasCasters = false; + RenderPipeline.SubmitRenderRequest(m_Camera, new RenderPipeline.StandardRequest { destination = m_Destination }); + + Assert.IsTrue(boundsPass.hasCasters, "The main light has no shadow casters"); + return boundsPass.casterBounds.min.z; + } + + [Test] + public void LayerShadowCullDistance_WithPlanarLayerCulling_KeepsCastersBehindCamera() + { + m_Camera.layerCullSpherical = false; + + float casterBoundsMinZ = RenderAndCaptureShadowCasterBoundsMinZ(); + + Assert.IsTrue(casterBoundsMinZ < -k_FarLayerShadowCullDistance, $"Shadow caster bounds start at z = {casterBoundsMinZ}"); + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/LayerShadowCullDistanceTests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/LayerShadowCullDistanceTests.cs.meta new file mode 100644 index 00000000000..52dec54f24d --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/LayerShadowCullDistanceTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 3cb51aa51203f4eb0af2523d873ed92c \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/LightAndProbeTransitionTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/LightAndProbeTransitionTests.cs new file mode 100644 index 00000000000..62882411a97 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/LightAndProbeTransitionTests.cs @@ -0,0 +1,461 @@ +using System.Collections; +using System.Collections.Generic; +using System.Text.RegularExpressions; +using NUnit.Framework; +using UnityEngine.Experimental.Rendering; +using UnityEngine.TestTools; + +namespace UnityEngine.Rendering.Universal.Tests +{ + // URP creates the additional lights constant buffer for the first camera that has an additional light, and + // skips the reflection probe upload for the cameras that see no probe. These tests render a camera that starts + // without an additional light or a probe, then gets one, loses it and gets it back, and check each frame: the + // frame where the light or probe appears is shaded by it, and the frame after it is gone is shaded as before, + // although the buffer still holds its data. + [TestFixture] + class LightAndProbeTransitionTests + { + // Layer of the test objects, which only the test camera renders. + const int k_Layer = 30; + const int k_TargetSize = 64; + // In 8-bit color: the least a quad must change when the light or probe appears, and the most two frames + // that should match may differ. + const float k_MinChange = 0.25f; + const float k_MaxDifference = 0.02f; + + // Away from the objects of the scene the tests run in. + static readonly Vector3 k_Origin = new Vector3(0f, 0f, 1000f); + + // The error a player logs when it lacks a shader variant, with strict variant matching. + static readonly Regex k_MissingVariant = new Regex(@"\bvariant\b.*\bnot found\b"); + + RenderPipelineAsset m_PreviousQualityRenderPipelineAsset; +#if UNITY_EDITOR + bool m_PreviousAllowAsyncCompilation; +#endif + readonly List m_DisabledLights = new(); + readonly List m_DisabledCameras = new(); + readonly HashSet m_ProjectRenderingModes = new(); + bool m_ProjectUsesReflectionProbeBlending; + + UniversalRenderPipelineAsset m_Asset; + UniversalRendererData m_RendererData; + + readonly List m_TestObjects = new(); + Camera m_Camera; + RenderTexture m_Target; + Texture2D m_Readback; + Material m_OpaqueMaterial; + Material m_TransparentMaterial; + Renderer m_OpaqueQuad; + Renderer m_TransparentQuad; + Light m_Light; + ReflectionProbe m_Probe; + // Color at the center of the opaque and the transparent quad in the last frame that Render read back. + (Color opaque, Color transparent) m_Frame; + readonly List m_LoggedErrors = new(); + + [OneTimeSetUp] + public void OneTimeSetUp() + { + // Captured before any Assert.Ignore: OneTimeTearDown runs even when OneTimeSetUp ignores. + m_PreviousQualityRenderPipelineAsset = QualitySettings.renderPipeline; +#if UNITY_EDITOR + m_PreviousAllowAsyncCompilation = UnityEditor.ShaderUtil.allowAsyncCompilation; +#endif + + if (GraphicsSettings.currentRenderPipeline is not UniversalRenderPipelineAsset) + Assert.Ignore("These tests only run when URP is the active render pipeline."); + + // A player only has the shader variants of the rendering modes and features its URP assets use. + AddProjectAsset(GraphicsSettings.defaultRenderPipeline); + for (int i = 0; i < QualitySettings.count; i++) + AddProjectAsset(QualitySettings.GetRenderPipelineAssetAt(i)); + +#if UNITY_EDITOR + // Otherwise the editor draws the first frames with a placeholder shader while it compiles the variants. + UnityEditor.ShaderUtil.allowAsyncCompilation = false; +#endif + + // The tests compare frames with and without one light, so no other light may shade the test objects. + foreach (var light in Object.FindObjectsByType(FindObjectsInactive.Exclude)) + { + if (!light.enabled) + continue; + light.enabled = false; + m_DisabledLights.Add(light); + } + + // The tests let frames pass, during which no other camera may render the renderer under test. + foreach (var camera in Object.FindObjectsByType(FindObjectsInactive.Exclude)) + { + if (!camera.enabled) + continue; + camera.enabled = false; + m_DisabledCameras.Add(camera); + } + + m_RendererData = ScriptableObject.CreateInstance(); + m_Asset = ScriptableObject.CreateInstance(); + m_Asset.m_RendererDataList[0] = m_RendererData; + QualitySettings.renderPipeline = m_Asset; + } + + void AddProjectAsset(RenderPipelineAsset asset) + { + if (asset is not UniversalRenderPipelineAsset universalAsset) + return; + + m_ProjectUsesReflectionProbeBlending |= universalAsset.ShouldUseReflectionProbeBlending(); + foreach (var rendererData in universalAsset.rendererDataList) + { + if (rendererData is UniversalRendererData universalRendererData) + m_ProjectRenderingModes.Add(universalRendererData.renderingMode); + } + } + + [OneTimeTearDown] + public void OneTimeTearDown() + { + QualitySettings.renderPipeline = m_PreviousQualityRenderPipelineAsset; +#if UNITY_EDITOR + UnityEditor.ShaderUtil.allowAsyncCompilation = m_PreviousAllowAsyncCompilation; +#endif + + foreach (var light in m_DisabledLights) + { + if (light != null) + light.enabled = true; + } + m_DisabledLights.Clear(); + + foreach (var camera in m_DisabledCameras) + { + if (camera != null) + camera.enabled = true; + } + m_DisabledCameras.Clear(); + + if (m_Asset != null) + Object.DestroyImmediate(m_Asset); + if (m_RendererData != null) + Object.DestroyImmediate(m_RendererData); + } + + [SetUp] + public void SetUp() + { + var shader = Shader.Find(ShaderUtils.GetShaderPath(ShaderPathID.Lit)); + if (shader == null) + Assert.Ignore("The Lit shader is not in this build."); + + m_Target = new RenderTexture(k_TargetSize, k_TargetSize, GraphicsFormat.R8G8B8A8_UNorm, CoreUtils.GetDefaultDepthOnlyFormat()); + m_Target.Create(); + m_Readback = new Texture2D(k_TargetSize, k_TargetSize, TextureFormat.RGBA32, false, true); + m_TestObjects.Add(m_Readback); + + var cameraObject = CreateObject("Camera", Vector3.zero); + m_Camera = cameraObject.AddComponent(); + m_Camera.enabled = false; // Rendered only by the render requests of the tests. + m_Camera.cullingMask = 1 << k_Layer; + m_Camera.clearFlags = CameraClearFlags.SolidColor; + m_Camera.backgroundColor = Color.black; + m_Camera.aspect = 1f; + m_Camera.fieldOfView = 60f; + m_Camera.nearClipPlane = 0.1f; + m_Camera.farClipPlane = 10f; + m_Camera.allowHDR = false; + m_Camera.allowMSAA = false; + var cameraData = cameraObject.AddComponent(); + cameraData.SetRenderer(0); + cameraData.renderPostProcessing = false; + cameraData.renderShadows = false; + + // A transparent object goes through the forward path in every rendering mode, and so reads the constant + // buffers also with Deferred, where the opaque objects are lit by the deferred lights. + var quad = CreateQuadMesh(); + m_OpaqueMaterial = CreateMaterial(shader, transparent: false); + m_TransparentMaterial = CreateMaterial(shader, transparent: true); + m_OpaqueQuad = CreateQuad("Opaque Quad", new Vector3(-0.85f, 0f, 3f), quad, m_OpaqueMaterial); + m_TransparentQuad = CreateQuad("Transparent Quad", new Vector3(0.85f, 0f, 3f), quad, m_TransparentMaterial); + + // Between the camera and the quads, which it lights from the front. + m_Light = CreateObject("Point Light", new Vector3(0f, 0f, 2f)).AddComponent(); + m_Light.type = LightType.Point; + m_Light.color = Color.red; + m_Light.intensity = 4f; + m_Light.range = 5f; + m_Light.shadows = LightShadows.None; + m_Light.enabled = false; + + // Its box holds both quads. + m_Probe = CreateObject("Reflection Probe", new Vector3(0f, 0f, 3f)).AddComponent(); + m_Probe.mode = ReflectionProbeMode.Custom; + m_Probe.customBakedTexture = CreateRedCubemap(); + m_Probe.size = new Vector3(6f, 6f, 6f); + m_Probe.boxProjection = false; + m_Probe.enabled = false; + + m_LoggedErrors.Clear(); + Application.logMessageReceivedThreaded += OnLogMessageReceived; + } + + [TearDown] + public void TearDown() + { + Application.logMessageReceivedThreaded -= OnLogMessageReceived; + LogAssert.ignoreFailingMessages = false; + + if (m_Asset != null) + m_Asset.reflectionProbeBlending = false; + + foreach (var obj in m_TestObjects) + { + if (obj != null) + Object.DestroyImmediate(obj); + } + m_TestObjects.Clear(); + + if (m_Target != null) + { + m_Target.Release(); + Object.DestroyImmediate(m_Target); + m_Target = null; + } + } + + [UnityTest] + public IEnumerator AdditionalLightAppearsAndDisappears_EachFrameIsShadedByTheLightsItHas( + [Values(RenderingMode.Forward, RenderingMode.ForwardPlus, RenderingMode.Deferred, RenderingMode.DeferredPlus)] RenderingMode renderingMode) + { + UseRenderingMode(renderingMode); + + // Two frames without additional lights, so the new renderer has no additional lights buffer yet. + yield return Render(); + yield return Render(); + var unlit = m_Frame; + + // With persistent constant buffers, this frame creates the buffer. A light is culled from the frame it is + // enabled in, so the render request follows it without letting a frame pass. + m_Light.enabled = true; + yield return Render(); + AssertChanged(unlit, m_Frame, "the first frame with the additional light"); + + // The buffer stays bound and still holds the light, which the shaders must not read anymore. + m_Light.enabled = false; + yield return Render(); + AssertUnchanged(unlit, m_Frame, "the first frame after the additional light is gone"); + + m_Light.enabled = true; + yield return Render(); + AssertChanged(unlit, m_Frame, "the frame where the additional light comes back"); + } + + [UnityTest] + public IEnumerator ReflectionProbeAppearsAndDisappears_EachFrameReflectsTheProbesItHas( + [Values(RenderingMode.ForwardPlus, RenderingMode.DeferredPlus)] RenderingMode renderingMode) + { + if (!Application.isEditor && !m_ProjectUsesReflectionProbeBlending) + Assert.Ignore("No URP asset of this project blends reflection probes, so the shader variants of the reflection probe atlas are not in the build."); + + // These rendering modes use the reflection probe atlas, and its constant buffer, with probe blending. + m_Asset.reflectionProbeBlending = true; + UseRenderingMode(renderingMode); + + // Mirrors, which show only the reflection. + foreach (var material in new[] { m_OpaqueMaterial, m_TransparentMaterial }) + { + material.SetFloat("_Metallic", 1f); + material.SetFloat("_Smoothness", 1f); + } + + // With persistent constant buffers, the first frame creates the buffer and uploads it empty, and the + // second one skips the upload. + yield return Render(); + yield return Render(); + var unreflected = m_Frame; + + // The engine adds an enabled probe to its culling data, and removes a disabled one, at its next frame update. + m_Probe.enabled = true; + yield return null; + yield return Render(); + AssertChanged(unreflected, m_Frame, "the first frame with the reflection probe"); + + // This frame skips the upload: the buffer still holds the probe, which the shaders must not read anymore. + m_Probe.enabled = false; + yield return null; + yield return Render(); + AssertUnchanged(unreflected, m_Frame, "the first frame after the reflection probe is gone"); + + m_Probe.enabled = true; + yield return null; + yield return Render(); + AssertChanged(unreflected, m_Frame, "the frame where the reflection probe comes back"); + } + + void UseRenderingMode(RenderingMode renderingMode) + { + if (!Application.isEditor && !m_ProjectRenderingModes.Contains(renderingMode)) + Assert.Ignore($"No URP asset of this project uses {renderingMode}, so its shader variants are not in the build."); + + // Setting the mode invalidates the renderer data, so the next frame creates a new renderer, without buffers. + m_RendererData.renderingMode = renderingMode; + } + + // Renders one frame of the test camera, and reads the color at the center of the quads back into m_Frame. + IEnumerator Render() + { + // The errors are checked below, to tell a shader variant missing from the build apart. + LogAssert.ignoreFailingMessages = true; + RenderPipeline.SubmitRenderRequest(m_Camera, new RenderPipeline.StandardRequest { destination = m_Target }); + + // ReadPixels needs a synchronous readback, which WebGPU has only in browsers with JSPI. + if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.WebGPU) + { + var request = AsyncGPUReadback.Request(m_Target, 0, TextureFormat.RGBA32); + while (!request.done) + yield return null; + Assert.IsFalse(request.hasError, "The readback of the frame failed."); + m_Readback.SetPixelData(request.GetData(), 0); + } + else + { + var previous = RenderTexture.active; + RenderTexture.active = m_Target; + m_Readback.ReadPixels(new Rect(0, 0, k_TargetSize, k_TargetSize), 0, 0, false); + RenderTexture.active = previous; + } + + m_Frame = (ReadCenterColor(m_OpaqueQuad), ReadCenterColor(m_TransparentQuad)); + + // A player only has the shader variants its URP assets use, and draws a frame that needs another one wrong: + // the test can't judge that frame. Any other error fails the test, as it would without this check. + string[] errors; + lock (m_LoggedErrors) + errors = m_LoggedErrors.ToArray(); + foreach (var error in errors) + { + if (k_MissingVariant.IsMatch(error)) + Assert.Ignore($"This build lacks a shader variant the test needs: {error}"); + } + if (errors.Length > 0) + Assert.Fail($"Errors were logged: {string.Join(" | ", errors)}"); + } + + void OnLogMessageReceived(string message, string stackTrace, LogType type) + { + if (type is LogType.Error or LogType.Assert or LogType.Exception) + { + lock (m_LoggedErrors) + m_LoggedErrors.Add(message); + } + } + + // Mean color of the 3x3 pixels at the center of the quad. + Color ReadCenterColor(Renderer quad) + { + var center = m_Camera.WorldToViewportPoint(quad.transform.position); + int x = Mathf.FloorToInt(center.x * k_TargetSize); + int y = Mathf.FloorToInt(center.y * k_TargetSize); + var sum = Color.clear; + for (int dy = -1; dy <= 1; dy++) + { + for (int dx = -1; dx <= 1; dx++) + sum += m_Readback.GetPixel(x + dx, y + dy); + } + return sum / 9f; + } + + // The light and the probe are red, so the quads they shade get redder, whatever else lights the scene. + static float Redness(Color color) => color.r - 0.5f * (color.g + color.b); + + static float MaxDifference(Color a, Color b) => Mathf.Max(Mathf.Abs(a.r - b.r), Mathf.Max(Mathf.Abs(a.g - b.g), Mathf.Abs(a.b - b.b))); + + static void AssertChanged((Color opaque, Color transparent) before, (Color opaque, Color transparent) frame, string frameName) + { + Assert.That(Redness(frame.opaque) - Redness(before.opaque), Is.GreaterThan(k_MinChange), + $"The opaque quad isn't shaded in {frameName}: {frame.opaque}, against {before.opaque} before."); + Assert.That(Redness(frame.transparent) - Redness(before.transparent), Is.GreaterThan(k_MinChange), + $"The transparent quad isn't shaded in {frameName}: {frame.transparent}, against {before.transparent} before."); + } + + static void AssertUnchanged((Color opaque, Color transparent) before, (Color opaque, Color transparent) frame, string frameName) + { + Assert.That(MaxDifference(frame.opaque, before.opaque), Is.LessThan(k_MaxDifference), + $"The opaque quad is still shaded in {frameName}: {frame.opaque}, against {before.opaque} before."); + Assert.That(MaxDifference(frame.transparent, before.transparent), Is.LessThan(k_MaxDifference), + $"The transparent quad is still shaded in {frameName}: {frame.transparent}, against {before.transparent} before."); + } + + GameObject CreateObject(string name, Vector3 position) + { + var gameObject = new GameObject($"{nameof(LightAndProbeTransitionTests)} {name}") { layer = k_Layer }; + gameObject.transform.position = k_Origin + position; + m_TestObjects.Add(gameObject); + return gameObject; + } + + Renderer CreateQuad(string name, Vector3 position, Mesh mesh, Material material) + { + var gameObject = CreateObject(name, position); + gameObject.AddComponent().sharedMesh = mesh; + var renderer = gameObject.AddComponent(); + renderer.sharedMaterial = material; + renderer.shadowCastingMode = ShadowCastingMode.Off; + return renderer; + } + + // A 1x1 quad facing the camera. Built here rather than with CreatePrimitive, which also adds a collider. + Mesh CreateQuadMesh() + { + var mesh = new Mesh { name = "Transition Test Quad" }; + mesh.vertices = new[] { new Vector3(-0.5f, -0.5f, 0f), new Vector3(0.5f, -0.5f, 0f), new Vector3(-0.5f, 0.5f, 0f), new Vector3(0.5f, 0.5f, 0f) }; + mesh.normals = new[] { Vector3.back, Vector3.back, Vector3.back, Vector3.back }; + mesh.uv = new[] { new Vector2(0f, 0f), new Vector2(1f, 0f), new Vector2(0f, 1f), new Vector2(1f, 1f) }; + mesh.triangles = new[] { 0, 3, 1, 3, 0, 2 }; + mesh.RecalculateTangents(); + m_TestObjects.Add(mesh); + return mesh; + } + + // White and rough, so the quads take the color of the light. Both faces are drawn, so the winding of the quad + // doesn't matter. + Material CreateMaterial(Shader shader, bool transparent) + { + var material = new Material(shader) { name = transparent ? "Transition Test Transparent" : "Transition Test Opaque" }; + material.SetColor("_BaseColor", Color.white); + material.SetFloat("_Smoothness", 0f); + material.SetFloat("_Cull", (float)CullMode.Off); + if (transparent) + { + // What the material inspector sets for an alpha blended surface. Alpha 1 keeps the lit color as is. + material.SetFloat("_Surface", 1f); + material.SetFloat("_Blend", 0f); + material.SetFloat("_SrcBlend", (float)BlendMode.SrcAlpha); + material.SetFloat("_DstBlend", (float)BlendMode.OneMinusSrcAlpha); + material.SetFloat("_SrcBlendAlpha", (float)BlendMode.One); + material.SetFloat("_DstBlendAlpha", (float)BlendMode.OneMinusSrcAlpha); + material.SetFloat("_ZWrite", 0f); + material.SetOverrideTag("RenderType", "Transparent"); + material.EnableKeyword("_SURFACE_TYPE_TRANSPARENT"); + material.renderQueue = (int)RenderQueue.Transparent; + } + m_TestObjects.Add(material); + return material; + } + + Cubemap CreateRedCubemap() + { + const int size = 16; + var cubemap = new Cubemap(size, TextureFormat.RGBA32, true) { name = "Transition Test Red Reflection" }; + var pixels = new Color[size * size]; + for (int i = 0; i < pixels.Length; i++) + pixels[i] = Color.red; + for (int face = 0; face < 6; face++) + cubemap.SetPixels(pixels, (CubemapFace)face); + cubemap.Apply(true, true); + m_TestObjects.Add(cubemap); + return cubemap; + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/LightAndProbeTransitionTests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/LightAndProbeTransitionTests.cs.meta new file mode 100644 index 00000000000..a292a8f6a11 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/LightAndProbeTransitionTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b19228bf0ae941f5986fb2d7e64e98e4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/LightClusteringOracle.cs b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/LightClusteringOracle.cs new file mode 100644 index 00000000000..f1707f7e80a --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/LightClusteringOracle.cs @@ -0,0 +1,756 @@ +using System; +using System.Collections.Generic; +using Unity.Collections; +using Unity.Jobs; +using Unity.Mathematics; +using UnityEngine.Rendering.Universal.Internal; + +namespace UnityEngine.Rendering.Universal.Tests +{ + enum ClusteringItemKind + { + Point, + Spot, + Probe, + } + + /// + /// A light or reflection probe in world space, as the clustering jobs receive it. + /// + struct ClusteringItem + { + public ClusteringItemKind kind; + public float3 position; + public float3 direction; + public float range; + public float spotAngle; + public float3 extents; + public quaternion rotation; + + public static ClusteringItem Point(float3 position, float range) => + new ClusteringItem { kind = ClusteringItemKind.Point, position = position, direction = new float3(0, 0, 1), range = range, spotAngle = 30f, rotation = quaternion.identity }; + + public static ClusteringItem Spot(float3 position, float3 direction, float range, float spotAngle) => + new ClusteringItem { kind = ClusteringItemKind.Spot, position = position, direction = direction, range = range, spotAngle = spotAngle, rotation = quaternion.identity }; + + public static ClusteringItem Probe(float3 center, float3 extents, quaternion rotation) => + new ClusteringItem { kind = ClusteringItemKind.Probe, position = center, direction = new float3(0, 0, 1), extents = extents, rotation = rotation }; + + public override string ToString() => kind == ClusteringItemKind.Probe + ? $"Probe(center=({position.x:R},{position.y:R},{position.z:R}) extents=({extents.x:R},{extents.y:R},{extents.z:R}) rotation=({rotation.value.x:R},{rotation.value.y:R},{rotation.value.z:R},{rotation.value.w:R}))" + : $"{kind}(position=({position.x:R},{position.y:R},{position.z:R}) direction=({direction.x:R},{direction.y:R},{direction.z:R}) range={range:R} spotAngle={spotAngle:R})"; + } + + /// + /// One view, or two for XR, and the items to cluster. + /// + class ClusteringScene + { + public bool orthographic; + public int viewCount = 1; + public float4x4[] worldToViews = { float4x4.identity, float4x4.identity }; + public float4x4[] viewToClips = new float4x4[2]; + public float near; + public float far; + public int2 screenSize; + public List items = new List(); + + public static float4x4 Perspective(float p00, float p11, float2 lensShift, float near, float far) => new float4x4( + new float4(p00, 0, 0, 0), + new float4(0, p11, 0, 0), + new float4(lensShift.x, lensShift.y, -(far + near) / (far - near), -1), + new float4(0, 0, -(2f * far * near) / (far - near), 0)); + + public static float4x4 Orthographic(float halfWidth, float halfHeight, float2 lensShift, float near, float far) + { + var m = float4x4.identity; + m.c0.x = 1f / halfWidth; + m.c1.y = 1f / halfHeight; + m.c2.z = -2f / (far - near); + m.c3 = new float4(lensShift.x, lensShift.y, -(far + near) / (far - near), 1); + return m; + } + + /// + /// A perspective scene with an identity world-to-view matrix and one item given in view space with +z forward. + /// + public static ClusteringScene PerspectiveViewSpace(float p00, float p11, float2 lensShift, float near, float far, int2 screenSize, ClusteringItem itemVS) + { + var scene = new ClusteringScene { near = near, far = far, screenSize = screenSize }; + scene.viewToClips[0] = scene.viewToClips[1] = Perspective(p00, p11, lensShift, near, far); + scene.items.Add(FlipZ(itemVS)); + return scene; + } + + public static ClusteringScene PerspectiveViewSpace(float fovYDeg, float aspect, float near, float far, int2 screenSize, ClusteringItem itemVS) + { + var p11 = 1f / math.tan(math.radians(fovYDeg) * 0.5f); + return PerspectiveViewSpace(p11 / aspect, p11, float2.zero, near, far, screenSize, itemVS); + } + + /// + /// An orthographic scene with an identity world-to-view matrix and one item given in view space with +z forward. + /// + public static ClusteringScene OrthographicViewSpace(float halfWidth, float halfHeight, float near, float far, int2 screenSize, ClusteringItem itemVS) + { + var scene = new ClusteringScene { orthographic = true, near = near, far = far, screenSize = screenSize }; + scene.viewToClips[0] = scene.viewToClips[1] = Orthographic(halfWidth, halfHeight, float2.zero, near, far); + scene.items.Add(FlipZ(itemVS)); + return scene; + } + + static ClusteringItem FlipZ(ClusteringItem item) + { + item.position.z = -item.position.z; + item.direction.z = -item.direction.z; + item.rotation = new quaternion(-item.rotation.value.x, -item.rotation.value.y, item.rotation.value.z, item.rotation.value.w); + return item; + } + + public override string ToString() + { + var s = $"orthographic={orthographic} views={viewCount} near={near:R} far={far:R} screen={screenSize}\n"; + for (var v = 0; v < viewCount; v++) + s += $" view {v}: worldToView={worldToViews[v]} viewToClip={viewToClips[v]}\n"; + foreach (var item in items) + s += $" {item}\n"; + return s; + } + } + + /// + /// Reference for the light clustering jobs. Runs ForwardLights.ScheduleClusteringJobs on a scene and compares its tile + /// masks and z-bins with ray casts against the exact light and probe volumes. + /// + /// Each item is converted to view space in double precision from the same float inputs the jobs receive, so the + /// reference is the exact geometry of those inputs and any float error in the jobs counts against the jobs. The + /// volumes are the ones the jobs cover: a sphere for a point light, a cone of half the spot angle intersected with the + /// range sphere for a spot light, and a box for a reflection probe, all limited to depths between the near and far + /// planes. + /// + /// Two kinds of errors are reported: + /// - Missing: the GPU looks up lights per pixel center, so an item must be in every tile that contains a pixel center + /// whose view ray hits its volume, and in every z-bin between the depths where that ray enters and leaves it. + /// This check is exact up to double precision. + /// - Outside: over-coverage is allowed but costs performance, so this check only reports an item in a tile or z-bin + /// it clearly does not reach. It errs towards passing: a tile counts as reached when the volume comes within + /// k_TouchMargin pixels of the tile rectangle, which accepts slivers and contact along a tile edge, and a z-bin + /// counts as reached when it is at most one bin away from the depth extent of the volume. + /// + /// The layout of the outputs is checked as well. Each z-bin has a header with the range of light indices and the + /// range of probe indices the shader iterates; a range must cover the items of its kind in the bin, stay within the + /// indices of its kind, and be empty when the bin has none. No bit may be set for an item index that does not exist, + /// and nothing may be written past the tiles and z-bins in use. + /// + static class LightClusteringOracle + { + // Distance in pixels within which a volume counts as touching a tile rectangle. Absorbs float error in the jobs + // and volumes that touch a tile along an edge or in a sliver too thin to sample. + const double k_TouchMargin = 0.125; + + public class Result + { + public List missing = new List(); + public List outside = new List(); + public bool failed => missing.Count > 0 || outside.Count > 0; + + public override string ToString() => + (missing.Count > 0 ? $"Missing ({missing.Count}): {string.Join("; ", missing.GetRange(0, math.min(10, missing.Count)))}\n" : "") + + (outside.Count > 0 ? $"Outside ({outside.Count}): {string.Join("; ", outside.GetRange(0, math.min(10, outside.Count)))}\n" : ""); + } + + class Output + { + public int2 tileResolution; + public int tileWidth; + public int wordsPerTile; + public int binCount; + public float zBinScale; + public float zBinOffset; + public uint[] tileMasks; + public uint[] zBins; + } + + static bool reflectionProbeRotation => + !GraphicsSettings.TryGetRenderPipelineSettings(out var settings) || settings.UseReflectionProbeRotation; + + // The jobs index lights before probes; the reference uses the same order to find each item's bit. + static List InJobOrder(ClusteringScene scene) + { + var ordered = new List(); + ordered.AddRange(scene.items.FindAll(i => i.kind != ClusteringItemKind.Probe)); + ordered.AddRange(scene.items.FindAll(i => i.kind == ClusteringItemKind.Probe)); + return ordered; + } + + static Output Run(ClusteringScene scene, List ordered) + { + var lightCount = ordered.FindAll(i => i.kind != ClusteringItemKind.Probe).Count; + var lights = new NativeArray(lightCount, Allocator.TempJob); + var probes = new NativeArray(ordered.Count - lightCount, Allocator.TempJob); + var zBins = new NativeArray(UniversalRenderPipeline.maxZBinWords, Allocator.TempJob); + var tileMasks = new NativeArray(UniversalRenderPipeline.maxTileWords, Allocator.TempJob); + try + { + for (var i = 0; i < ordered.Count; i++) + { + var item = ordered[i]; + if (item.kind == ClusteringItemKind.Probe) + { + probes[i - lightCount] = new VisibleReflectionProbe + { + bounds = new Bounds(item.position, 2f * (Vector3)item.extents), + localToWorldMatrix = Matrix4x4.TRS(item.position, item.rotation, Vector3.one), + }; + } + else + { + lights[i] = new VisibleLight + { + lightType = item.kind == ClusteringItemKind.Spot ? LightType.Spot : LightType.Point, + finalColor = Color.white, + screenRect = new Rect(0, 0, 1, 1), + localToWorldMatrix = new Matrix4x4( + new Vector4(1, 0, 0, 0), + new Vector4(0, 1, 0, 0), + new Vector4(item.direction.x, item.direction.y, item.direction.z, 0), + new Vector4(item.position.x, item.position.y, item.position.z, 1)), + range = item.range, + spotAngle = item.spotAngle, + intersectsNearPlane = true, + intersectsFarPlane = true, + }; + } + } + + var output = new Output(); + var handle = ForwardLights.ScheduleClusteringJobs( + false, true, lights, probes, zBins, tileMasks, + new Fixed2(scene.worldToViews[0], scene.worldToViews[1]), + new Fixed2(scene.viewToClips[0], scene.viewToClips[1]), + scene.viewCount, scene.screenSize, scene.near, scene.far, scene.orthographic, + out _, out _, out output.binCount, out output.zBinScale, out output.zBinOffset, + out output.tileResolution, out output.tileWidth, out output.wordsPerTile); + JobHandle.ScheduleBatchedJobs(); + handle.Complete(); + output.tileMasks = tileMasks.ToArray(); + output.zBins = zBins.ToArray(); + return output; + } + finally + { + lights.Dispose(); + probes.Dispose(); + zBins.Dispose(); + tileMasks.Dispose(); + } + } + + /// + /// Runs the clustering jobs on the scene and returns every missing or outside tile and z-bin, per item and view. + /// + public static Result Check(ClusteringScene scene) + { + var ordered = InJobOrder(scene); + var output = Run(scene, ordered); + var result = new Result(); + var tileResolution = output.tileResolution; + var tileWidth = output.tileWidth; + for (var view = 0; view < scene.viewCount; view++) + { + var camera = new Camera(scene, view); + for (var index = 0; index < ordered.Count; index++) + { + var volume = new Volume(scene, view, ordered[index]); + var (zMin, zMax) = volume.DepthExtent(); + + // Relative tolerance for depth comparisons, a few hundred times the float precision of the depths. + var zTolerance = 1e-5 * (math.abs(zMin) + math.abs(zMax) + math.abs(scene.near) + 1); + + // A volume that only touches the near or far plane has a visible part of zero area, a point or a line, + // which no ray sampling can find. Its tiles are not checked for over-coverage. + var degenerate = zMax < scene.near + zTolerance || zMin > scene.far - zTolerance; + var word = index / 32; + var bit = 1u << (index % 32); + var label = $"item {index} {ordered[index].kind} view {view}"; + var maskBase = view * output.wordsPerTile * tileResolution.x * tileResolution.y; + bool InTile(int tx, int ty) => (output.tileMasks[maskBase + (ty * tileResolution.x + tx) * output.wordsPerTile + word] & bit) != 0; + bool InBin(int b) => b >= 0 && b < output.binCount && + (output.zBins[(view * output.binCount + b) * (ZBinningJob.headerLength + output.wordsPerTile) + ZBinningJob.headerLength + word] & bit) != 0; + // Same z-bin mapping as the shader: linear in depth for orthographic cameras, logarithmic otherwise. + int BinOf(double z) => (int)math.floor((scene.orthographic ? z : math.log2(z)) * output.zBinScale + output.zBinOffset); + + // Cast a ray through each pixel center on screen. A tile is reached when one of its rays hits the volume, + // and every z-bin between the depths where that ray enters and leaves the volume must hold the item. + // Partial tiles at the screen edges only have rays for their on-screen pixels. + for (var ty = 0; ty < tileResolution.y; ty++) + { + for (var tx = 0; tx < tileResolution.x; tx++) + { + var hit = false; + var binMissing = false; + for (var py = ty * tileWidth; py < math.min(scene.screenSize.y, (ty + 1) * tileWidth); py++) + { + for (var px = tx * tileWidth; px < math.min(scene.screenSize.x, (tx + 1) * tileWidth); px++) + { + camera.Ray(px + 0.5, py + 0.5, out var origin, out var direction); + var (lo, hi) = volume.Hit(origin, direction, scene.near, scene.far); + if (lo > hi) + continue; + hit = true; + var lastBin = math.min(BinOf(hi), output.binCount - 1); + for (var b = math.max(BinOf(lo), 0); b <= lastBin && !binMissing; b++) + { + if (!InBin(b)) + { + binMissing = true; + result.missing.Add($"{label} z-bin {b} (depths {lo:G6}..{hi:G6} at pixel {px},{py})"); + } + } + } + } + + if (hit && !InTile(tx, ty)) + result.missing.Add($"{label} tile ({tx},{ty})"); + if (!hit && !degenerate && InTile(tx, ty) && !volume.TouchesTile(camera, tx, ty, tileWidth, scene.near, scene.far)) + result.outside.Add($"{label} tile ({tx},{ty})"); + } + } + + // A z-bin is over-covered when it lies more than one bin beyond the depth extent of the volume, clipped to + // the near and far planes. A volume entirely outside them allows no bin. + zMin = math.max(zMin - zTolerance, scene.near); + zMax = math.min(zMax + zTolerance, scene.far); + var allowedMin = zMin <= zMax ? BinOf(zMin) - 1 : int.MaxValue; + var allowedMax = zMin <= zMax ? BinOf(zMax) + 1 : int.MinValue; + for (var b = 0; b < output.binCount; b++) + { + if (InBin(b) && (b < allowedMin || b > allowedMax)) + result.outside.Add($"{label} z-bin {b} (volume depths {zMin:G6}..{zMax:G6})"); + } + } + } + CheckLayout(scene, ordered, output, result); + return result; + } + + static void CheckLayout(ClusteringScene scene, List ordered, Output output, Result result) + { + var lightCount = ordered.FindAll(i => i.kind != ClusteringItemKind.Probe).Count; + var stride = ZBinningJob.headerLength + output.wordsPerTile; + // The first header word of a z-bin is the range of light indices the shader iterates in that bin, the second + // the range of probe indices. A range must cover every item of its kind in the bin, stay within the indices of + // its kind, and be empty when the bin has no item of its kind; otherwise the shader would visit an item of the + // other kind. + var kindBegin = new int2(0, lightCount); + var kindEnd = new int2(lightCount, ordered.Count); + for (var bin = 0; bin < scene.viewCount * output.binCount; bin++) + { + var present = new bool2(false, false); + for (var word = 0; word < output.wordsPerTile; word++) + { + var bits = output.zBins[bin * stride + ZBinningJob.headerLength + word]; + for (var bit = 0; bit < 32; bit++) + { + if ((bits & (1u << bit)) == 0) + continue; + var index = word * 32 + bit; + if (index >= ordered.Count) + { + result.outside.Add($"z-bin {bin} has a bit for item {index}, which does not exist"); + continue; + } + + var kind = index < lightCount ? 0 : 1; + present[kind] = true; + var header = output.zBins[bin * stride + kind]; + if (index < (header & 0xFFFF) || index > header >> 16) + result.missing.Add($"z-bin {bin} header {kind} is {header & 0xFFFF}..{header >> 16} and leaves out item {index}"); + } + } + + for (var kind = 0; kind < 2; kind++) + { + var header = output.zBins[bin * stride + kind]; + int min = (int)(header & 0xFFFF), max = (int)(header >> 16); + if (min > max) + continue; + if (!present[kind]) + result.outside.Add($"z-bin {bin} header {kind} is {min}..{max} but the bin has no item of its kind"); + else if (min < kindBegin[kind] || max >= kindEnd[kind]) + result.outside.Add($"z-bin {bin} header {kind} is {min}..{max}, outside the item indices {kindBegin[kind]}..{kindEnd[kind] - 1} of its kind"); + } + } + for (var i = scene.viewCount * output.binCount * stride; i < output.zBins.Length; i++) + { + if (output.zBins[i] != 0) + result.outside.Add($"z-bin word {i} past the bins in use is {output.zBins[i]}"); + } + + var tileWords = output.tileResolution.x * output.tileResolution.y * output.wordsPerTile; + for (var tile = 0; tile < scene.viewCount * output.tileResolution.x * output.tileResolution.y; tile++) + { + for (var word = 0; word < output.wordsPerTile; word++) + { + var bits = output.tileMasks[tile * output.wordsPerTile + word]; + var validBits = math.clamp(ordered.Count - word * 32, 0, 32); + if (validBits < 32 && bits >> validBits != 0) + result.outside.Add($"tile {tile} word {word} has bits for items that do not exist: {bits:X8}"); + } + } + for (var i = scene.viewCount * tileWords; i < output.tileMasks.Length; i++) + { + if (output.tileMasks[i] != 0) + result.outside.Add($"tile mask word {i} past the tiles in use is {output.tileMasks[i]}"); + } + } + + // Rays and projections derived from the view-to-clip matrix itself, independently of how the jobs derive their + // view planes from it. View space has +z forward and the depth along a ray is its parameter. + readonly struct Camera + { + readonly bool m_Orthographic; + readonly double4x4 m_ViewToClip; + + public bool orthographic => m_Orthographic; + readonly double2 m_Screen; + + public Camera(ClusteringScene scene, int view) + { + m_Orthographic = scene.orthographic; + m_ViewToClip = scene.viewToClips[view]; + m_Screen = new double2(scene.screenSize.x, scene.screenSize.y); + } + + // Pixel position of a view-space point. + public double2 Project(double3 p) + { + var ndc = m_Orthographic + ? new double2(p.x * m_ViewToClip[0][0] + m_ViewToClip[3][0], p.y * m_ViewToClip[1][1] + m_ViewToClip[3][1]) + : new double2(p.x / p.z * m_ViewToClip[0][0] - m_ViewToClip[2][0], p.y / p.z * m_ViewToClip[1][1] - m_ViewToClip[2][1]); + return (ndc * 0.5 + 0.5) * m_Screen; + } + + // View-space ray through a pixel position, as origin + depth * direction. Perspective rays start at the camera, + // orthographic rays start in the camera plane and point along +z. + public void Ray(double px, double py, out double3 origin, out double3 direction) + { + var ndc = new double2(px, py) / m_Screen * 2 - 1; + if (m_Orthographic) + { + origin = new double3((ndc.x - m_ViewToClip[3][0]) / m_ViewToClip[0][0], (ndc.y - m_ViewToClip[3][1]) / m_ViewToClip[1][1], 0); + direction = new double3(0, 0, 1); + } + else + { + origin = 0; + direction = new double3((ndc.x + m_ViewToClip[2][0]) / m_ViewToClip[0][0], (ndc.y + m_ViewToClip[2][1]) / m_ViewToClip[1][1], 1); + } + } + } + + // The volume of one item in the view space of one view, in double precision. + readonly struct Volume + { + readonly ClusteringItemKind m_Kind; + readonly double3 m_Position; + readonly double3 m_Axis; + readonly double m_CosSq; + readonly double m_Range; + readonly double3x3 m_Basis; + readonly double3 m_Extents; + + public Volume(ClusteringScene scene, int view, ClusteringItem item) + { + var worldToView = (double4x4)scene.worldToViews[view]; + var flip = new double3(1, 1, -1); + m_Kind = item.kind; + m_Position = math.mul(worldToView, new double4((double3)item.position, 1)).xyz * flip; + m_Axis = math.normalize(math.mul(worldToView, new double4((double3)item.direction, 0)).xyz * flip); + var cos = math.cos(math.radians((double)item.spotAngle) * 0.5); + m_CosSq = cos * cos; + m_Range = item.range; + var rotation = reflectionProbeRotation ? new double3x3(new float3x3(item.rotation)) : double3x3.identity; + m_Basis = new double3x3( + math.mul(worldToView, new double4(rotation.c0, 0)).xyz * flip, + math.mul(worldToView, new double4(rotation.c1, 0)).xyz * flip, + math.mul(worldToView, new double4(rotation.c2, 0)).xyz * flip); + m_Extents = (double3)item.extents; + } + + // Depth interval [lo, hi] of origin + s * direction inside the volume for s in [s0, s1]; lo > hi if none. + // Boxes use the slab method. Spheres solve a quadratic. Cones solve the cone quadric and intersect the result + // with the sphere interval; the volume is convex, so its inside along a ray is one interval. + public (double, double) Hit(double3 origin, double3 direction, double s0, double s1) + { + if (m_Kind == ClusteringItemKind.Probe) + { + double lo = s0, hi = s1; + for (var k = 0; k < 3; k++) + { + var length = math.length(m_Basis[k]); + var axis = m_Basis[k] / length; + var extent = m_Extents[k] * length; + var offset = math.dot(origin - m_Position, axis); + var speed = math.dot(direction, axis); + if (speed == 0) + { + if (math.abs(offset) > extent) + return (1, 0); + continue; + } + var ta = (-extent - offset) / speed; + var tb = (extent - offset) / speed; + lo = math.max(lo, math.min(ta, tb)); + hi = math.min(hi, math.max(ta, tb)); + if (lo > hi) + return (1, 0); + } + return (lo, hi); + } + + var toCenter = m_Position - origin; + double dd = math.dot(direction, direction), da = math.dot(direction, toCenter), aa = math.dot(toCenter, toCenter); + var disc = da * da - dd * (aa - m_Range * m_Range); + if (disc < 0) + return (1, 0); + var sq = math.sqrt(disc); + var a0 = math.max((da - sq) / dd, s0); + var a1 = math.min((da + sq) / dd, s1); + if (a0 > a1 || m_Kind == ClusteringItemKind.Point) + return (a0, a1); + + // Along the ray, the inside of the cone can only begin or end at a root of the cone quadric + // ga s^2 + 2 gb s + gc = 0, where the ray meets the double cone, or where it crosses the plane through the + // vertex, which separates the two nappes. Sorting these candidates with the sphere interval bounds and + // testing each candidate and each midpoint between neighbors finds the inside interval exactly. The roots are + // computed as q / ga and gc / q, which keeps the single root when the ray is parallel to a cone line, where + // ga is 0. + double du = math.dot(direction, m_Axis), au = math.dot(toCenter, m_Axis); + double ga = du * du - m_CosSq * dd, gb = -du * au + m_CosSq * da, gc = au * au - m_CosSq * aa; + Span sorted = stackalloc double[6]; + var n = 0; + Insert(sorted, ref n, a0, a0, a1); + Insert(sorted, ref n, a1, a0, a1); + // A grazing ray can round the discriminant below 0; the extra candidates are harmless, InsideCone decides. + var root = math.sqrt(math.max(gb * gb - ga * gc, 0)); + var q = -(gb + (gb < 0 ? -root : root)); + if (q != 0) + { + Insert(sorted, ref n, q / ga, a0, a1); + Insert(sorted, ref n, gc / q, a0, a1); + } + if (du != 0) + Insert(sorted, ref n, au / du, a0, a1); + + double inLo = double.MaxValue, inHi = double.MinValue; + for (var i = 0; i < n; i++) + { + if (InsideCone(origin, direction, sorted[i])) + { + inLo = math.min(inLo, sorted[i]); + inHi = math.max(inHi, sorted[i]); + } + if (i + 1 < n && InsideCone(origin, direction, 0.5 * (sorted[i] + sorted[i + 1]))) + { + inLo = math.min(inLo, sorted[i]); + inHi = math.max(inHi, sorted[i + 1]); + } + } + return (inLo, inHi); + } + + static void Insert(Span sorted, ref int count, double value, double min, double max) + { + if (double.IsNaN(value) || value < min || value > max) + return; + var k = count++; + while (k > 0 && sorted[k - 1] > value) + { + sorted[k] = sorted[k - 1]; + k--; + } + sorted[k] = value; + } + + // Whether the point at depth s lies in the forward nappe of the cone. The small tolerance counts points on the + // surface as inside, which can only make the missing check stricter. + bool InsideCone(double3 origin, double3 direction, double s) + { + var q = origin + s * direction - m_Position; + var axial = math.dot(q, m_Axis); + return axial >= 0 && axial * axial - m_CosSq * math.dot(q, q) >= -1e-12; + } + + // Exact depth range of the whole volume, ignoring the near and far planes. + public (double, double) DepthExtent() + { + if (m_Kind == ClusteringItemKind.Probe) + { + var e = math.abs(m_Basis.c0.z) * m_Extents.x + math.abs(m_Basis.c1.z) * m_Extents.y + math.abs(m_Basis.c2.z) * m_Extents.z; + return (m_Position.z - e, m_Position.z + e); + } + if (m_Kind == ClusteringItemKind.Point) + return (m_Position.z - m_Range, m_Position.z + m_Range); + + // A spot volume reaches its depth extremes at the vertex or on the base circle, where the cone meets the + // sphere. The sphere cap goes further only when the view axis lies inside the cone, in which case the extreme + // is a full range away from the vertex. + var cos = math.sqrt(m_CosSq); + var baseCenter = m_Position + m_Axis * m_Range * cos; + var baseExtent = m_Range * math.sqrt(1 - m_CosSq) * math.sqrt(math.max(0, 1 - m_Axis.z * m_Axis.z)); + var lo = -m_Axis.z >= cos ? m_Position.z - m_Range : math.min(m_Position.z, baseCenter.z - baseExtent); + var hi = m_Axis.z >= cos ? m_Position.z + m_Range : math.max(m_Position.z, baseCenter.z + baseExtent); + return (lo, hi); + } + + // Whether the volume comes within k_TouchMargin pixels of the tile rectangle. Points known to be in the volume + // are tested first: the center of a point light or probe, or the vertex and two axis points of a spot light. + // This covers volumes smaller than a sample spacing and a spot light whose vertex touches a tile at a single + // point. Then the grown rectangle is sampled with rays on grids of 1/16 and 1/64 pixel. + public bool TouchesTile(Camera camera, int tx, int ty, int tileWidth, double near, double far) + { + var depthTolerance = 1e-5 * (math.length(m_Position) + m_Range + math.length(m_Extents) + math.abs(near)); + for (var i = 0; i < 3; i++) + { + if (m_Kind != ClusteringItemKind.Spot && i > 0) + break; + var p = m_Position + m_Axis * (m_Range * math.sqrt(m_CosSq) * i * 0.5); + if (p.z < near - depthTolerance || p.z > far + depthTolerance || (!camera.orthographic && p.z <= 0)) + continue; + var pixel = camera.Project(p); + if (math.all(pixel >= new double2(tx, ty) * tileWidth - k_TouchMargin) && math.all(pixel <= new double2(tx + 1, ty + 1) * tileWidth + k_TouchMargin)) + return true; + } + + foreach (var samplesPerPixel in new[] { 16, 64 }) + { + var size = tileWidth + 2 * k_TouchMargin; + var n = (int)math.ceil(size * samplesPerPixel); + for (var j = 0; j <= n; j++) + { + for (var i = 0; i <= n; i++) + { + camera.Ray(tx * tileWidth - k_TouchMargin + size * i / n, ty * tileWidth - k_TouchMargin + size * j / n, out var origin, out var direction); + var (lo, hi) = Hit(origin, direction, near, far); + if (lo <= hi) + return true; + } + } + } + return false; + } + } + + static float3 RandomDirection(ref Unity.Mathematics.Random rng) + { + const float a = 0.70710677f; + var special = new[] + { + new float3(0, 0, 1), new float3(0, 0, -1), new float3(1, 0, 0), new float3(-1, 0, 0), new float3(0, 1, 0), new float3(0, -1, 0), + new float3(a, 0, a), new float3(-a, 0, a), new float3(0, a, a), new float3(0, -a, a), new float3(a, 0, -a), new float3(0, a, -a), + new float3(a, a, 0), math.normalize(new float3(1, 1, 1)), math.normalize(new float3(-1, 1, 1)), + }; + return rng.NextInt(0, 2) == 0 ? special[rng.NextInt(0, special.Length)] : math.normalize(rng.NextFloat3(-1f, 1f) + new float3(0, 0, 1e-3f)); + } + + /// + /// Seeded random scenes: perspective or orthographic, one or two views, lens shift, and items biased towards the + /// degenerate configurations that broke the clustering jobs before: axis-aligned and 45 degree spot axes, vertices + /// on the view axis or near the near plane, cameras on the cone axis, cone edges along the view direction, and items + /// crossing the near and far planes. + /// + public static ClusteringScene RandomScene(ref Unity.Mathematics.Random rng, int2 screenSize, int maxItems) + { + var scene = new ClusteringScene + { + orthographic = rng.NextInt(0, 3) == 0, + viewCount = rng.NextInt(0, 4) == 0 ? 2 : 1, + screenSize = screenSize, + }; + var scale = rng.NextFloat(2f, 40f); + if (scene.orthographic) + { + scene.near = rng.NextInt(0, 3) == 0 ? -rng.NextFloat(0.1f, 20f) : rng.NextFloat(0.01f, 2f); + scene.far = scene.near + rng.NextFloat(5f, 200f); + } + else + { + scene.near = rng.NextFloat(0.01f, 2f); + scene.far = rng.NextInt(0, 4) == 0 ? rng.NextFloat(scene.near + 0.5f, 20f) : rng.NextFloat(50f, 5000f); + } + + var flip = float4x4.Scale(1, 1, -1); + var viewToWorld = rng.NextBool() + ? float4x4.identity + : float4x4.TRS(rng.NextFloat3(-50f, 50f), quaternion.EulerXYZ(rng.NextFloat3(-math.PI, math.PI)), 1f); + var aspect = (float)screenSize.x / screenSize.y * rng.NextFloat(0.8f, 1.25f); + var halfHeight = rng.NextFloat(1f, 30f); + var p11 = 1f / math.tan(math.radians(rng.NextFloat(20f, 120f)) * 0.5f); + for (var v = 0; v < scene.viewCount; v++) + { + var eye = v == 0 ? float3.zero : new float3(rng.NextFloat(0.02f, 0.08f), 0, 0); + scene.worldToViews[v] = math.mul(flip, math.inverse(math.mul(viewToWorld, float4x4.Translate(eye)))); + var shift = rng.NextInt(0, 3) == 0 || v == 1 ? rng.NextFloat2(-0.4f, 0.4f) : float2.zero; + scene.viewToClips[v] = scene.orthographic + ? ClusteringScene.Orthographic(halfHeight * aspect, halfHeight, shift, scene.near, scene.far) + : ClusteringScene.Perspective(p11 / aspect, p11, shift, scene.near, scene.far); + } + if (scene.viewCount == 1) + { + scene.worldToViews[1] = scene.worldToViews[0]; + scene.viewToClips[1] = scene.viewToClips[0]; + } + + var viewToWorldFlipped = math.mul(viewToWorld, flip); + var count = rng.NextInt(1, maxItems + 1); + for (var i = 0; i < count; i++) + { + var positionVS = new float3(rng.NextFloat(-1f, 1f) * scale, rng.NextFloat(-1f, 1f) * scale, rng.NextFloat(-0.3f, 1.2f) * scale); + switch (rng.NextInt(0, 8)) + { + case 0: positionVS.z = scene.near; break; + case 1: positionVS.z = scene.near * (1f + (rng.NextBool() ? 1f : -1f) * math.pow(10f, rng.NextFloat(-6f, -1f))); break; + case 2: positionVS.xy = 0; break; + case 3: positionVS = math.round(positionVS); break; + case 4: positionVS.z = scene.far * rng.NextFloat(0.9f, 1.1f); break; + } + + var kind = rng.NextInt(0, 10); + if (kind < 2) + { + var extents = rng.NextFloat3(0.05f, 1f) * scale * rng.NextFloat(0.1f, 1f); + if (rng.NextInt(0, 4) == 0) + extents = math.round(extents) + 0.5f; + var rotation = rng.NextInt(0, 3) == 0 ? quaternion.identity : quaternion.EulerXYZ(rng.NextFloat3(-math.PI, math.PI)); + scene.items.Add(ClusteringItem.Probe(math.transform(viewToWorldFlipped, new float3(positionVS.xy, -positionVS.z)), extents, rotation)); + continue; + } + + var range = rng.NextFloat(0.2f, 1.5f) * scale; + if (kind < 4) + { + scene.items.Add(ClusteringItem.Point(math.transform(viewToWorldFlipped, new float3(positionVS.xy, -positionVS.z)), range)); + continue; + } + + var directionVS = RandomDirection(ref rng); + if (rng.NextInt(0, 6) == 0) + positionVS = -directionVS * math.round(rng.NextFloat(0.5f, 0.9f) * range); + float spotAngle; + switch (rng.NextInt(0, 3)) + { + case 0: spotAngle = math.round(rng.NextFloat(1f, 179f) / 5f) * 5f; break; + case 1: spotAngle = 2f * math.degrees(math.acos(math.saturate(math.abs(directionVS.z)))); break; + default: spotAngle = rng.NextFloat(1f, 179f); break; + } + scene.items.Add(ClusteringItem.Spot( + math.transform(viewToWorldFlipped, new float3(positionVS.xy, -positionVS.z)), + math.rotate(viewToWorldFlipped, new float3(directionVS.xy, -directionVS.z)), + range, + math.clamp(spotAngle, 1f, 179f))); + } + return scene; + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/LightClusteringOracle.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/LightClusteringOracle.cs.meta new file mode 100644 index 00000000000..6057bf525ac --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/LightClusteringOracle.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: d77e88cab17104a5989b830dcd178107 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/LightClusteringTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/LightClusteringTests.cs index 9aec8b2c0ca..ec5e8daca74 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/LightClusteringTests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/LightClusteringTests.cs @@ -1,475 +1,366 @@ -// Unit tests for light clustering code used in Forward+ and Deferred+ rendering -// modes. +// Unit tests for light clustering code used in Forward+ and Deferred+ rendering modes. Each scene is checked against +// LightClusteringOracle: no light or probe may be missing from a tile or z-bin it reaches, and none may be in a tile or +// z-bin its volume stays clear of. +using System; using System.Collections.Generic; using NUnit.Framework; using Unity.Collections; -using Unity.Jobs; using Unity.Mathematics; using UnityEngine.Rendering.Universal.Internal; using UnityEngine.TestTools; namespace UnityEngine.Rendering.Universal.Tests { + [UnityPlatform(include = new RuntimePlatform[] { RuntimePlatform.WindowsEditor, RuntimePlatform.WindowsPlayer, RuntimePlatform.OSXEditor, RuntimePlatform.OSXPlayer })] class LightClusteringTests { - [Description("The tiling job calculates an intersection between an XZ plane and the light volume to determine the range of tiles that the light affects. In the cases where this range falls completely outside of the screen, this test ensures that the ranges are clamped correctly to screen boundaries. If not tested, this bug affects the cone section of spot lights, the cap section of spot lights, and also point lights. This test was added due to UUM-84591.")] - [UnityPlatform(include = new RuntimePlatform[] { RuntimePlatform.WindowsEditor, RuntimePlatform.WindowsPlayer, RuntimePlatform.OSXEditor, RuntimePlatform.OSXPlayer })] - [Test] - public void LightClustering_WhenLightVolumeIntersectionWithXZPlaneIsOutsideTheScreen_ZBinsAndTileMasksAreCorrect() + const float k_Diagonal = 0.57735026f; + const float k_Half = 0.70710677f; + static readonly int2 k_SmallScreen = new int2(64, 64); + static readonly int2 k_Screen = new int2(480, 270); + + static ClusteringScene Perspective(float fovYDeg, float aspect, float near, float far, int2 screenSize, ClusteringItem itemVS) => + ClusteringScene.PerspectiveViewSpace(fovYDeg, aspect, near, far, screenSize, itemVS); + + static ClusteringScene Perspective(float p00, float p11, float2 lensShift, float near, float far, int2 screenSize, ClusteringItem itemVS) => + ClusteringScene.PerspectiveViewSpace(p00, p11, lensShift, near, far, screenSize, itemVS); + + static ClusteringScene Orthographic(float halfWidth, float halfHeight, float near, float far, int2 screenSize, ClusteringItem itemVS) => + ClusteringScene.OrthographicViewSpace(halfWidth, halfHeight, near, far, screenSize, itemVS); + + static TestCaseData Case(string name, string description, ClusteringScene scene) => + new TestCaseData(scene).SetName($"LightClustering_IsExact({name})").SetDescription(description); + + static IEnumerable ExactScenes() { - NativeArray lights = new(1, Allocator.TempJob); - // Light world transform: - // UnityEditor.TransformWorldPlacementJSON:{"position":{"x":3.0,"y":3.0,"z":0.0},"rotation":{"x":0.511572539806366,"y":0.3068491518497467,"z":-0.7767189145088196,"w":0.20210090279579163},"scale":{"x":1.0,"y":1.0,"z":1.0}} - lights[0] = new VisibleLight() { - lightType = LightType.Spot, - finalColor = Color.white, - screenRect = new Rect(0, 0, 1, 1), - localToWorldMatrix = new Matrix4x4( - new Vector4(-0.394897342f, 0, -0.918725133f, 0), - new Vector4(0.627902389f, -0.729997516f, -0.269892514f, 0), - new Vector4(-0.670667171f, -0.683449626f, 0.288274288f, 0), - new Vector4(3, 3, 0, 1) - ), - range = 10, - spotAngle = 100, - intersectsNearPlane = true, - intersectsFarPlane = false, - }; - NativeArray probes = new(0, Allocator.TempJob); - NativeArray zBins = new(UniversalRenderPipeline.maxZBinWords, Allocator.TempJob); - NativeArray tileMasks = new (UniversalRenderPipeline.maxTileWords, Allocator.TempJob); - - // Camera world transform: - // UnityEditor.TransformWorldPlacementJSON:{"position":{"x":-4.0,"y":1.0,"z":2.0},"rotation":{"x":0.32139381766319277,"y":0.663413941860199,"z":-0.3830222189426422,"w":0.5566704273223877},"scale":{"x":1.0,"y":1.0,"z":1.0}} - float4x4 worldToView = new float4x4( - new float4(-0.1736481f, 0.8528686f, -0.4924039f, 0f), - new float4(0f, 0.5f, 0.8660254f, 0f), - new float4(-0.9848078f, -0.1503837f, 0.08682406f, 0f), - new float4(1.275023f, 3.212242f, -3.009289f, 1f) - ); - var worldToViews = new Fixed2(worldToView, worldToView); - float4x4 viewToClip = new float4x4( - new float4(0.7968904f, 0f, 0f, 0f), - new float4(0f, 1.732051f, 0f, 0f), - new float4(0f, 0f, -1.0006f, -1f), - new float4(0f, 0f, -0.60018f, 0f) - ); - var viewToClips = new Fixed2(viewToClip, viewToClip); - int2 screenResolution = new(128, 128); - float nearPlane = 0.3f; - float farPlane = 1000f; - - JobHandle handle = ForwardLights.ScheduleClusteringJobs( - false, - true, - lights, - probes, - zBins, - tileMasks, - worldToViews, - viewToClips, - 1, - screenResolution, - nearPlane, - farPlane, - false, - out int localLightCount, - out int directionalLightCount, - out int binCount, - out float zBinScale, - out float zBinOffset, - out int2 tileResolution, - out int actualTileWidth, - out int wordsPerTile - ); - JobHandle.ScheduleBatchedJobs(); - handle.Complete(); - - // Uncomment temporarily if the reference arrays need to be updated. - // Debug.Log(string.Join(",", zBins)); - // Debug.Log(string.Join(",", tileMasks)); - - // If the following assertions fail, there isn't currently good - // tooling to visualize the difference. A 3D texture slice viewer - // can be built that would fix this issue. But the cost-benefit is - // not worth it at the moment, since the diff of a PR that fails - // this test can be enough to go on. - // - // Also, these assertions can fail if a change is made includes more - // false positives, i.e. lights contributing to _more_ clusters than - // expected due to increased conservatism, or lights contributing to - // _less_ clusters due increased accuracy. In either of these cases, - // it is up to the author of these code changes to update the - // expected values. - try - { - CollectionAssert.AreEqual(expectedZBins1, zBins); - CollectionAssert.AreEqual(expectedTileMasks1, tileMasks); + var scene = new ClusteringScene { near = 0.3f, far = 1000f, screenSize = new int2(128, 128) }; + scene.worldToViews[0] = scene.worldToViews[1] = new float4x4( + new float4(-0.1736481f, 0.8528686f, -0.4924039f, 0f), + new float4(0f, 0.5f, 0.8660254f, 0f), + new float4(-0.9848078f, -0.1503837f, 0.08682406f, 0f), + new float4(1.275023f, 3.212242f, -3.009289f, 1f)); + scene.viewToClips[0] = scene.viewToClips[1] = ClusteringScene.Perspective(0.7968904f, 1.732051f, float2.zero, scene.near, scene.far); + scene.items.Add(ClusteringItem.Spot(new float3(3f, 3f, 0f), new float3(-0.670667171f, -0.683449626f, 0.288274288f), 10f, 100f)); + yield return Case("SpotRangeOutsideScreenInXZPlane", "A spot light whose intersection with an XZ plane falls outside the screen (UUM-84591).", scene); } - finally + + yield return Case("PointLightCrossingNearPlane", "A point light crossing the near plane.", + Perspective(1f, 1f, float2.zero, 0.5f, 100f, k_SmallScreen, ClusteringItem.Point(new float3(1.604f, -1.6087f, 0.8924f), 1.2312f))); + yield return Case("PointLightAboveFrustum", "A point light above the frustum reaching the top tile row.", + Perspective(1f, 1f, float2.zero, 0.5f, 100f, k_SmallScreen, ClusteringItem.Point(new float3(-4.4307f, 7.244f, 5.7363f), 1.9306f))); + yield return Case("PointLightInFrontOfCamera", "A point light in front of the camera.", + Perspective(1f, 1f, float2.zero, 0.5f, 100f, k_SmallScreen, ClusteringItem.Point(new float3(0.3f, 0.2f, 5f), 1.3f))); + yield return Case("PointLightCrossingFarPlane", "A point light crossing the far plane.", + Perspective(60f, 16f / 9f, 0.3f, 27f, k_Screen, ClusteringItem.Point(new float3(0.5f, 0.3f, 30f), 5f))); + yield return Case("PointLightCrossingNearPlaneOffCenter", "A point light crossing the near plane whose vertical extent on screen comes from its section with the near plane.", + Perspective(0.7515261f, 1.1239314f, new float2(-0.35771352f, 0.24809685f), 0.6553464f, 2306.9248f, new int2(250, 141), ClusteringItem.Point(new float3(-5.5001135f, -5.4904704f, 0.96593094f), 6.838029f))); + yield return Case("PointLightFarOffScreenNearCamera", "A point light so far to the side of a camera with a close near plane that its tile coordinates exceed the 16-bit range of the tile ranges.", + Perspective(60f, 16f / 9f, 0.01f, 1000f, k_Screen, ClusteringItem.Point(new float3(22f, 0f, 0.3f), 0.35f))); + yield return Case("PointLightBehindCamera", "A point light entirely behind the camera is in no tile or z-bin.", + Perspective(60f, 16f / 9f, 0.3f, 1000f, k_Screen, ClusteringItem.Point(new float3(0f, 0f, -5f), 2f))); + yield return Case("PointLightEnclosingNearPlane", "A point light whose sphere contains the near-plane rectangle covers every tile.", + Perspective(1f, 1f, float2.zero, 0.5f, 100f, k_SmallScreen, ClusteringItem.Point(new float3(0.3f, -0.2f, 1f), 5f))); + + yield return Case("SpotLightInFrontOfNearPlane", "A spot light in front of the near plane.", + Perspective(72.032f, 1.3333f, 0.412f, 1000f, k_SmallScreen, ClusteringItem.Spot(new float3(1.5852f, -1.4977f, 6.9015f), new float3(-0.1672f, -0.2562f, 0.952f), 2.227f, 75.974f))); + yield return Case("SpotLightCrossingNearPlane", "A spot light crossing the near plane.", + Perspective(58.88f, 1.3333f, 0.461f, 1000f, k_SmallScreen, ClusteringItem.Spot(new float3(0.447f, 1.0636f, 1.4462f), new float3(0.011f, -0.121f, 0.9926f), 2.017f, 112.675f))); + yield return Case("SpotSilhouetteOffScreenEdge", "A spot light whose silhouette leaves the screen.", + Perspective(86.3651f, 0.9666f, 0.357f, 1000f, k_SmallScreen, ClusteringItem.Spot(new float3(-0.008f, -0.1112f, -2.0052f), new float3(-0.9652f, -0.1627f, 0.2046f), 4.0016f, 66.8309f))); + yield return Case("SpotVertexInCameraPlane", "A spot light whose vertex lies in the camera plane (UUM-154016).", + Perspective(60f, 16f / 9f, 0.3f, 1000f, k_Screen, ClusteringItem.Spot(new float3(-4.8e-7f, -0.2f, 0f), new float3(3.7e-9f, 0f, 1f), 50f, 55f))); + yield return Case("SpotBehindCameraAlongViewAxis", "A spot light behind the camera whose axis is the view direction (UUM-159132).", + Perspective(60f, 989f / 485f, 0.3f, 1000f, new int2(989, 485), ClusteringItem.Spot(new float3(0.25f, 0f, -2f), new float3(0f, 0f, 1f), 6f, 30f))); + yield return Case("SpotAxisAt45DegreesInXZ", "A spot light whose axis is at exactly 45 degrees in the XZ plane.", + Perspective(0.89631605f, 1.0262334f, float2.zero, 0.11539972f, 1000f, k_Screen, ClusteringItem.Spot(new float3(0f, 0f, 12.25f), new float3(k_Half, 0f, k_Half), 40f, 90f))); + yield return Case("SpotAxisAlongViewDiagonal", "A spot light whose axis is the view-space diagonal (1, 1, 1).", + Perspective(0.44447416f, 0.85071206f, float2.zero, 0.78974074f, 1000f, k_Screen, ClusteringItem.Spot(new float3(-4.25f, 0.25f, 0f), new float3(k_Diagonal, k_Diagonal, k_Diagonal), 5f, 45f))); + yield return Case("SpotVertexOnNearPlane", "A wide spot light whose vertex lies on the near plane.", + Perspective(0.45082957f, 1.0431756f, float2.zero, 0.8158224f, 1000f, k_Screen, ClusteringItem.Spot(new float3(3f, -0.5f, 0.8158224f), new float3(0f, k_Half, k_Half), 6f, 110f))); + yield return Case("SpotVertexJustBehindNearPlane", "A nearly hemispherical spot light whose vertex lies just behind the near plane.", + Perspective(0.5678351f, 1.0830803f, float2.zero, 0.3802336f, 1000f, k_Screen, ClusteringItem.Spot(new float3(24.75f, -35.25f, 0.37797466f), new float3(k_Half, k_Half, 0f), 55f, 179f))); + yield return Case("SpotWithUnboundedNearPlaneSection", "A spot light whose section with the near plane has no finite extremes.", + Perspective(0.8330596f, 1.219217f, new float2(-0.2787532f, 0.22271621f), 0.50425756f, 1000f, k_Screen, ClusteringItem.Spot(new float3(0f, 0f, 0.25f), new float3(k_Diagonal, k_Diagonal, k_Diagonal), 10f, 109.47122f))); + yield return Case("SpotLightCrossingFarPlane", "A spot light crossing the far plane.", + Perspective(60f, 16f / 9f, 0.3f, 25f, k_Screen, ClusteringItem.Spot(new float3(0.5f, 0.3f, 20f), new float3(0f, 0f, 1f), 15f, 60f))); { - lights.Dispose(); - probes.Dispose(); - zBins.Dispose(); - tileMasks.Dispose(); + var scene = new ClusteringScene { near = 0.54576063f, far = 1000f, screenSize = new int2(160, 90) }; + scene.worldToViews[0] = scene.worldToViews[1] = new float4x4( + new float4(-0.1186f, -0.44585413f, 0.8872137f, 0f), + new float4(0.22589295f, 0.85797536f, 0.46135753f, 0f), + new float4(0.9669056f, -0.25513235f, 0.0010405704f, 0f), + new float4(19.057278f, -13.34542f, -38.808697f, 1f)); + scene.viewToClips[0] = scene.viewToClips[1] = ClusteringScene.Perspective(1.2988923f, 2.8259869f, new float2(0.19827574f, -0.04960227f), scene.near, scene.far); + scene.items.Add(ClusteringItem.Spot(new float3(30.4875f, 25.492296f, -1.2410641f), new float3(-0.11860001f, 0.22589296f, 0.9669056f), 33f, 179f)); + yield return Case("SpotBaseCircleAroundCamera", "A wide spot light whose base circle surrounds the camera in a side view.", scene); } + + yield return Case("ReflectionProbeCrossingFarPlane", "A reflection probe crossing the far plane.", + Perspective(60f, 16f / 9f, 0.3f, 28f, k_Screen, ClusteringItem.Probe(new float3(20f, 0f, 30f), new float3(5f, 5f, 5f), quaternion.identity))); + yield return Case("ReflectionProbeBehindCamera", "A reflection probe entirely behind the camera is in no tile or z-bin.", + Perspective(60f, 16f / 9f, 0.3f, 1000f, k_Screen, ClusteringItem.Probe(new float3(0f, 0f, -5f), new float3(1f, 1f, 1f), quaternion.identity))); + + yield return Case("OrthographicPointLightCentered", "An orthographic point light.", + Orthographic(4f, 4f, 0.5f, 100f, k_SmallScreen, ClusteringItem.Point(new float3(0.3f, 0.2f, 5f), 1.3f))); + yield return Case("OrthographicPointLightOffLeftEdge", "An orthographic point light partly off the left screen edge.", + Orthographic(4f, 4f, 0.5f, 100f, k_SmallScreen, ClusteringItem.Point(new float3(-5f, -3.5f, 5f), 1.1f))); + yield return Case("OrthographicPointLightAtNegativeDepth", "An orthographic point light at negative depth with a negative near plane.", + Orthographic(6f, 6f, -5f, 10f, k_SmallScreen, ClusteringItem.Point(new float3(0f, 0f, -2f), 1f))); + yield return Case("OrthographicPointLightCrossingNearPlane", "An orthographic point light crossing the near plane.", + Orthographic(8f, 4.5f, 1f, 100f, k_Screen, ClusteringItem.Point(new float3(0.5f, 0.3f, 0f), 2f))); + yield return Case("OrthographicSpotOffRightEdge", "An orthographic spot light off the right screen edge.", + Orthographic(0.5184f * 11.7982f, 11.7982f, 0.4803f, 1000f, k_SmallScreen, ClusteringItem.Spot(new float3(6.6041f, 6.1272f, 2.8334f), new float3(-0.4904f, 0.868f, -0.0783f), 2.6565f, 56.2812f))); + yield return Case("OrthographicSpotCrossingNearAndFarPlanes", "An orthographic spot light crossing the near and far planes.", + Orthographic(8f, 4.5f, 1f, 4f, k_Screen, ClusteringItem.Spot(new float3(-3f, 0.3f, -1f), new float3(k_Half, 0f, k_Half), 9f, 60f))); + yield return Case("OrthographicReflectionProbeOnTileBoundaries", "An orthographic axis-aligned reflection probe whose edges lie on tile boundaries.", + Orthographic(4f, 4f, 0.5f, 100f, k_SmallScreen, ClusteringItem.Probe(new float3(0f, 0f, 5f), new float3(1f, 2f, 1f), quaternion.identity))); } - // Identity world-to-view, 90-degree FOV; tiling negates view Z, so view (x, y, z) is world (x, y, -z). - static bool PointLightCoversTile(float3 lightPositionVS, float range, int2 tile) + [TestCaseSource(nameof(ExactScenes))] + public void LightClustering_IsExact(ClusteringScene scene) { - var lights = new NativeArray(1, Allocator.TempJob); - lights[0] = new VisibleLight() - { - lightType = LightType.Point, - finalColor = Color.white, - screenRect = new Rect(0, 0, 1, 1), - localToWorldMatrix = new Matrix4x4( - new Vector4(1, 0, 0, 0), - new Vector4(0, 1, 0, 0), - new Vector4(0, 0, 1, 0), - new Vector4(lightPositionVS.x, lightPositionVS.y, -lightPositionVS.z, 1) - ), - range = range, - spotAngle = 0, - intersectsNearPlane = true, - intersectsFarPlane = false, - }; - var probes = new NativeArray(0, Allocator.TempJob); - var zBins = new NativeArray(UniversalRenderPipeline.maxZBinWords, Allocator.TempJob); - var tileMasks = new NativeArray(UniversalRenderPipeline.maxTileWords, Allocator.TempJob); - - var worldToView = float4x4.identity; - var worldToViews = new Fixed2(worldToView, worldToView); - - const float near = 0.5f; - const float far = 100f; - float p22 = -(far + near) / (far - near); - float p23 = -(2f * far * near) / (far - near); - var viewToClip = new float4x4( - new float4(1, 0, 0, 0), - new float4(0, 1, 0, 0), - new float4(0, 0, p22, -1), - new float4(0, 0, p23, 0) - ); - var viewToClips = new Fixed2(viewToClip, viewToClip); - int2 screenResolution = new(64, 64); - - JobHandle handle = ForwardLights.ScheduleClusteringJobs( - false, true, lights, probes, zBins, tileMasks, - worldToViews, viewToClips, 1, screenResolution, near, far, false, - out _, out _, out _, out _, out _, out int2 tileResolution, out _, out int wordsPerTile); - JobHandle.ScheduleBatchedJobs(); - handle.Complete(); - - int maskIndex = (tile.y * tileResolution.x + tile.x) * wordsPerTile; - bool covered = (tileMasks[maskIndex] & 1u) != 0u; - - lights.Dispose(); - probes.Dispose(); - zBins.Dispose(); - tileMasks.Dispose(); - return covered; + var result = LightClusteringOracle.Check(scene); + if (result.failed) + Assert.Fail($"{result}{scene}"); } - [Description("A point light crossing the near plane covers the tile at its horizon extreme.")] - [UnityPlatform(include = new RuntimePlatform[] { RuntimePlatform.WindowsEditor, RuntimePlatform.WindowsPlayer, RuntimePlatform.OSXEditor, RuntimePlatform.OSXPlayer })] + [Description("The horizon of a projected circle is missing, not a far-away point, when the camera is inside the ellipse.")] [Test] - public void LightClustering_PointLightCrossingNearPlane_CoversHorizonTileInFrontOfNear() + public void LightClustering_ProjectedCircleHorizonAroundCamera_IsMissing() { - Assert.IsTrue( - PointLightCoversTile(new float3(1.6040f, -1.6087f, 0.8924f), 1.2312f, new int2(7, 2)), - "Tile (7,2) is covered by the light volume but is missing from the tile mask."); + // A cone base circle facing the camera sideways, with the camera inside its projection onto the YZ plane. + var found = TilingJob.GetProjectedCircleHorizon(new float2(-4.750001f, 2.279692E-09f), 32.998745f, new float2(1f, 0f), new float2(0f, 1f), out var uv1, out var uv2); + Assert.IsFalse(found, $"Expected no horizon, got {uv1} and {uv2}."); } - [Description("A point light above the frustum covers the edge tile row.")] - [UnityPlatform(include = new RuntimePlatform[] { RuntimePlatform.WindowsEditor, RuntimePlatform.WindowsPlayer, RuntimePlatform.OSXEditor, RuntimePlatform.OSXPlayer })] + [Description("Cone section points are accepted on or inside the cone up to its base, and rejected outside its angle, which degenerate sections can produce.")] [Test] - public void LightClustering_PointLightOutsideFrustumVertically_CoversEdgeRowTile() + public void LightClustering_ConeSectionPointCheck_RejectsPointsOutsideTheCone() { - Assert.IsTrue( - PointLightCoversTile(new float3(-4.4307f, 7.2440f, 5.7363f), 1.9306f, new int2(0, 7)), - "Edge-row tile (0,7) is covered by the light volume but is missing from the tile mask."); + var vertex = new float3(1f, 2f, 3f); + var axis = math.normalize(new float3(0.3f, -0.2f, 1f)); + var halfAngle = math.radians(20f); + var cosHalfAngle = math.cos(halfAngle); + var sinHalfAngle = math.sin(halfAngle); + const float range = 10f; + var coneHeight = range * cosHalfAngle; + var tolerance = 1e-5f * (math.length(vertex) + range); + var side = math.normalize(math.cross(axis, new float3(1f, 0f, 0f))); + bool IsOnCone(float angle, float distance) => + TilingJob.IsOnCone(vertex + (math.cos(angle) * axis + math.sin(angle) * side) * distance, vertex, axis, cosHalfAngle, sinHalfAngle, coneHeight, tolerance); + + Assert.IsTrue(IsOnCone(halfAngle, 5f), "A point on the cone was rejected."); + Assert.IsTrue(IsOnCone(0f, 5f), "A point on the axis was rejected."); + Assert.IsFalse(IsOnCone(halfAngle + math.radians(10f), 5f), "A point outside the cone angle was accepted."); + Assert.IsFalse(IsOnCone(halfAngle, 0.5f * range / cosHalfAngle + range), "A point beyond the cone base was accepted."); + Assert.IsFalse(IsOnCone(math.PI - halfAngle, 5f), "A point on the opposite nappe was accepted."); } - // Identity world-to-view; tiling negates view Z, so view (x, y, z) is world (x, y, -z). - static bool SpotLightCoversTile(float fovYDeg, float aspect, float near, float3 posVS, float3 dirVS, float range, float spotAngle, int2 tile, int2? screenSize = null) + [Description("Clustering into buffers left over from a previous run gives the same result as into cleared buffers.")] + [Test] + public void LightClustering_ReusedBuffers_MatchFreshBuffers() { - var lights = new NativeArray(1, Allocator.TempJob); - lights[0] = new VisibleLight() + var reusedZBins = new NativeArray(UniversalRenderPipeline.maxZBinWords, Allocator.TempJob); + var reusedTileMasks = new NativeArray(UniversalRenderPipeline.maxTileWords, Allocator.TempJob); + var freshZBins = new NativeArray(UniversalRenderPipeline.maxZBinWords, Allocator.TempJob); + var freshTileMasks = new NativeArray(UniversalRenderPipeline.maxTileWords, Allocator.TempJob); + try { - lightType = LightType.Spot, - finalColor = Color.white, - screenRect = new Rect(0, 0, 1, 1), - localToWorldMatrix = new Matrix4x4( - new Vector4(1, 0, 0, 0), - new Vector4(0, 1, 0, 0), - new Vector4(dirVS.x, dirVS.y, -dirVS.z, 0), - new Vector4(posVS.x, posVS.y, -posVS.z, 1) - ), - range = range, - spotAngle = spotAngle, - intersectsNearPlane = true, - intersectsFarPlane = false, - }; - var probes = new NativeArray(0, Allocator.TempJob); - var zBins = new NativeArray(UniversalRenderPipeline.maxZBinWords, Allocator.TempJob); - var tileMasks = new NativeArray(UniversalRenderPipeline.maxTileWords, Allocator.TempJob); - - var worldToView = float4x4.identity; - var worldToViews = new Fixed2(worldToView, worldToView); - - const float far = 1000f; - float p11 = 1f / math.tan(math.radians(fovYDeg) * 0.5f); - float p00 = p11 / aspect; - var viewToClip = new float4x4( - new float4(p00, 0, 0, 0), - new float4(0, p11, 0, 0), - new float4(0, 0, -(far + near) / (far - near), -1), - new float4(0, 0, -(2f * far * near) / (far - near), 0) - ); - var viewToClips = new Fixed2(viewToClip, viewToClip); - int2 screenResolution = screenSize ?? new int2(64, 64); - - JobHandle handle = ForwardLights.ScheduleClusteringJobs( - false, true, lights, probes, zBins, tileMasks, - worldToViews, viewToClips, 1, screenResolution, near, far, false, - out _, out _, out _, out _, out _, out int2 tileResolution, out _, out int wordsPerTile); - JobHandle.ScheduleBatchedJobs(); - handle.Complete(); + for (var i = 0; i < reusedZBins.Length; i++) + { + reusedZBins[i] = 0xFFFFFFFFu; + } + for (var i = 0; i < reusedTileMasks.Length; i++) + { + reusedTileMasks[i] = 0xFFFFFFFFu; + } - int maskIndex = (tile.y * tileResolution.x + tile.x) * wordsPerTile; - bool covered = (tileMasks[maskIndex] & 1u) != 0u; + RunPointLightClustering(new float3(1f, 0.5f, 4f), 1.5f, reusedZBins, reusedTileMasks, out var binCount, out var tileResolution, out var wordsPerTile); + RunPointLightClustering(new float3(1f, 0.5f, 4f), 1.5f, freshZBins, freshTileMasks, out _, out _, out _); - lights.Dispose(); - probes.Dispose(); - zBins.Dispose(); - tileMasks.Dispose(); - return covered; + var zBinWords = binCount * (ZBinningJob.headerLength + wordsPerTile); + var tileWords = tileResolution.x * tileResolution.y * wordsPerTile; + CollectionAssert.AreEqual(freshZBins.GetSubArray(0, zBinWords).ToArray(), reusedZBins.GetSubArray(0, zBinWords).ToArray()); + CollectionAssert.AreEqual(freshTileMasks.GetSubArray(0, tileWords).ToArray(), reusedTileMasks.GetSubArray(0, tileWords).ToArray()); + } + finally + { + reusedZBins.Dispose(); + reusedTileMasks.Dispose(); + freshZBins.Dispose(); + freshTileMasks.Dispose(); + } } - [Description("A spot light in front of the near plane covers a tile inside its cone.")] - [UnityPlatform(include = new RuntimePlatform[] { RuntimePlatform.WindowsEditor, RuntimePlatform.WindowsPlayer, RuntimePlatform.OSXEditor, RuntimePlatform.OSXPlayer })] + [Description("An infinite far plane is treated as the largest finite one, so the light still lands in the z-bins.")] [Test] - public void LightClustering_SpotLightInFrontOfNear_CoversInteriorTile() + public void LightClustering_InfiniteFarPlane_LightIsInZBins() { - Assert.IsTrue( - SpotLightCoversTile(72.032f, 1.3333f, 0.412f, new float3(1.5852f, -1.4977f, 6.9015f), new float3(-0.1672f, -0.2562f, 0.9520f), 2.227f, 75.974f, new int2(4, 2)), - "Spot cone covers tile (4,2) but it is missing from the tile mask."); - } + var zBins = new NativeArray(UniversalRenderPipeline.maxZBinWords, Allocator.TempJob); + var tileMasks = new NativeArray(UniversalRenderPipeline.maxTileWords, Allocator.TempJob); + try + { + RunPointLightClustering(new float3(1f, 0.5f, 4f), 1.5f, zBins, tileMasks, out var binCount, out _, out var wordsPerTile, float.PositiveInfinity); - [Description("A spot light crossing the near plane covers a tile inside its cone.")] - [UnityPlatform(include = new RuntimePlatform[] { RuntimePlatform.WindowsEditor, RuntimePlatform.WindowsPlayer, RuntimePlatform.OSXEditor, RuntimePlatform.OSXPlayer })] - [Test] - public void LightClustering_SpotLightCrossingNear_CoversInteriorTile() - { - Assert.IsTrue( - SpotLightCoversTile(58.880f, 1.3333f, 0.461f, new float3(0.4470f, 1.0636f, 1.4462f), new float3(0.0110f, -0.1210f, 0.9926f), 2.017f, 112.675f, new int2(4, 6)), - "Spot cone covers tile (4,6) but it is missing from the tile mask."); + var binsWithLight = 0; + for (var bin = 0; bin < binCount; bin++) + { + if ((zBins[bin * (ZBinningJob.headerLength + wordsPerTile) + ZBinningJob.headerLength] & 1u) != 0) + binsWithLight++; + } + Assert.Greater(binsWithLight, 0, $"The light is missing from all {binCount} z-bins."); + } + finally + { + zBins.Dispose(); + tileMasks.Dispose(); + } } - [Description("A spot light whose vertex lies in the camera plane covers the tiles along both sides of its cone.")] - [UnityPlatform(include = new RuntimePlatform[] { RuntimePlatform.WindowsEditor, RuntimePlatform.WindowsPlayer, RuntimePlatform.OSXEditor, RuntimePlatform.OSXPlayer })] + [Description("Lights and probes without a volume (zero range, spot angle or extents) are in no tile or z-bin.")] [Test] - public void LightClustering_SpotVertexInCameraPlane_CoversConeSideTiles() + public void LightClustering_ItemsWithoutVolume_AreSkipped() { - var posVS = new float3(-4.8e-7f, -0.2f, 0f); - var dirVS = new float3(3.7e-9f, 0f, 1f); - var screenSize = new int2(480, 270); - Assert.IsTrue( - SpotLightCoversTile(60f, 16f / 9f, 0.3f, posVS, dirVS, 50f, 55f, new int2(16, 6), screenSize), - "Spot cone covers tile (16,6) but it is missing from the tile mask."); - Assert.IsTrue( - SpotLightCoversTile(60f, 16f / 9f, 0.3f, posVS, dirVS, 50f, 55f, new int2(43, 6), screenSize), - "Spot cone covers tile (43,6) but it is missing from the tile mask."); + var lights = new NativeArray(2, Allocator.TempJob); + var probes = new NativeArray(1, Allocator.TempJob); + var zBins = new NativeArray(UniversalRenderPipeline.maxZBinWords, Allocator.TempJob); + var tileMasks = new NativeArray(UniversalRenderPipeline.maxTileWords, Allocator.TempJob); + try + { + // View space (x, y, z) is world (x, y, -z) under an identity world-to-view matrix. + lights[0] = new VisibleLight + { + lightType = LightType.Point, + finalColor = Color.white, + screenRect = new Rect(0, 0, 1, 1), + localToWorldMatrix = Matrix4x4.Translate(new Vector3(0f, 0f, -5f)), + range = 0f, + }; + lights[1] = new VisibleLight + { + lightType = LightType.Spot, + finalColor = Color.white, + screenRect = new Rect(0, 0, 1, 1), + localToWorldMatrix = Matrix4x4.TRS(new Vector3(0f, 0f, -2f), Quaternion.LookRotation(Vector3.back), Vector3.one), + range = 5f, + spotAngle = 0f, + }; + probes[0] = new VisibleReflectionProbe + { + bounds = new Bounds(new Vector3(1f, 0f, -4f), Vector3.zero), + localToWorldMatrix = Matrix4x4.Translate(new Vector3(1f, 0f, -4f)), + }; + var worldToViews = new Fixed2(float4x4.identity, float4x4.identity); + var viewToClip = float4x4.PerspectiveFov(math.radians(90f), 1f, 0.5f, 100f); + var viewToClips = new Fixed2(viewToClip, viewToClip); + + ForwardLights.ScheduleClusteringJobs( + false, true, lights, probes, zBins, tileMasks, + worldToViews, viewToClips, 1, new int2(64, 64), 0.5f, 100f, false, + out _, out _, out var binCount, out _, out _, out var tileResolution, out _, out var wordsPerTile).Complete(); + + for (var bin = 0; bin < binCount; bin++) + { + for (var word = 0; word < wordsPerTile; word++) + Assert.AreEqual(0u, zBins[bin * (ZBinningJob.headerLength + wordsPerTile) + ZBinningJob.headerLength + word], $"z-bin {bin} holds an item."); + } + for (var i = 0; i < tileResolution.x * tileResolution.y * wordsPerTile; i++) + Assert.AreEqual(0u, tileMasks[i], $"Tile word {i} holds an item."); + } + finally + { + lights.Dispose(); + probes.Dispose(); + zBins.Dispose(); + tileMasks.Dispose(); + } } - [Description("A spot light whose silhouette leaves the screen does not cover the edge column.")] - [UnityPlatform(include = new RuntimePlatform[] { RuntimePlatform.WindowsEditor, RuntimePlatform.WindowsPlayer, RuntimePlatform.OSXEditor, RuntimePlatform.OSXPlayer })] + [Description("A light beyond the supported view distance is in no tile or z-bin, and a light with a huge range around the camera is in all of them.")] [Test] - public void LightClustering_SpotSilhouetteOffScreenEdge_DoesNotOverCoverEdgeColumn() - { - Assert.IsFalse( - SpotLightCoversTile(86.3651f, 0.9666f, 0.3570f, new float3(-0.0080f, -0.1112f, -2.0052f), new float3(-0.9652f, -0.1627f, 0.2046f), 4.0016f, 66.8309f, new int2(0, 1)), - "Edge-column tile (0,1) is outside the spot cone but was marked (edge over-coverage)."); - } - - // Orthographic camera; half-width = aspect * orthoHalfHeight. - static bool OrthoSpotLightCoversTile(float orthoHalfHeight, float aspect, float near, float3 posVS, float3 dirVS, float range, float spotAngle, int2 tile) + public void LightClustering_DistantAndHugeLights_StayBounded() { - var lights = new NativeArray(1, Allocator.TempJob); - lights[0] = new VisibleLight() - { - lightType = LightType.Spot, - finalColor = Color.white, - screenRect = new Rect(0, 0, 1, 1), - localToWorldMatrix = new Matrix4x4( - new Vector4(1, 0, 0, 0), - new Vector4(0, 1, 0, 0), - new Vector4(dirVS.x, dirVS.y, -dirVS.z, 0), - new Vector4(posVS.x, posVS.y, -posVS.z, 1) - ), - range = range, - spotAngle = spotAngle, - intersectsNearPlane = true, - intersectsFarPlane = false, - }; - var probes = new NativeArray(0, Allocator.TempJob); + var lights = new NativeArray(2, Allocator.TempJob); var zBins = new NativeArray(UniversalRenderPipeline.maxZBinWords, Allocator.TempJob); var tileMasks = new NativeArray(UniversalRenderPipeline.maxTileWords, Allocator.TempJob); + try + { + lights[0] = PointLightAtView(new float3(0f, 0f, 5e9f), 1000f); + lights[1] = PointLightAtView(new float3(0f, 0f, 2f), 1e20f); + ClusterLights(lights, 1e12f, zBins, tileMasks, out var binCount, out var tileResolution, out var wordsPerTile); - var worldToView = float4x4.identity; - var worldToViews = new Fixed2(worldToView, worldToView); - - const float far = 1000f; - float p00 = 1f / (aspect * orthoHalfHeight); - float p11 = 1f / orthoHalfHeight; - var viewToClip = new float4x4( - new float4(p00, 0, 0, 0), - new float4(0, p11, 0, 0), - new float4(0, 0, -2f / (far - near), 0), - new float4(0, 0, -(far + near) / (far - near), 1) - ); - var viewToClips = new Fixed2(viewToClip, viewToClip); - int2 screenResolution = new(64, 64); - - JobHandle handle = ForwardLights.ScheduleClusteringJobs( - false, true, lights, probes, zBins, tileMasks, - worldToViews, viewToClips, 1, screenResolution, near, far, true, - out _, out _, out _, out _, out _, out int2 tileResolution, out _, out int wordsPerTile); - JobHandle.ScheduleBatchedJobs(); - handle.Complete(); - - int maskIndex = (tile.y * tileResolution.x + tile.x) * wordsPerTile; - bool covered = (tileMasks[maskIndex] & 1u) != 0u; - - lights.Dispose(); - probes.Dispose(); - zBins.Dispose(); - tileMasks.Dispose(); - return covered; + for (var bin = 0; bin < binCount; bin++) + { + var word = zBins[bin * (ZBinningJob.headerLength + wordsPerTile) + ZBinningJob.headerLength]; + Assert.AreEqual(0u, word & 1u, $"The distant light is in z-bin {bin}."); + Assert.AreEqual(2u, word & 2u, $"The huge light is missing from z-bin {bin}."); + } + for (var tile = 0; tile < tileResolution.x * tileResolution.y; tile++) + { + var word = tileMasks[tile * wordsPerTile]; + Assert.AreEqual(0u, word & 1u, $"The distant light is in tile {tile}."); + Assert.AreEqual(2u, word & 2u, $"The huge light is missing from tile {tile}."); + } + } + finally + { + lights.Dispose(); + zBins.Dispose(); + tileMasks.Dispose(); + } } - [Description("An orthographic spot light off the right screen edge covers the edge tile.")] - [UnityPlatform(include = new RuntimePlatform[] { RuntimePlatform.WindowsEditor, RuntimePlatform.WindowsPlayer, RuntimePlatform.OSXEditor, RuntimePlatform.OSXPlayer })] + [Description("A light with a non-finite position, e.g. from a broken transform, is in no z-bin.")] [Test] - public void LightClustering_OrthographicSpotOffRightEdge_CoversEdgeTile() - { - Assert.IsTrue( - OrthoSpotLightCoversTile(11.7982f, 0.5184f, 0.4803f, new float3(6.6041f, 6.1272f, 2.8334f), new float3(-0.4904f, 0.868f, -0.0783f), 2.6565f, 56.2812f, new int2(7, 6)), - "Orthographic spot covers tile (7,6) but it is missing from the tile mask."); - } - - // Orthographic camera; returns whether the z-bin at view depth viewZ contains the light. - static bool OrthoPointLightCoversZBinAtDepth(float3 lightPositionVS, float range, float near, float far, float viewZ) + public void LightClustering_NonFiniteLightPosition_IsInNoZBin() { var lights = new NativeArray(1, Allocator.TempJob); - lights[0] = new VisibleLight() - { - lightType = LightType.Point, - finalColor = Color.white, - screenRect = new Rect(0, 0, 1, 1), - localToWorldMatrix = new Matrix4x4( - new Vector4(1, 0, 0, 0), - new Vector4(0, 1, 0, 0), - new Vector4(0, 0, 1, 0), - new Vector4(lightPositionVS.x, lightPositionVS.y, -lightPositionVS.z, 1) - ), - range = range, - spotAngle = 0, - intersectsNearPlane = true, - intersectsFarPlane = false, - }; - var probes = new NativeArray(0, Allocator.TempJob); var zBins = new NativeArray(UniversalRenderPipeline.maxZBinWords, Allocator.TempJob); var tileMasks = new NativeArray(UniversalRenderPipeline.maxTileWords, Allocator.TempJob); + try + { + lights[0] = PointLightAtView(new float3(0f, 0f, float.NaN), 2f); + ClusterLights(lights, 100f, zBins, tileMasks, out var binCount, out _, out var wordsPerTile); - var worldToView = float4x4.identity; - var worldToViews = new Fixed2(worldToView, worldToView); - - // Only the half-size and center terms are read by the tiling setup. - const float halfSize = 6f; - var viewToClip = new float4x4( - new float4(1f / halfSize, 0, 0, 0), - new float4(0, 1f / halfSize, 0, 0), - new float4(0, 0, -2f / (far - near), 0), - new float4(0, 0, -(far + near) / (far - near), 1) - ); - var viewToClips = new Fixed2(viewToClip, viewToClip); - int2 screenResolution = new(64, 64); - - JobHandle handle = ForwardLights.ScheduleClusteringJobs( - false, true, lights, probes, zBins, tileMasks, - worldToViews, viewToClips, 1, screenResolution, near, far, true, - out _, out _, out _, out float zBinScale, out float zBinOffset, out _, out _, out int wordsPerTile); - JobHandle.ScheduleBatchedJobs(); - handle.Complete(); - - // Orthographic z-bin index is linear in view-space Z (matches the shader). - int binIndex = (int)(viewZ * zBinScale + zBinOffset); - int stride = 2 + wordsPerTile; // 2 header words + bitmask words - bool covered = (zBins[binIndex * stride + 2] & 1u) != 0u; - - lights.Dispose(); - probes.Dispose(); - zBins.Dispose(); - tileMasks.Dispose(); - return covered; + for (var bin = 0; bin < binCount; bin++) + Assert.AreEqual(0u, zBins[bin * (ZBinningJob.headerLength + wordsPerTile) + ZBinningJob.headerLength], $"z-bin {bin} holds the light."); + } + finally + { + lights.Dispose(); + zBins.Dispose(); + tileMasks.Dispose(); + } } - [Description("With a negative orthographic near plane, a light at negative depth is in its z-bin.")] - [UnityPlatform(include = new RuntimePlatform[] { RuntimePlatform.WindowsEditor, RuntimePlatform.WindowsPlayer, RuntimePlatform.OSXEditor, RuntimePlatform.OSXPlayer })] - [Test] - public void LightClustering_OrthographicNegativeNearPlane_PointLightCoversZBinAtItsDepth() + // View space (x, y, z) is world (x, y, -z) under the identity world-to-view matrix of ClusterLights. + static VisibleLight PointLightAtView(float3 positionVS, float range) => new VisibleLight { - Assert.IsTrue( - OrthoPointLightCoversZBinAtDepth(new float3(0f, 0f, -2f), 1f, -5f, 10f, -2f), - "Light at view-space Z -2 is missing from the z-bin at depth -2 (negative near plane)."); - } + lightType = LightType.Point, + finalColor = Color.white, + screenRect = new Rect(0, 0, 1, 1), + localToWorldMatrix = Matrix4x4.Translate(new Vector3(positionVS.x, positionVS.y, -positionVS.z)), + range = range, + }; - // Identity world-to-view, 64x64 screen (8x8 tiles), square view plane of half-size halfSize (at Z=1 for - // perspective); tiling negates view Z, so view (x, y, z) is world (x, y, -z). Returns item 0's tile coverage. - static bool[,] ComputeTileCoverage(NativeArray lights, NativeArray probes, bool orthographic, float halfSize) + static void ClusterLights(NativeArray lights, float farPlane, NativeArray zBins, NativeArray tileMasks, out int binCount, out int2 tileResolution, out int wordsPerTile) { - var zBins = new NativeArray(UniversalRenderPipeline.maxZBinWords, Allocator.TempJob); - var tileMasks = new NativeArray(UniversalRenderPipeline.maxTileWords, Allocator.TempJob); + var probes = new NativeArray(0, Allocator.TempJob); var worldToViews = new Fixed2(float4x4.identity, float4x4.identity); - - const float near = 0.5f; - const float far = 100f; - var viewToClip = orthographic - ? new float4x4( - new float4(1f / halfSize, 0, 0, 0), - new float4(0, 1f / halfSize, 0, 0), - new float4(0, 0, -2f / (far - near), 0), - new float4(0, 0, -(far + near) / (far - near), 1)) - : new float4x4( - new float4(1f / halfSize, 0, 0, 0), - new float4(0, 1f / halfSize, 0, 0), - new float4(0, 0, -(far + near) / (far - near), -1), - new float4(0, 0, -(2f * far * near) / (far - near), 0)); + var viewToClip = float4x4.PerspectiveFov(math.radians(90f), 1f, 0.5f, math.min(farPlane, 1e6f)); var viewToClips = new Fixed2(viewToClip, viewToClip); - JobHandle handle = ForwardLights.ScheduleClusteringJobs( + ForwardLights.ScheduleClusteringJobs( false, true, lights, probes, zBins, tileMasks, - worldToViews, viewToClips, 1, new int2(64, 64), near, far, orthographic, - out _, out _, out _, out _, out _, out int2 tileResolution, out _, out int wordsPerTile); - JobHandle.ScheduleBatchedJobs(); - handle.Complete(); - - var coverage = new bool[tileResolution.x, tileResolution.y]; - for (var y = 0; y < tileResolution.y; y++) - for (var x = 0; x < tileResolution.x; x++) - coverage[x, y] = (tileMasks[(y * tileResolution.x + x) * wordsPerTile] & 1u) != 0u; - - zBins.Dispose(); - tileMasks.Dispose(); - return coverage; + worldToViews, viewToClips, 1, new int2(64, 64), 0.5f, farPlane, false, + out _, out _, out binCount, out _, out _, out tileResolution, out _, out wordsPerTile).Complete(); + + probes.Dispose(); } - static bool[,] ComputePointLightTileCoverage(float3 lightPositionVS, float range, bool orthographic, float halfSize) + static void RunPointLightClustering(float3 lightPositionVS, float range, NativeArray zBins, NativeArray tileMasks, out int binCount, out int2 tileResolution, out int wordsPerTile, float farClipPlane = 100f) { var lights = new NativeArray(1, Allocator.TempJob); lights[0] = new VisibleLight() @@ -479,138 +370,39 @@ public void LightClustering_OrthographicNegativeNearPlane_PointLightCoversZBinAt screenRect = new Rect(0, 0, 1, 1), localToWorldMatrix = Matrix4x4.Translate(new Vector3(lightPositionVS.x, lightPositionVS.y, -lightPositionVS.z)), range = range, - spotAngle = 0, - intersectsNearPlane = false, - intersectsFarPlane = false, }; var probes = new NativeArray(0, Allocator.TempJob); - try - { - return ComputeTileCoverage(lights, probes, orthographic, halfSize); - } - finally - { - lights.Dispose(); - probes.Dispose(); - } - } - - static string FormatTiles(List tiles) => string.Join(", ", tiles.ConvertAll(t => $"({t.x},{t.y})")); - - // The orthographic footprint of a point light is a disk, so the exact set of tiles it overlaps is known. - [Description("An orthographic point light covers exactly the tiles its disk overlaps.")] - [UnityPlatform(include = new RuntimePlatform[] { RuntimePlatform.WindowsEditor, RuntimePlatform.WindowsPlayer, RuntimePlatform.OSXEditor, RuntimePlatform.OSXPlayer })] - [TestCase(0.3f, 0.2f, 1.3f, TestName = "LightClustering_OrthographicPointLight_CoversExactlyItsDiskTiles(Centered)")] - [TestCase(-5f, -3.5f, 1.1f, TestName = "LightClustering_OrthographicPointLight_CoversExactlyItsDiskTiles(OffLeftEdge)")] - public void LightClustering_OrthographicPointLight_CoversExactlyItsDiskTiles(float x, float y, float range) - { - const float halfSize = 4f; - var coverage = ComputePointLightTileCoverage(new float3(x, y, 5f), range, true, halfSize); - - // A tile the disk only touches (zero-area overlap) may go either way, depending on float rounding. - const float tangentTolerance = 1e-4f; - var tileSize = 2f * halfSize / coverage.GetLength(0); - var missing = new List(); - var extra = new List(); - for (var ty = 0; ty < coverage.GetLength(1); ty++) - { - for (var tx = 0; tx < coverage.GetLength(0); tx++) - { - var tileMin = -halfSize + tileSize * new float2(tx, ty); - var closest = math.clamp(new float2(x, y), tileMin, tileMin + tileSize); - var distance = math.distance(closest, new float2(x, y)); - if (distance < range - tangentTolerance && !coverage[tx, ty]) missing.Add(new int2(tx, ty)); - if (distance > range + tangentTolerance && coverage[tx, ty]) extra.Add(new int2(tx, ty)); - } - } - - Assert.IsEmpty(missing, $"Tiles overlapped by the light are not covered: {FormatTiles(missing)}"); - Assert.IsEmpty(extra, $"Tiles outside the light are covered: {FormatTiles(extra)}"); - } - - [Description("A perspective point light covers no tile outside its projected screen-space bounds.")] - [UnityPlatform(include = new RuntimePlatform[] { RuntimePlatform.WindowsEditor, RuntimePlatform.WindowsPlayer, RuntimePlatform.OSXEditor, RuntimePlatform.OSXPlayer })] - [Test] - public void LightClustering_PerspectivePointLight_CoversNoTileOutsideItsProjectedBounds() - { - const float halfSize = 1f; - var position = new float3(0.3f, 0.2f, 5f); - const float range = 1.3f; - var coverage = ComputePointLightTileCoverage(position, range, false, halfSize); - - // Tangent lines from the eye bound the sphere's projection on each axis. - float2 ProjectedTileBounds(float lateral, float tileCount) - { - var angle = math.atan2(lateral, position.z); - var halfAngle = math.asin(range / math.length(new float2(lateral, position.z))); - var ndc = math.tan(new float2(angle - halfAngle, angle + halfAngle)) / halfSize; - return math.floor((ndc * 0.5f + 0.5f) * tileCount); - } - var boundsX = ProjectedTileBounds(position.x, coverage.GetLength(0)); - var boundsY = ProjectedTileBounds(position.y, coverage.GetLength(1)); + var worldToViews = new Fixed2(float4x4.identity, float4x4.identity); + var viewToClip = float4x4.PerspectiveFov(math.radians(90f), 1f, 0.5f, 100f); + var viewToClips = new Fixed2(viewToClip, viewToClip); - var extra = new List(); - for (var ty = 0; ty < coverage.GetLength(1); ty++) - for (var tx = 0; tx < coverage.GetLength(0); tx++) - if (coverage[tx, ty] && (tx < boundsX.x || tx > boundsX.y || ty < boundsY.x || ty > boundsY.y)) - extra.Add(new int2(tx, ty)); + ForwardLights.ScheduleClusteringJobs( + false, true, lights, probes, zBins, tileMasks, + worldToViews, viewToClips, 1, new int2(64, 64), 0.5f, farClipPlane, false, + out _, out _, out binCount, out _, out _, out tileResolution, out _, out wordsPerTile).Complete(); - Assert.IsTrue(coverage[4, 4], "The tile containing the light center is not covered."); - Assert.IsEmpty(extra, $"Tiles outside the light's projected bounds are covered: {FormatTiles(extra)}"); + lights.Dispose(); + probes.Dispose(); } - // Horizontal hull edges lying exactly on tile row boundaries hit the 0/0 case of the edge-plane intersection. - [Description("An orthographic axis-aligned reflection probe with edges on tile boundaries covers no tile outside its bounds.")] - [UnityPlatform(include = new RuntimePlatform[] { RuntimePlatform.WindowsEditor, RuntimePlatform.WindowsPlayer, RuntimePlatform.OSXEditor, RuntimePlatform.OSXPlayer })] + [Description("Randomized check of light clustering on scenes biased towards degenerate configurations. The scenes depend on floating-point math that can differ between platforms, so this is not deterministic and is run manually. Configure it with URP_LIGHT_CLUSTERING_FUZZ_COUNT, URP_LIGHT_CLUSTERING_FUZZ_SEED and URP_LIGHT_CLUSTERING_FUZZ_MAX_ITEMS.")] + [Explicit("Randomized and not deterministic across platforms; run manually.")] [Test] - public void LightClustering_OrthographicReflectionProbeOnTileBoundaries_CoversNoTileOutsideItsBounds() + public void LightClustering_RandomScenes_AreExact() { - const float halfSize = 4f; - var center = new float3(0f, 0f, 5f); - var extents = new float3(1f, 2f, 1f); - - var lights = new NativeArray(0, Allocator.TempJob); - var probes = new NativeArray(1, Allocator.TempJob); - probes[0] = new VisibleReflectionProbe() - { - bounds = new Bounds(new Vector3(center.x, center.y, -center.z), 2f * (Vector3)extents), - localToWorldMatrix = Matrix4x4.Translate(new Vector3(center.x, center.y, -center.z)), - }; - bool[,] coverage; - try - { - coverage = ComputeTileCoverage(lights, probes, true, halfSize); - } - finally + static int Read(string name, int fallback) => int.TryParse(Environment.GetEnvironmentVariable(name), out var value) ? value : fallback; + var seed = (uint)Read("URP_LIGHT_CLUSTERING_FUZZ_SEED", 1); + var count = Read("URP_LIGHT_CLUSTERING_FUZZ_COUNT", 1000); + var maxItems = Read("URP_LIGHT_CLUSTERING_FUZZ_MAX_ITEMS", 40); + var screenSizes = new[] { new int2(160, 90), new int2(250, 141), new int2(97, 203), new int2(64, 64) }; + var rng = new Unity.Mathematics.Random(seed); + for (var i = 0; i < count; i++) { - lights.Dispose(); - probes.Dispose(); + var scene = LightClusteringOracle.RandomScene(ref rng, screenSizes[i % screenSizes.Length], maxItems); + var result = LightClusteringOracle.Check(scene); + if (result.failed) + Assert.Fail($"Scene {i} (seed {seed}, max items {maxItems}):\n{result}{scene}"); } - - // Closed bounds: a tile that only touches the probe along a tile boundary may be covered. - var tileCount = new float2(coverage.GetLength(0), coverage.GetLength(1)); - var boundsMin = math.ceil(((center.xy - extents.xy) / halfSize * 0.5f + 0.5f) * tileCount) - 1f; - var boundsMax = math.floor(((center.xy + extents.xy) / halfSize * 0.5f + 0.5f) * tileCount); - - var extra = new List(); - for (var ty = 0; ty < coverage.GetLength(1); ty++) - for (var tx = 0; tx < coverage.GetLength(0); tx++) - if (coverage[tx, ty] && (tx < boundsMin.x || tx > boundsMax.x || ty < boundsMin.y || ty > boundsMax.y)) - extra.Add(new int2(tx, ty)); - - Assert.IsTrue(coverage[3, 3], "A tile inside the probe is not covered."); - Assert.IsEmpty(extra, $"Tiles outside the probe bounds are covered: {FormatTiles(extra)}"); } - - static readonly uint[] expectedZBins1 = - { - 0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,0,65535,1,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,65535,65535,0,0 - }; - - static readonly uint[] expectedTileMasks1 = - { - 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 - }; - } } diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/RealBackbufferMSAATests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/RealBackbufferMSAATests.cs index 7b7f9c3dd19..73ba225c6e3 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/RealBackbufferMSAATests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/RealBackbufferMSAATests.cs @@ -74,9 +74,9 @@ public void OneTimeSetUp() if (UniversalRenderer.PlatformRequiresExplicitMsaaResolve()) IgnoreWithLog("Platform resolves MSAA explicitly (no multisampled back buffer); the real back buffer MSAA request is always 1, so there is nothing to test here."); - // Under XR, URP renders into the XR-owned back buffer and never multisamples it directly, so the - // optimization is inactive. A global gate (rather than URP's per-camera xr.enabled check) is enough - // to skip the device XR and mock-XR jobs, where the fixture is meaningless. + // Under XR, the cameras here render into the XR eye textures, not the real back buffer, so this + // fixture's checks don't apply (XRDisplayMSAATests covers the eye textures). A global gate (rather + // than URP's per-camera xr.enabled check) is enough to skip the device XR and mock-XR jobs. if (XRSystem.displayActive || XRGraphicsAutomatedTests.enabled) IgnoreWithLog("XR is active; URP renders into the XR-owned back buffer and never multisamples it directly, so there is nothing to test here."); @@ -278,6 +278,31 @@ public IEnumerator TileOnly_DirectCamera_KeepsMSAA() } } + [UnityTest] + public IEnumerator TileOnlyDeferred_DirectCamera_KeepsMSAA_FallsBackToForward() + { + // Tile-only Deferred doesn't support MSAA, but must still request it so the renderer falls back to Forward instead of silently dropping MSAA. + m_RendererData.renderingMode = RenderingMode.Deferred; + m_RendererData.tileOnlyMode = true; + try + { + CreateScreenCamera(intermediate: false); + + yield return null; + var renderer = m_Asset.GetRenderer(0) as UniversalRenderer; + if (renderer == null || !renderer.useTileOnlyMode) + Assert.Ignore("Tile-only mode is not active on this platform."); + + yield return SettleAndAssert(needsRealBackbufferMSAA: true); + Assert.AreEqual(RenderingMode.Forward, renderer.renderingModeActual, "Tile-only Deferred with MSAA should fall back to Forward."); + } + finally + { + m_RendererData.renderingMode = RenderingMode.Forward; + m_RendererData.tileOnlyMode = false; + } + } + [UnityTest] public IEnumerator RenderRequest_DoesNotChangeBackbufferMSAA() { diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/RenderGraphConstraintsTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/RenderGraphConstraintsTests.cs index 11cbe5ca4e0..21766e54b97 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/RenderGraphConstraintsTests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/RenderGraphConstraintsTests.cs @@ -340,6 +340,10 @@ public IEnumerator RenderTextureCameraDoesNotTriggerOnTileValidation() [UnityTest] public IEnumerator PreviewCameraDoesNotTriggerOnTileValidation() { + if (Application.platform == RuntimePlatform.WindowsEditor && SystemInfo.graphicsDeviceType == GraphicsDeviceType.Direct3D12 + && System.Array.Exists(System.Environment.GetCommandLineArgs(), arg => arg.Equals("-force-ugk", StringComparison.OrdinalIgnoreCase))) + Assert.Ignore("https://jira.unity3d.com/browse/UUM-161913"); + var renderTexture = new RenderTexture(256, 256, 24); var gameObject = new GameObject(); var camera = gameObject.AddComponent(); 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 63600c891ba..ee896c6396e 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/RuntimeTests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/RuntimeTests.cs @@ -17,6 +17,8 @@ class RuntimeTests RenderTexture m_Destination; GameObject m_TargetLight; GameObject m_AnotherLight; + UniversalRenderPipelineAsset m_TestAsset; + UniversalRendererData m_TestRendererData; [SetUp] public void Setup() @@ -41,6 +43,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; + } } static readonly (int tier, string textTier)[] k_ShadowResolutions = @@ -123,6 +135,99 @@ public IEnumerator PipelineHasCorrectColorSpace() "GraphicsSettings.lightsUseLinearIntensity must match active color space."); } + [UnityTest] + public IEnumerator RenderRequest_WithCubemapDestination_RendersIntoRequestedFace( + [Values] bool useSingleCameraRequest, + [Values] bool destinationHasDepth) + { + AssetCheck(); + + if ((SystemInfo.copyTextureSupport & CopyTextureSupport.DifferentTypes) == 0) + Assert.Ignore("Render requests into a cubemap require CopyTextureSupport.DifferentTypes."); + + // The active quality level can use a debug renderer that overwrites the camera color + m_TestRendererData = ScriptableObject.CreateInstance(); + m_TestRendererData.renderingMode = RenderingMode.Forward; + m_TestAsset = ScriptableObject.CreateInstance(); + m_TestAsset.m_RendererDataList[0] = m_TestRendererData; + QualitySettings.renderPipeline = m_TestAsset; + yield return null; + Assert.AreSame(m_TestAsset, GraphicsSettings.currentRenderPipeline, "The test URP asset is not active."); + + camera.clearFlags = CameraClearFlags.SolidColor; + camera.backgroundColor = Color.red; + camera.cullingMask = 0; + + var depthStencilFormat = destinationHasDepth + ? CoreUtils.GetDefaultDepthStencilFormat() + : UnityEngine.Experimental.Rendering.GraphicsFormat.None; + m_Destination = new RenderTexture(64, 64, UnityEngine.Experimental.Rendering.GraphicsFormat.R8G8B8A8_UNorm, + depthStencilFormat) + { + dimension = TextureDimension.Cube + }; + m_Destination.Create(); + + if (useSingleCameraRequest) + { + RenderPipeline.SubmitRenderRequest(camera, new UniversalRenderPipeline.SingleCameraRequest + { + destination = m_Destination, + face = CubemapFace.PositiveX + }); + } + else + { + RenderPipeline.SubmitRenderRequest(camera, new RenderPipeline.StandardRequest + { + destination = m_Destination, + face = CubemapFace.PositiveX + }); + } + yield return null; + + var faceCopy = new RenderTexture(m_Destination.width, m_Destination.height, 0, m_Destination.graphicsFormat); + Texture2D readback = null; + var previousActive = RenderTexture.active; + try + { + Graphics.CopyTexture(m_Destination, (int)CubemapFace.PositiveX, 0, faceCopy, 0, 0); + + int centerX = faceCopy.width / 2; + int centerY = faceCopy.height / 2; + Color pixel; + + // ReadPixels does not work on WebGPU when the browser lacks JSPI + if (SystemInfo.supportsAsyncGPUReadback) + { + var request = AsyncGPUReadback.Request(faceCopy, 0, TextureFormat.RGBA32); + while (!request.done) + yield return null; + + Assert.IsFalse(request.hasError, "AsyncGPUReadback of the requested cubemap face failed."); + pixel = request.GetData()[centerY * faceCopy.width + centerX]; + } + else + { + readback = new Texture2D(faceCopy.width, faceCopy.height, TextureFormat.RGBA32, false); + RenderTexture.active = faceCopy; + readback.ReadPixels(new Rect(0, 0, faceCopy.width, faceCopy.height), 0, 0); + readback.Apply(); + pixel = readback.GetPixel(centerX, centerY); + } + + Assert.Greater(pixel.r, 0.9f, $"The requested cubemap face does not contain the camera rendering. Pixel: {pixel}"); + } + finally + { + RenderTexture.active = previousActive; + faceCopy.Release(); + Object.DestroyImmediate(faceCopy); + if (readback != null) + Object.DestroyImmediate(readback); + } + } + // When switching to URP it sets "UniversalPipeline" as global shader tag. // When switching to Built-in it sets "" as global shader tag. #if UNITY_EDITOR // TODO This API call does not reset in player diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/ShadowCaster2DSpriteSkinFlipTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/ShadowCaster2DSpriteSkinFlipTests.cs new file mode 100644 index 00000000000..d3fc02c2a69 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/ShadowCaster2DSpriteSkinFlipTests.cs @@ -0,0 +1,416 @@ +#if U2D_ANIMATION_INSTALLED && UNITY_EDITOR +using System.Collections; +using NUnit.Framework; +using Unity.Collections; +using UnityEngine.Experimental.Rendering; +using UnityEngine.TestTools; +using UnityEngine.U2D; +using UnityEngine.U2D.Animation; + +namespace UnityEngine.Rendering.Universal.Tests +{ + // UUM-159819: with GPU skinning, a flipped Sprite Skin and its Shadow Caster 2D shadow drifted + // apart while the bones were posed. The sprite shaders flipped before GPU skinning, but the + // shadow paths skin first and then flip, and F*R(a) == R(-a)*F. + // + // SelfShadowSilhouette_MatchesSprite draws one GPU-skinned SpriteRenderer twice with + // DrawRenderer, the way URP does: once with a built-in sprite shader pass, and once with the + // "Self" caster pass of Hidden/Shadow2D (the pass ShadowRendering.RenderSpriteShadow uses). + // The two silhouettes must cover the same pixels. + // + // FlippedSprite_IsMirrorOfUnflippedSprite checks that the result is also right, not only + // consistent: a flipped, posed sprite must be the mirror image of the same sprite unflipped. + // That is what CPU skinning and the CPU-outline projected shadow produce. + class ShadowCaster2DSpriteSkinFlipTests : IPrebuildSetup, IPostBuildCleanup + { + public enum SpriteShader + { + Unlit, + Lit, + } + + public struct Case + { + public SpriteShader shader; + public bool flipX; + public bool flipY; + public float boneAngle; + + public override string ToString() => $"{shader},flipX={flipX},flipY={flipY},bone={boneAngle}"; + } + + static readonly Case[] k_ShadowCases = + { + new Case { shader = SpriteShader.Unlit, flipX = false, flipY = false, boneAngle = 30f }, + new Case { shader = SpriteShader.Unlit, flipX = true, flipY = false, boneAngle = 0f }, + new Case { shader = SpriteShader.Unlit, flipX = true, flipY = false, boneAngle = 30f }, + new Case { shader = SpriteShader.Unlit, flipX = false, flipY = true, boneAngle = 30f }, + new Case { shader = SpriteShader.Unlit, flipX = true, flipY = true, boneAngle = 30f }, + new Case { shader = SpriteShader.Unlit, flipX = true, flipY = false, boneAngle = -45f }, + new Case { shader = SpriteShader.Lit, flipX = false, flipY = false, boneAngle = 30f }, + new Case { shader = SpriteShader.Lit, flipX = true, flipY = false, boneAngle = 30f }, + new Case { shader = SpriteShader.Lit, flipX = false, flipY = true, boneAngle = 30f }, + }; + + static readonly Case[] k_MirrorCases = + { + new Case { shader = SpriteShader.Unlit, flipX = true, flipY = false, boneAngle = 30f }, + new Case { shader = SpriteShader.Unlit, flipX = false, flipY = true, boneAngle = 30f }, + new Case { shader = SpriteShader.Unlit, flipX = true, flipY = true, boneAngle = 30f }, + new Case { shader = SpriteShader.Lit, flipX = true, flipY = false, boneAngle = 30f }, + }; + + const int k_Size = 128; + const int k_MaxFrames = 30; + const float k_MaxMismatch = 0.02f; + const string k_SkinnedSpriteKeyword = "SKINNED_SPRITE"; + const string k_SpriteCasterKeyword = "SHADOW_SPRITE_CASTER"; + const string k_PrevMeshDeformationKey = "UUM-159819.PrevMeshDeformation"; + + RenderPipelineAsset m_PrevDefaultPipeline; + RenderPipelineAsset m_PrevQualityPipeline; + Renderer2DData m_RendererData; + UniversalRenderPipelineAsset m_PipelineAsset; + GameObject m_CameraGO; + Camera m_Camera; + GameObject m_SpriteGO; + SpriteRenderer m_Renderer; + Texture2D m_Texture; + Sprite m_Sprite; + Material m_SpriteMaterial; + int m_SpritePass; + Material m_ShadowMaterial; + int m_SelfPass; + RenderTexture m_CameraRT; + RenderTexture m_SpriteRT; + RenderTexture m_ShadowRT; + bool m_CaptureRequested; + bool m_Captured; + + // GPU skinning is a player setting. Set it before the test enters Play Mode. + public void Setup() + { + UnityEditor.SessionState.SetInt(k_PrevMeshDeformationKey, (int)UnityEditor.PlayerSettings.meshDeformation); + UnityEditor.PlayerSettings.meshDeformation = UnityEditor.MeshDeformation.GPU; + } + + public void Cleanup() + { + int prev = UnityEditor.SessionState.GetInt(k_PrevMeshDeformationKey, -1); + if (prev >= 0) + UnityEditor.PlayerSettings.meshDeformation = (UnityEditor.MeshDeformation)prev; + } + + [SetUp] + public void SetUpScene() + { + m_PrevDefaultPipeline = GraphicsSettings.defaultRenderPipeline; + m_PrevQualityPipeline = QualitySettings.renderPipeline; + + m_RendererData = ScriptableObject.CreateInstance(); + m_PipelineAsset = UniversalRenderPipelineAsset.Create(m_RendererData); + m_PipelineAsset.useSRPBatcher = true; + GraphicsSettings.defaultRenderPipeline = m_PipelineAsset; + QualitySettings.renderPipeline = null; + + m_CameraRT = new RenderTexture(k_Size, k_Size, GraphicsFormat.R8G8B8A8_UNorm, GraphicsFormat.None); + m_SpriteRT = new RenderTexture(k_Size, k_Size, GraphicsFormat.R8G8B8A8_UNorm, GraphicsFormat.None); + m_ShadowRT = new RenderTexture(k_Size, k_Size, GraphicsFormat.R8G8B8A8_UNorm, GraphicsFormat.None); + + m_CameraGO = new GameObject("UUM-159819 Camera"); + m_CameraGO.transform.position = new Vector3(0, 0, -10); + m_Camera = m_CameraGO.AddComponent(); + m_Camera.orthographic = true; + m_Camera.orthographicSize = 2f; + m_Camera.clearFlags = CameraClearFlags.SolidColor; + m_Camera.backgroundColor = Color.clear; + m_Camera.targetTexture = m_CameraRT; + + var shadowShader = Shader.Find("Hidden/Shadow2D"); + Assert.IsNotNull(shadowShader, "Hidden/Shadow2D not found."); + m_ShadowMaterial = new Material(shadowShader); + m_ShadowMaterial.EnableKeyword(k_SpriteCasterKeyword); + m_ShadowMaterial.EnableKeyword(k_SkinnedSpriteKeyword); + m_SelfPass = m_ShadowMaterial.FindPass("Self"); + + RenderPipelineManager.endCameraRendering += OnEndCameraRendering; + } + + [TearDown] + public void TearDownScene() + { + RenderPipelineManager.endCameraRendering -= OnEndCameraRendering; + + Object.DestroyImmediate(m_SpriteGO); + Object.DestroyImmediate(m_CameraGO); + Object.DestroyImmediate(m_Sprite); + Object.DestroyImmediate(m_Texture); + Object.DestroyImmediate(m_SpriteMaterial); + Object.DestroyImmediate(m_ShadowMaterial); + foreach (var rt in new[] { m_CameraRT, m_SpriteRT, m_ShadowRT }) + { + if (rt == null) + continue; + rt.Release(); + Object.DestroyImmediate(rt); + } + + GraphicsSettings.defaultRenderPipeline = m_PrevDefaultPipeline; + QualitySettings.renderPipeline = m_PrevQualityPipeline; + Object.DestroyImmediate(m_PipelineAsset); + Object.DestroyImmediate(m_RendererData); + } + + // Unlit: pass 0 of Sprite-Unlit-Default. Lit: the UniversalForward pass of Sprite-Lit-Default, + // which shares the skin-then-flip vertex code with the other Lit passes but does not need + // 2D light textures, so its output is the plain sprite color. + void CreateSpriteMaterial(SpriteShader shader) + { + if (shader == SpriteShader.Unlit) + { + m_SpriteMaterial = new Material(Shader.Find("Universal Render Pipeline/2D/Sprite-Unlit-Default")); + m_SpritePass = 0; + return; + } + + m_SpriteMaterial = new Material(Shader.Find("Universal Render Pipeline/2D/Sprite-Lit-Default")); + m_SpritePass = -1; + var lightMode = new ShaderTagId("LightMode"); + for (int i = 0; i < m_SpriteMaterial.passCount; ++i) + { + if (m_SpriteMaterial.shader.FindPassTagValue(i, lightMode).name == "UniversalForward") + { + m_SpritePass = i; + break; + } + } + Assert.GreaterOrEqual(m_SpritePass, 0, "Sprite-Lit-Default has no UniversalForward pass."); + } + + // A 1x2 unit white quad with one bone at its centre. Every vertex is fully weighted to it. + void CreateSkinnedSprite(Case c) + { + CreateSpriteMaterial(c.shader); + + m_Texture = new Texture2D(32, 64, TextureFormat.RGBA32, false); + var pixels = new Color32[32 * 64]; + for (int i = 0; i < pixels.Length; ++i) + pixels[i] = new Color32(255, 255, 255, 255); + m_Texture.SetPixels32(pixels); + m_Texture.Apply(); + + m_Sprite = Sprite.Create(m_Texture, new Rect(0, 0, 32, 64), new Vector2(0.5f, 0.5f), 32f, 0, SpriteMeshType.FullRect); + m_Sprite.SetBones(new[] + { + new SpriteBone { name = "bone", position = Vector3.zero, rotation = Quaternion.identity, length = 1f, parentId = -1 } + }); + + using (var bindPoses = new NativeArray(1, Allocator.Temp)) + { + var poses = bindPoses; + poses[0] = Matrix4x4.identity; + m_Sprite.SetBindPoses(poses); + } + + int vertexCount = m_Sprite.GetVertexCount(); + using (var weights = new NativeArray(vertexCount, Allocator.Temp)) + { + var w = weights; + for (int i = 0; i < vertexCount; ++i) + w[i] = new BoneWeight { boneIndex0 = 0, weight0 = 1f }; + m_Sprite.SetVertexAttribute(VertexAttribute.BlendWeight, w); + } + + m_SpriteGO = new GameObject("UUM-159819 Sprite"); + m_Renderer = m_SpriteGO.AddComponent(); + m_Renderer.sprite = m_Sprite; + m_Renderer.sharedMaterial = m_SpriteMaterial; + m_Renderer.flipX = c.flipX; + m_Renderer.flipY = c.flipY; + + var bone = new GameObject("bone").transform; + bone.SetParent(m_SpriteGO.transform, false); + bone.localRotation = Quaternion.Euler(0, 0, c.boneAngle); + + var skin = m_SpriteGO.AddComponent(); + skin.alwaysUpdate = true; + skin.SetRootTransform(m_SpriteGO.transform); + var state = skin.SetBoneTransforms(new[] { bone }); + Assert.AreEqual(SpriteSkinState.Ready, state, "SpriteSkin setup failed."); + } + + void OnEndCameraRendering(ScriptableRenderContext context, Camera camera) + { + if (camera != m_Camera || !m_CaptureRequested) + return; + m_CaptureRequested = false; + + var cmd = new CommandBuffer { name = "UUM-159819 capture" }; + cmd.SetViewProjectionMatrices(camera.worldToCameraMatrix, camera.projectionMatrix); + + cmd.SetRenderTarget(m_SpriteRT); + cmd.ClearRenderTarget(false, true, Color.clear); + cmd.DrawRenderer(m_Renderer, m_Renderer.sharedMaterial, 0, m_SpritePass); + + cmd.SetRenderTarget(m_ShadowRT); + cmd.ClearRenderTarget(false, true, Color.clear); + cmd.DrawRenderer(m_Renderer, m_ShadowMaterial, 0, m_SelfPass); + + context.ExecuteCommandBuffer(cmd); + context.Submit(); + cmd.Release(); + m_Captured = true; + } + + static bool[] ReadMask(RenderTexture rt) + { + var tex = new Texture2D(rt.width, rt.height, TextureFormat.RGBA32, false); + var prev = RenderTexture.active; + RenderTexture.active = rt; + tex.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0); + tex.Apply(); + RenderTexture.active = prev; + + var pixels = tex.GetPixels32(); + Object.DestroyImmediate(tex); + + var mask = new bool[pixels.Length]; + for (int i = 0; i < pixels.Length; ++i) + mask[i] = pixels[i].r > 127; + return mask; + } + + static int Count(bool[] mask) + { + int n = 0; + foreach (var m in mask) + if (m) ++n; + return n; + } + + // Mismatched pixels divided by pixels covered by either mask. + static float MismatchRatio(bool[] a, bool[] b, out int mismatch, out int union) + { + mismatch = 0; + union = 0; + for (int i = 0; i < a.Length; ++i) + { + if (a[i] || b[i]) ++union; + if (a[i] != b[i]) ++mismatch; + } + return union == 0 ? 0f : (float)mismatch / union; + } + + // The sprite pivot is at the world origin, which is the centre of the render target, so a + // flip about the pivot maps pixel (x, y) to (k_Size-1-x, y) for X and (x, k_Size-1-y) for Y. + static bool[] Mirror(bool[] mask, bool flipX, bool flipY) + { + var result = new bool[mask.Length]; + for (int y = 0; y < k_Size; ++y) + { + for (int x = 0; x < k_Size; ++x) + { + int sx = flipX ? k_Size - 1 - x : x; + int sy = flipY ? k_Size - 1 - y : y; + result[y * k_Size + x] = mask[sy * k_Size + sx]; + } + } + return result; + } + + void AssertPrerequisites() + { + Assume.That(SystemInfo.supportsComputeShaders, "GPU skinning needs compute shaders."); + Assert.GreaterOrEqual(m_SelfPass, 0, "Hidden/Shadow2D has no Self pass."); + Assert.AreEqual(UnityEditor.MeshDeformation.GPU, UnityEditor.PlayerSettings.meshDeformation, "GPU skinning is off."); + } + + // Let 2D Animation move the Sprite Skin to its GPU deformation system. That needs the + // renderer's SRP-batcher state, which is only known after it has been rendered. + IEnumerator WaitForGpuDeformation() + { + for (int frame = 0; frame < k_MaxFrames; ++frame) + { + m_Camera.Render(); + yield return null; + if (frame >= 5 && m_SpriteMaterial.IsKeywordEnabled(k_SkinnedSpriteKeyword)) + break; + } + Assert.IsTrue(m_SpriteMaterial.IsKeywordEnabled(k_SkinnedSpriteKeyword), + "The Sprite Skin never switched to GPU deformation (SKINNED_SPRITE is off on its material)."); + } + + void Capture() + { + m_Captured = false; + m_CaptureRequested = true; + m_Camera.Render(); + Assert.IsTrue(m_Captured, "endCameraRendering capture did not run."); + } + + [UnityTest] + public IEnumerator SelfShadowSilhouette_MatchesSprite_ForGpuSkinnedSprite([ValueSource(nameof(k_ShadowCases))] Case c) + { + AssertPrerequisites(); + CreateSkinnedSprite(c); + yield return WaitForGpuDeformation(); + + Capture(); + var spriteMask = ReadMask(m_SpriteRT); + var shadowMask = ReadMask(m_ShadowRT); + + int spriteCount = Count(spriteMask); + int shadowCount = Count(shadowMask); + Assert.Greater(spriteCount, 100, "The sprite drew almost nothing."); + Assert.Greater(shadowCount, 100, "The shadow caster Self pass drew almost nothing."); + + float ratio = MismatchRatio(spriteMask, shadowMask, out int mismatch, out int union); + Assert.LessOrEqual(ratio, k_MaxMismatch, + $"{c}: the Shadow Caster 2D silhouette does not match the GPU-skinned sprite " + + $"({mismatch} of {union} pixels differ, sprite={spriteCount}, shadow={shadowCount}). " + + "The sprite shader and Shadow2DCasterVertex.hlsl apply flip and GPU skinning in a different order."); + } + + [UnityTest] + public IEnumerator FlippedSprite_IsMirrorOfUnflippedSprite_ForGpuSkinnedSprite([ValueSource(nameof(k_MirrorCases))] Case c) + { + AssertPrerequisites(); + + // Start unflipped, capture, then flip the same renderer and capture again. + var unflipped = c; + unflipped.flipX = false; + unflipped.flipY = false; + CreateSkinnedSprite(unflipped); + yield return WaitForGpuDeformation(); + + Capture(); + var unflippedSprite = ReadMask(m_SpriteRT); + var unflippedShadow = ReadMask(m_ShadowRT); + Assert.Greater(Count(unflippedSprite), 100, "The unflipped sprite drew almost nothing."); + + m_Renderer.flipX = c.flipX; + m_Renderer.flipY = c.flipY; + m_Camera.Render(); + yield return null; + Assert.IsTrue(m_SpriteMaterial.IsKeywordEnabled(k_SkinnedSpriteKeyword), + "The Sprite Skin left GPU deformation after the flip changed."); + + Capture(); + var flippedSprite = ReadMask(m_SpriteRT); + var flippedShadow = ReadMask(m_ShadowRT); + + var expected = Mirror(unflippedSprite, c.flipX, c.flipY); + float spriteRatio = MismatchRatio(expected, flippedSprite, out int spriteMismatch, out int spriteUnion); + Assert.LessOrEqual(spriteRatio, k_MaxMismatch, + $"{c}: the flipped GPU-skinned sprite is not the mirror image of the unflipped one " + + $"({spriteMismatch} of {spriteUnion} pixels differ). Skinning must run before the flip."); + + var expectedShadow = Mirror(unflippedShadow, c.flipX, c.flipY); + float shadowRatio = MismatchRatio(expectedShadow, flippedShadow, out int shadowMismatch, out int shadowUnion); + Assert.LessOrEqual(shadowRatio, k_MaxMismatch, + $"{c}: the flipped shadow caster silhouette is not the mirror image of the unflipped one " + + $"({shadowMismatch} of {shadowUnion} pixels differ)."); + } + } +} +#endif diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/ShadowCaster2DSpriteSkinFlipTests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/ShadowCaster2DSpriteSkinFlipTests.cs.meta new file mode 100644 index 00000000000..c718bb88bcc --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/ShadowCaster2DSpriteSkinFlipTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: fb184e2cf6af40b4c9cc8c10e7946b6b \ No newline at end of file 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..9704f62a007 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), null); + } + + // 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.SetRootTransform(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 diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/ShadowUtilsTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/ShadowUtilsTests.cs index 7c24d65c851..7e8d0c8789d 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/ShadowUtilsTests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/ShadowUtilsTests.cs @@ -1,4 +1,5 @@ using NUnit.Framework; +using UnityEngine.Experimental.Rendering; namespace UnityEngine.Rendering.Universal.Tests { @@ -27,17 +28,72 @@ public void GetSlopeScaleDepthBias_MapsModeBiasAndKernelRadiusToRasterizerSlope( Assert.That(ShadowUtils.GetSlopeScaleDepthBias(normalizedSlopeScale, depthBiasMode, softShadowKernelRadius), Is.EqualTo(expected).Within(k_Tolerance)); } - [Description("The legacy mode pushes casters away from the light by the bias value in texels. The slope-scale mode keeps a fixed 0.05 texel push while the caster normal bias mode is active, because the slope term and the caster normal bias both vanish on receivers facing the light head-on. The receiver normal bias mode covers those receivers itself, so the push is dropped there.")] - [TestCase(ShadowDepthBiasMode.Legacy, ShadowNormalBiasMode.Caster, 1.0f, 2.0f, -2.0f)] - [TestCase(ShadowDepthBiasMode.Legacy, ShadowNormalBiasMode.Receiver, 0.05f, 2.0f, -0.1f)] - [TestCase(ShadowDepthBiasMode.Legacy, ShadowNormalBiasMode.Caster, 0.0f, 2.0f, 0.0f)] - [TestCase(ShadowDepthBiasMode.SlopeScale, ShadowNormalBiasMode.Caster, 0.0f, 2.0f, -0.1f)] - [TestCase(ShadowDepthBiasMode.SlopeScale, ShadowNormalBiasMode.Caster, 1.0f, 2.0f, -0.1f)] - [TestCase(ShadowDepthBiasMode.SlopeScale, ShadowNormalBiasMode.Caster, 0.5f, 0.4f, -0.02f)] - [TestCase(ShadowDepthBiasMode.SlopeScale, ShadowNormalBiasMode.Receiver, 1.0f, 2.0f, 0.0f)] - public void GetCasterDepthBias_MapsModesAndTexelSizeToCasterOffset(ShadowDepthBiasMode depthBiasMode, ShadowNormalBiasMode normalBiasMode, float depthBias, float texelSize, float expected) + [Description("The legacy mode pushes casters away from the light by the bias value in texels. The slope-scale mode keeps a fixed 0.05 texel push while the caster normal bias mode is active, because the slope term and the caster normal bias both vanish on receivers facing the light head-on. The receiver normal bias mode covers those receivers itself, so the push is dropped there on a 16-bit shadow map.")] + [TestCase(ShadowDepthBiasMode.Legacy, ShadowNormalBiasMode.Caster, 1.0f, 2.0f, false, -2.0f)] + [TestCase(ShadowDepthBiasMode.Legacy, ShadowNormalBiasMode.Receiver, 0.05f, 2.0f, false, -0.1f)] + [TestCase(ShadowDepthBiasMode.Legacy, ShadowNormalBiasMode.Caster, 0.0f, 2.0f, false, 0.0f)] + [TestCase(ShadowDepthBiasMode.SlopeScale, ShadowNormalBiasMode.Caster, 0.0f, 2.0f, false, -0.1f)] + [TestCase(ShadowDepthBiasMode.SlopeScale, ShadowNormalBiasMode.Caster, 1.0f, 2.0f, false, -0.1f)] + [TestCase(ShadowDepthBiasMode.SlopeScale, ShadowNormalBiasMode.Caster, 0.5f, 0.4f, false, -0.02f)] + [TestCase(ShadowDepthBiasMode.SlopeScale, ShadowNormalBiasMode.Receiver, 1.0f, 2.0f, false, 0.0f)] + public void GetCasterDepthBias_MapsModesAndTexelSizeToCasterOffset(ShadowDepthBiasMode depthBiasMode, ShadowNormalBiasMode normalBiasMode, float depthBias, float texelSize, bool highPrecisionShadowmap, float expected) { - Assert.That(ShadowUtils.GetCasterDepthBias(depthBias, depthBiasMode, normalBiasMode, texelSize), Is.EqualTo(expected).Within(k_Tolerance)); + Assert.That(ShadowUtils.GetCasterDepthBias(depthBias, 0.0f, depthBiasMode, normalBiasMode, texelSize, highPrecisionShadowmap), Is.EqualTo(expected).Within(k_Tolerance)); + } + + [Description("A 16-bit shadow map rounds the caster depth and so hides the receiver's own depth error, while a finer shadow map stores it. On a shadow map finer than 16 bit a mode with nothing else covering receivers facing the light head-on keeps a caster push of at least 0.005 texels, and larger legacy bias values pass through unchanged. A receiver normal bias of at least 0.005 covers those receivers, so the push is dropped there.")] + [TestCase(ShadowDepthBiasMode.Legacy, ShadowNormalBiasMode.Caster, 0.0f, 0.25f, 2.0f, -0.01f)] + [TestCase(ShadowDepthBiasMode.Legacy, ShadowNormalBiasMode.Caster, 0.002f, 0.25f, 2.0f, -0.01f)] + [TestCase(ShadowDepthBiasMode.Legacy, ShadowNormalBiasMode.Caster, 1.0f, 0.25f, 2.0f, -2.0f)] + [TestCase(ShadowDepthBiasMode.Legacy, ShadowNormalBiasMode.Receiver, 0.0f, 0.0f, 2.0f, -0.01f)] + [TestCase(ShadowDepthBiasMode.Legacy, ShadowNormalBiasMode.Receiver, 0.0f, 1.0f, 2.0f, 0.0f)] + [TestCase(ShadowDepthBiasMode.SlopeScale, ShadowNormalBiasMode.Caster, 1.0f, 0.25f, 2.0f, -0.1f)] + [TestCase(ShadowDepthBiasMode.SlopeScale, ShadowNormalBiasMode.Receiver, 1.0f, 0.0f, 2.0f, -0.01f)] + [TestCase(ShadowDepthBiasMode.SlopeScale, ShadowNormalBiasMode.Receiver, 1.0f, 0.004f, 2.0f, -0.01f)] + [TestCase(ShadowDepthBiasMode.SlopeScale, ShadowNormalBiasMode.Receiver, 1.0f, 0.005f, 2.0f, 0.0f)] + [TestCase(ShadowDepthBiasMode.SlopeScale, ShadowNormalBiasMode.Receiver, 1.0f, 1.0f, 2.0f, 0.0f)] + [TestCase(ShadowDepthBiasMode.SlopeScale, ShadowNormalBiasMode.Receiver, 0.0f, 0.0f, 0.4f, -0.002f)] + public void GetCasterDepthBias_KeepsAMinimumCasterOffsetOnHighPrecisionShadowmaps(ShadowDepthBiasMode depthBiasMode, ShadowNormalBiasMode normalBiasMode, float depthBias, float normalBias, float texelSize, float expected) + { + Assert.That(ShadowUtils.GetCasterDepthBias(depthBias, normalBias, depthBiasMode, normalBiasMode, texelSize, highPrecisionShadowmap: true), Is.EqualTo(expected).Within(k_Tolerance)); + } + + [Description("The minimum caster offset applies to depth formats finer than 16-bit UNorm, which includes the 24-bit formats a 16-bit request falls back to, and not to the 16-bit formats themselves.")] + [TestCase(GraphicsFormat.D16_UNorm, false)] + [TestCase(GraphicsFormat.D16_UNorm_S8_UInt, false)] + [TestCase(GraphicsFormat.D24_UNorm, true)] + [TestCase(GraphicsFormat.D24_UNorm_S8_UInt, true)] + [TestCase(GraphicsFormat.D32_SFloat, true)] + [TestCase(GraphicsFormat.D32_SFloat_S8_UInt, true)] + public void IsHighPrecisionShadowmap_IsTrueForFormatsFinerThan16Bit(GraphicsFormat format, bool expected) + { + Assert.That(ShadowUtils.IsHighPrecisionShadowmap(format), Is.EqualTo(expected)); + } + + [Description("Once the shadow caster pass has created the shadow map, the precision comes from its actual format, so a 16-bit request that fell back to a 24-bit format counts as high precision. Before that the format is unknown and the requested precision decides.")] + [TestCase(GraphicsFormat.D24_UNorm_S8_UInt, DepthBits.Depth16, true)] + [TestCase(GraphicsFormat.D16_UNorm, DepthBits.Depth16, false)] + [TestCase(GraphicsFormat.D32_SFloat, DepthBits.Depth32, true)] + [TestCase(GraphicsFormat.None, DepthBits.Depth16, false)] + [TestCase(GraphicsFormat.None, DepthBits.Depth32, true)] + public void IsHighPrecisionShadowmap_PrefersTheActualFormatOverTheRequestedPrecision(GraphicsFormat format, DepthBits requestedDepthBits, bool expected) + { + Assert.That(ShadowUtils.IsHighPrecisionShadowmap(format, requestedDepthBits), Is.EqualTo(expected)); + } + + [Description("The returned resolution is the largest power-of-two fraction of the smaller atlas side at which the requested number of tiles fits. The tiles are counted per axis, so atlas sides that are not multiples of the resolution do not inflate the count.")] + [TestCase(600, 1000, 25, 75)] + [TestCase(300, 400, 5, 75)] + [TestCase(1000, 600, 25, 75)] + [TestCase(1024, 1024, 1, 1024)] + [TestCase(1024, 1024, 4, 512)] + [TestCase(1024, 2048, 3, 512)] + public void GetMaxTileResolutionInAtlas_ReturnsLargestResolutionThatFitsTileCount(int atlasWidth, int atlasHeight, int tileCount, int expected) + { + int resolution = ShadowUtils.GetMaxTileResolutionInAtlas(atlasWidth, atlasHeight, tileCount); + + Assert.That(resolution, Is.EqualTo(expected)); + Assert.That((atlasWidth / resolution) * (atlasHeight / resolution), Is.GreaterThanOrEqualTo(tileCount)); } [Description("Each soft shadow quality maps to the radius of its PCF kernel. The shadow biases scale with this radius to compensate for the wider filter.")] @@ -49,6 +105,15 @@ public void GetSoftShadowKernelRadius_MapsSoftShadowQualityToKernelRadius(SoftSh Assert.That(ShadowUtils.GetSoftShadowKernelRadius(softShadowQuality), Is.EqualTo(expected).Within(k_Tolerance)); } + [Description("The kernel radius is the percentage of the shadow resolution, so it doubles with the resolution and the penumbra keeps its width. It never drops below half a texel.")] + [TestCase(0.341796875f, 1024.0f, 3.5f)] + [TestCase(0.341796875f, 2048.0f, 7.0f)] + [TestCase(0.1f, 256.0f, 0.5f)] + public void GetSoftShadowKernelRadius_MapsPercentAndShadowResolutionToKernelRadius(float softShadowKernelRadiusPercent, float shadowResolution, float expected) + { + Assert.That(ShadowUtils.GetSoftShadowKernelRadius(softShadowKernelRadiusPercent, shadowResolution), Is.EqualTo(expected).Within(k_Tolerance)); + } + [Description("A light set to UsePipelineSettings takes its soft shadow quality from the pipeline asset. The bias scaling and the shader filtering then agree on the kernel.")] [TestCase(SoftShadowQuality.Low)] [TestCase(SoftShadowQuality.Medium)] @@ -185,5 +250,377 @@ public void NormalBias_ModeSwitch_MovesTheSameOffsetBetweenChannels() float receiverNormalBias = ShadowUtils.GetReceiverNormalBias(0.7f, ShadowNormalBiasMode.Receiver, 0.42f, softShadowKernelRadius); Assert.That(receiverNormalBias, Is.EqualTo(-casterNormalBias).Within(k_Tolerance)); } + + [Description("PCSS replaces the highest soft shadow quality only, so a light resolving to Low or Medium keeps the tent filter even when the asset enables PCSS. A device without PCSS support, such as GL, keeps it too.")] + [TestCase(true, SoftShadowQuality.High, true, ExpectedResult = true)] + [TestCase(true, SoftShadowQuality.Medium, true, ExpectedResult = false)] + [TestCase(true, SoftShadowQuality.Low, true, ExpectedResult = false)] + [TestCase(false, SoftShadowQuality.High, true, ExpectedResult = false)] + [TestCase(true, SoftShadowQuality.High, false, ExpectedResult = false)] + public bool IsAdditionalLightPCSSEnabled_NeedsDeviceSupportAndTheAssetToggleAtTheHighestQuality(bool enabledInAsset, SoftShadowQuality resolvedQuality, bool pcssSupported) + { + if (!ShadowUtils.SupportsPerLightSoftShadowQuality()) + Assert.Ignore("XR mobile cannot select the soft shadow quality per light, so PCSS is never enabled there."); + + var asset = ScriptableObject.CreateInstance(); + try + { + asset.additionalLightShadowsPCSS = enabledInAsset; + return ShadowUtils.IsAdditionalLightPCSSEnabled((int)resolvedQuality, asset, pcssSupported); + } + finally + { + Object.DestroyImmediate(asset); + } + } + + [Description("GL doesn't support PCSS, so its lights keep the High quality tent filter.")] + [TestCase(GraphicsDeviceType.OpenGLES3, ExpectedResult = false)] + [TestCase(GraphicsDeviceType.OpenGLCore, ExpectedResult = false)] + [TestCase(GraphicsDeviceType.Direct3D11, ExpectedResult = true)] + [TestCase(GraphicsDeviceType.Direct3D12, ExpectedResult = true)] + [TestCase(GraphicsDeviceType.Vulkan, ExpectedResult = true)] + [TestCase(GraphicsDeviceType.Metal, ExpectedResult = true)] + [TestCase(GraphicsDeviceType.WebGPU, ExpectedResult = true)] + public bool SupportsPCSS_ExcludesGL(GraphicsDeviceType type) + { + return ShadowUtils.SupportsPCSS(type); + } + + [Description("Without a pipeline asset there is no PCSS toggle to read, so the light keeps the tent filter.")] + [Test] + public void IsAdditionalLightPCSSEnabled_WithoutAsset_IsFalse() + { + Assert.That(ShadowUtils.IsAdditionalLightPCSSEnabled((int)SoftShadowQuality.High, null), Is.False); + } + + [Description("The light inspector offers the PCSS parameters for a light that would take the PCSS path, which needs soft shadows on the light, soft shadow support in the asset, and a resolved quality of High.")] + [TestCase(LightShadows.Soft, true, SoftShadowQuality.High, ExpectedResult = true)] + [TestCase(LightShadows.Soft, true, SoftShadowQuality.Medium, ExpectedResult = false)] + [TestCase(LightShadows.Soft, false, SoftShadowQuality.High, ExpectedResult = false)] + [TestCase(LightShadows.Hard, true, SoftShadowQuality.High, ExpectedResult = false)] + [TestCase(LightShadows.None, true, SoftShadowQuality.High, ExpectedResult = false)] + public bool IsPCSSAvailableForLight_FollowsTheResolvedSoftShadowQuality(LightShadows shadows, bool supportsSoftShadows, SoftShadowQuality assetQuality) + { + if (!ShadowUtils.SupportsPerLightSoftShadowQuality()) + Assert.Ignore("XR mobile cannot select the soft shadow quality per light, so PCSS is never available there."); + + var asset = ScriptableObject.CreateInstance(); + var go = new GameObject(); + try + { + asset.supportsSoftShadows = supportsSoftShadows; + asset.softShadowQuality = assetQuality; + + var light = go.AddComponent(); + light.shadows = shadows; + + return ShadowUtils.IsPCSSAvailableForLight(light, asset); + } + finally + { + Object.DestroyImmediate(go); + Object.DestroyImmediate(asset); + } + } + + // Mirrors LinearEyeDepth in the shader + static float LinearEyeDepth(float deviceDepth, Vector4 zBufferParams) + { + return 1.0f / (zBufferParams.z * deviceDepth + zBufferParams.w); + } + + [Description("The punctual blocker depth is linearized from the shadow slice projection, so feeding the device depth of the near and far planes back through the shader formula returns the planes of that projection.")] + [Test] + public void ComputeAdditionalLightPCSSParams_LinearizesTheSliceDepthRange() + { + const float near = 0.1f; + const float far = 10.0f; + + ShadowUtils.ComputeAdditionalLightPCSSParams(0.0f, null, 512, Matrix4x4.Perspective(90.0f, 1.0f, near, far), + out _, out Vector4 zBufferParams); + + float nearDeviceDepth = SystemInfo.usesReversedZBuffer ? 1.0f : 0.0f; + float farDeviceDepth = SystemInfo.usesReversedZBuffer ? 0.0f : 1.0f; + + Assert.That(LinearEyeDepth(nearDeviceDepth, zBufferParams), Is.EqualTo(near).Within(1e-4f)); + Assert.That(LinearEyeDepth(farDeviceDepth, zBufferParams), Is.EqualTo(far).Within(1e-3f)); + } + + [Description("Zero samples would make the shader divide by the sample count, and the sample direction table only holds k_PCSSMaxSampleCount entries, so both counts are clamped into that range.")] + [TestCase(0, 0, 1, 1)] + [TestCase(1000, 1000, ShadowUtils.k_PCSSMaxSampleCount, ShadowUtils.k_PCSSMaxSampleCount)] + [TestCase(8, 12, 8, 12)] + public void ComputeAdditionalLightPCSSParams_ClampsTheSampleCounts(int blockerSampleCount, int filterSampleCount, int expectedBlocker, int expectedFilter) + { + var go = new GameObject(); + try + { + var light = go.AddComponent(); + light.type = LightType.Spot; + + var additionalLightData = go.AddComponent(); + additionalLightData.softShadowPCSSSampleQuality = PCSSSampleQuality.Custom; + additionalLightData.softShadowBlockerSampleCount = blockerSampleCount; + additionalLightData.softShadowFilterSampleCount = filterSampleCount; + + ShadowUtils.ComputeAdditionalLightPCSSParams(light.shapeRadius, additionalLightData, 512, + Matrix4x4.Perspective(90.0f, 1.0f, 0.1f, 10.0f), out Vector4 pcssParams, out _); + + Assert.That(pcssParams.z, Is.EqualTo(expectedBlocker)); + Assert.That(pcssParams.w, Is.EqualTo(expectedFilter)); + } + finally + { + Object.DestroyImmediate(go); + } + } + + [Description("A cascade the frame did not render keeps a zeroed atlas rectangle, which is how the shader tells it apart from the tile at the atlas origin. ComputeCascadeIndex returns the trailing slot for a pixel past the last cascade.")] + [Test] + public void ComputeMainLightPCSSParams_ZeroesTheCascadesThatWereNotRendered() + { + var cascadeSlices = new ShadowSliceData[4]; + cascadeSlices[0].projectionMatrix = Matrix4x4.Ortho(-10.0f, 10.0f, -10.0f, 10.0f, 0.0f, 100.0f); + cascadeSlices[0].offsetX = 0; + cascadeSlices[0].offsetY = 512; + cascadeSlices[0].resolution = 512; + + MainLightShadowCascadeVectors params0 = default, params1 = default, atlas = default; + ShadowUtils.ComputeMainLightPCSSParams(null, cascadeSlices, 1, 1024, 1024, ref params0, ref params1, ref atlas); + + Assert.That(atlas[0], Is.EqualTo(new Vector4(0.0f, 0.5f, 0.5f, 0.5f))); + + for (int i = 1; i < MainLightShadowCascadeVectors.count; ++i) + { + Assert.That(atlas[i], Is.EqualTo(Vector4.zero), "cascade {0} atlas rectangle", i); + Assert.That(params0[i], Is.EqualTo(Vector4.zero), "cascade {0} params0", i); + Assert.That(params1[i], Is.EqualTo(Vector4.zero), "cascade {0} params1", i); + } + } + + [Description("The shader converts between a depth difference and a filter radius in both directions, so the two scales must stay exact reciprocals. The radius follows the tangent of the half angular diameter, which is what makes a wider light cast a wider penumbra.")] + [Test] + public void ComputeMainLightPCSSParams_RadialAndDepthScalesAreReciprocal() + { + var go = new GameObject(); + try + { + var light = go.AddComponent(); + light.type = LightType.Directional; + + var additionalLightData = go.AddComponent(); + additionalLightData.softShadowAngularDiameter = 0.5f; + additionalLightData.softShadowScale = 1.0f; + + var cascadeSlices = new ShadowSliceData[4]; + cascadeSlices[0].projectionMatrix = Matrix4x4.Ortho(-10.0f, 10.0f, -10.0f, 10.0f, 0.0f, 100.0f); + cascadeSlices[0].resolution = 1024; + + MainLightShadowCascadeVectors params0 = default, params1 = default, atlas = default; + ShadowUtils.ComputeMainLightPCSSParams(additionalLightData, cascadeSlices, 1, 1024, 1024, ref params0, ref params1, ref atlas); + + // 2 * |m00 / m22| of the projection above + const float depthToRadialScale = 10.0f; + float expectedDepth2RadialScale = Mathf.Tan(0.5f * Mathf.Deg2Rad * 0.5f) * depthToRadialScale; + + Assert.That(params0[0].x, Is.EqualTo(expectedDepth2RadialScale).Within(1e-6f)); + Assert.That(params0[0].y, Is.EqualTo(1.0f / expectedDepth2RadialScale).Within(1e-3f)); + } + finally + { + Object.DestroyImmediate(go); + } + } + + [Description("The authored clump exponent spreads the blocker samples over a linear range, while the shader raises an already square-rooted distance to it, so the value is halved on the way to the GPU.")] + [Test] + public void ComputeMainLightPCSSParams_HalvesTheAuthoredClumpExponent() + { + var go = new GameObject(); + try + { + var light = go.AddComponent(); + light.type = LightType.Directional; + + var additionalLightData = go.AddComponent(); + additionalLightData.softShadowPCSSSampleQuality = PCSSSampleQuality.Custom; + additionalLightData.softShadowBlockerSamplingClumpExponent = 3.0f; + + var cascadeSlices = new ShadowSliceData[4]; + cascadeSlices[0].projectionMatrix = Matrix4x4.Ortho(-10.0f, 10.0f, -10.0f, 10.0f, 0.0f, 100.0f); + cascadeSlices[0].resolution = 1024; + + MainLightShadowCascadeVectors params0 = default, params1 = default, atlas = default; + ShadowUtils.ComputeMainLightPCSSParams(additionalLightData, cascadeSlices, 1, 1024, 1024, ref params0, ref params1, ref atlas); + + Assert.That(params1[0].w, Is.EqualTo(1.5f).Within(k_Tolerance)); + } + finally + { + Object.DestroyImmediate(go); + } + } + + [Description("The minimum filter radius is authored in texels of one cascade tile, so the shader is given the texel size of that tile rather than of the whole atlas.")] + [Test] + public void GetMainLightPCSSScalars_UsesTheTileTexelSizeAndClampsTheSampleCounts() + { + var go = new GameObject(); + try + { + var light = go.AddComponent(); + light.type = LightType.Directional; + + var additionalLightData = go.AddComponent(); + additionalLightData.softShadowPCSSSampleQuality = PCSSSampleQuality.Custom; + additionalLightData.softShadowBlockerSampleCount = 1000; + additionalLightData.softShadowFilterSampleCount = 0; + + Vector4 scalars = ShadowUtils.GetMainLightPCSSScalars(additionalLightData, 512); + + Assert.That(scalars.x, Is.EqualTo(1.0f / 512.0f).Within(k_Tolerance)); + Assert.That(scalars.y, Is.EqualTo(ShadowUtils.k_PCSSMaxSampleCount)); + Assert.That(scalars.z, Is.EqualTo(1)); + Assert.That(scalars.w, Is.EqualTo(0), "the temporal frame index is filled in at upload"); + } + finally + { + Object.DestroyImmediate(go); + } + } + + [Description("Medium is the default for new lights and lights serialized before the preset existed, so it has to render the same as the previous default sample counts.")] + [Test] + public void PCSSSampleQuality_DefaultsToMediumWithTheDefaultSampleCounts() + { + var go = new GameObject(); + try + { + var additionalLightData = go.AddComponent(); + + Assert.That(additionalLightData.softShadowPCSSSampleQuality, Is.EqualTo(PCSSSampleQuality.Medium)); + + ShadowUtils.GetPCSSPresetSampleCounts(PCSSSampleQuality.Medium, out int blockerSampleCount, out int filterSampleCount); + Assert.That(blockerSampleCount, Is.EqualTo(UniversalAdditionalLightData.k_DefaultSoftShadowBlockerSampleCount)); + Assert.That(filterSampleCount, Is.EqualTo(UniversalAdditionalLightData.k_DefaultSoftShadowFilterSampleCount)); + } + finally + { + Object.DestroyImmediate(go); + } + } + + [Description("A preset ignores the sample counts stored on the light, which only apply once the light is set to Custom.")] + [TestCase(PCSSSampleQuality.Low, 12, 8)] + [TestCase(PCSSSampleQuality.Medium, 24, 16)] + [TestCase(PCSSSampleQuality.High, 32, 24)] + [TestCase(PCSSSampleQuality.Custom, 5, 7)] + public void GetPCSSSampleCounts_ResolvesThePresetOrTheCustomValues(PCSSSampleQuality quality, int expectedBlocker, int expectedFilter) + { + var go = new GameObject(); + try + { + var additionalLightData = go.AddComponent(); + additionalLightData.softShadowPCSSSampleQuality = quality; + additionalLightData.softShadowBlockerSampleCount = 5; + additionalLightData.softShadowFilterSampleCount = 7; + + ShadowUtils.GetPCSSSampleCounts(additionalLightData, out int blockerSampleCount, out int filterSampleCount); + + Assert.That(blockerSampleCount, Is.EqualTo(expectedBlocker)); + Assert.That(filterSampleCount, Is.EqualTo(expectedFilter)); + } + finally + { + Object.DestroyImmediate(go); + } + } + + [Test] + public void GetPCSSSampleCounts_LightWithoutAdditionalData_UsesMedium() + { + ShadowUtils.GetPCSSSampleCounts(null, out int blockerSampleCount, out int filterSampleCount); + ShadowUtils.GetPCSSPresetSampleCounts(PCSSSampleQuality.Medium, out int expectedBlocker, out int expectedFilter); + + Assert.That(blockerSampleCount, Is.EqualTo(expectedBlocker)); + Assert.That(filterSampleCount, Is.EqualTo(expectedFilter)); + } + + [Description("A preset always renders with the default tuning values, so values left over from Custom cannot change the shadows while they are hidden. The angular diameter, softness scale and minimum filter size apply in every mode.")] + [Test] + public void ComputeMainLightPCSSParams_PresetIgnoresTheCustomTuningValues() + { + var go = new GameObject(); + try + { + var light = go.AddComponent(); + light.type = LightType.Directional; + + var additionalLightData = go.AddComponent(); + additionalLightData.softShadowPCSSSampleQuality = PCSSSampleQuality.High; + additionalLightData.softShadowMaxPenumbraSize = 2.0f; + additionalLightData.softShadowMaxSamplingDistance = 2.0f; + additionalLightData.softShadowMinFilterMaxAngularDiameter = 20.0f; + additionalLightData.softShadowBlockerSearchAngularDiameter = 20.0f; + additionalLightData.softShadowBlockerSamplingClumpExponent = 3.0f; + + var cascadeSlices = new ShadowSliceData[4]; + cascadeSlices[0].projectionMatrix = Matrix4x4.Ortho(-10.0f, 10.0f, -10.0f, 10.0f, 0.0f, 100.0f); + cascadeSlices[0].resolution = 1024; + + MainLightShadowCascadeVectors params0 = default, params1 = default, atlas = default; + ShadowUtils.ComputeMainLightPCSSParams(additionalLightData, cascadeSlices, 1, 1024, 1024, ref params0, ref params1, ref atlas); + + MainLightShadowCascadeVectors expectedParams0 = default, expectedParams1 = default, expectedAtlas = default; + ShadowUtils.ComputeMainLightPCSSParams(null, cascadeSlices, 1, 1024, 1024, ref expectedParams0, ref expectedParams1, ref expectedAtlas); + + Assert.That(params0[0], Is.EqualTo(expectedParams0[0])); + Assert.That(params1[0], Is.EqualTo(expectedParams1[0])); + + additionalLightData.softShadowAngularDiameter = 2.0f; + ShadowUtils.ComputeMainLightPCSSParams(additionalLightData, cascadeSlices, 1, 1024, 1024, ref params0, ref params1, ref atlas); + + Assert.That(params0[0].x, Is.GreaterThan(expectedParams0[0].x), "a wider light widens the penumbra under a preset"); + + additionalLightData.softShadowMinFilterSizeTexels = 4.0f; + ShadowUtils.ComputeMainLightPCSSParams(additionalLightData, cascadeSlices, 1, 1024, 1024, ref params0, ref params1, ref atlas); + + Assert.That(params1[0].x, Is.EqualTo(4.0f), "the minimum filter size applies under a preset"); + } + finally + { + Object.DestroyImmediate(go); + } + } + + [Description("The minimum filter size changes the look as much as the softness scale, so it applies under a preset as well as under Custom.")] + [Test] + public void ComputeAdditionalLightPCSSParams_MinFilterSizeAppliesInEveryMode() + { + var go = new GameObject(); + try + { + var light = go.AddComponent(); + light.type = LightType.Spot; + + var additionalLightData = go.AddComponent(); + additionalLightData.softShadowPCSSSampleQuality = PCSSSampleQuality.Low; + additionalLightData.softShadowMinFilterSize = 1.0f; + + Matrix4x4 projection = Matrix4x4.Perspective(90.0f, 1.0f, 0.1f, 10.0f); + ShadowUtils.ComputeAdditionalLightPCSSParams(light.shapeRadius, additionalLightData, 512, projection, out Vector4 presetParams, out _); + + additionalLightData.softShadowPCSSSampleQuality = PCSSSampleQuality.Custom; + ShadowUtils.ComputeAdditionalLightPCSSParams(light.shapeRadius, additionalLightData, 512, projection, out Vector4 customParams, out _); + + Assert.That(presetParams.y, Is.EqualTo(0.001f).Within(k_Tolerance)); + Assert.That(customParams.y, Is.EqualTo(0.001f).Within(k_Tolerance)); + } + finally + { + Object.DestroyImmediate(go); + } + } } } diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/SkippedPrepassTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/SkippedPrepassTests.cs new file mode 100644 index 00000000000..5a4a742278d --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/SkippedPrepassTests.cs @@ -0,0 +1,209 @@ +using System.Collections; +using System.Collections.Generic; +using NUnit.Framework; +using UnityEngine.Rendering.RenderGraphModule; +using UnityEngine.TestTools; + +namespace UnityEngine.Rendering.Universal.Tests +{ + // URP skips the prepass when the camera can't see any prepass layer. The textures it would have produced must still be + // published as globals, so that shaders sample the same textures that passes declare through the resource data. + class SkippedPrepassTests + { + class PrepassTexturesFeature : ScriptableRendererFeature + { + internal bool requireRenderingLayers; + internal CaptureGlobalsPass capturePass; + + public override void Create() + { + capturePass = new CaptureGlobalsPass(); + } + + public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData renderingData) + { + renderer.EnqueuePass(capturePass); + } + + internal override bool RequireRenderingLayers(bool isDeferred, bool needsGBufferAccurateNormals, out RenderingLayerUtils.Event atEvent, out RenderingLayerUtils.MaskSize maskSize) + { + atEvent = RenderingLayerUtils.Event.DepthNormalPrePass; + maskSize = RenderingLayerUtils.MaskSize.Bits8; + return requireRenderingLayers; + } + } + + // Records nothing, only compares the globals published by the prepass stage against the resource data + class CaptureGlobalsPass : ScriptableRenderPass + { + static readonly int k_CameraDepthTextureID = Shader.PropertyToID("_CameraDepthTexture"); + static readonly int k_CameraNormalsTextureID = Shader.PropertyToID("_CameraNormalsTexture"); + static readonly int k_CameraRenderingLayersTextureID = Shader.PropertyToID("_CameraRenderingLayersTexture"); + + internal readonly List mismatches = new(); + + public CaptureGlobalsPass() + { + renderPassEvent = RenderPassEvent.AfterRenderingPrePasses; + } + + public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) + { + var resourceData = frameData.Get(); + + CheckGlobal(renderGraph, k_CameraDepthTextureID, resourceData.cameraDepthTexture, "_CameraDepthTexture"); + CheckGlobal(renderGraph, k_CameraNormalsTextureID, resourceData.cameraNormalsTexture, "_CameraNormalsTexture"); + if (resourceData.renderingLayersTexture.IsValid()) + CheckGlobal(renderGraph, k_CameraRenderingLayersTextureID, resourceData.renderingLayersTexture, "_CameraRenderingLayersTexture"); + } + + void CheckGlobal(RenderGraph renderGraph, int propertyId, TextureHandle expected, string name) + { + if (renderGraph.GetGlobal(propertyId) != expected) + mismatches.Add(name); + } + } + + public enum PrepassState + { + Drawn, + SkippedByCullingMask, + SkippedByLayerMask, + } + + static readonly RenderingMode[] k_RenderingModes = { RenderingMode.Forward, RenderingMode.Deferred }; + const int k_PrepassLayer = 31; + + RenderPipelineAsset m_PreviousRenderPipelineAsset; + UniversalRenderPipelineAsset m_Asset; + readonly PrepassTexturesFeature[] m_Features = new PrepassTexturesFeature[k_RenderingModes.Length]; + readonly List m_Objects = new(); + Camera m_Camera; + UniversalAdditionalCameraData m_CameraData; + RenderTexture m_Destination; + + [UnityOneTimeSetUp] + public IEnumerator OneTimeSetUp() + { + m_PreviousRenderPipelineAsset = QualitySettings.renderPipeline; + + if (GraphicsSettings.currentRenderPipeline is not UniversalRenderPipelineAsset) + Assert.Ignore("These tests only run when URP is the active render pipeline."); + + // One renderer per rendering mode, so the tests only need a single pipeline switch + var rendererDataList = new ScriptableRendererData[k_RenderingModes.Length]; + for (int i = 0; i < k_RenderingModes.Length; ++i) + { + m_Features[i] = ScriptableObject.CreateInstance(); + m_Objects.Add(m_Features[i]); + + // A prepass restricted to a single layer can be skipped while opaque geometry stays visible + var rendererData = ScriptableObject.CreateInstance(); + rendererData.renderingMode = k_RenderingModes[i]; + rendererData.prepassLayerMask = 1 << k_PrepassLayer; + rendererData.rendererFeatures.Add(m_Features[i]); + m_Objects.Add(rendererData); + rendererDataList[i] = rendererData; + } + + m_Asset = ScriptableObject.CreateInstance(); + m_Asset.m_RendererDataList = rendererDataList; + m_Objects.Add(m_Asset); + QualitySettings.renderPipeline = m_Asset; + + var cameraGameObject = new GameObject("Skipped Prepass Camera"); + m_Objects.Add(cameraGameObject); + m_Camera = cameraGameObject.AddComponent(); + m_Camera.enabled = false; + m_CameraData = cameraGameObject.AddComponent(); + + m_Destination = new RenderTexture(64, 64, 24); + m_Objects.Add(m_Destination); + + // Let the pipeline switch to the test asset. Nothing may render during that frame in batchmode, so render once to + // make sure the pipeline exists. Creating it recreates the renderers, which would discard the per-test setup. + yield return null; + RenderPipeline.SubmitRenderRequest(m_Camera, new RenderPipeline.StandardRequest { destination = m_Destination }); + } + + [OneTimeTearDown] + public void OneTimeTearDown() + { + QualitySettings.renderPipeline = m_PreviousRenderPipelineAsset; + + foreach (var obj in m_Objects) + { + if (obj != null) + Object.DestroyImmediate(obj); + } + m_Objects.Clear(); + } + + // The drawn prepass cases check the expectations against the regular path + static IEnumerable PrepassCases() + { + foreach (var renderingMode in k_RenderingModes) + { + foreach (var prepassState in new[] { PrepassState.Drawn, PrepassState.SkippedByCullingMask, PrepassState.SkippedByLayerMask }) + { + // Deferred also skips the gbuffer pass with an empty culling mask, which leaves nothing to produce the normals + if (renderingMode == RenderingMode.Deferred && prepassState == PrepassState.SkippedByCullingMask) + continue; + + // Deferred ignores depth priming + var depthPrimingModes = renderingMode == RenderingMode.Deferred ? + new[] { DepthPrimingMode.Disabled } : new[] { DepthPrimingMode.Disabled, DepthPrimingMode.Forced }; + + foreach (var depthPrimingMode in depthPrimingModes) + { + foreach (bool depthInput in new[] { true, false }) + { + // Without a depth request, depth is only published when the prepass renders into the depth texture + if (!depthInput && (renderingMode == RenderingMode.Deferred || depthPrimingMode == DepthPrimingMode.Forced)) + continue; + + foreach (bool renderingLayers in new[] { false, true }) + { + string depth = depthInput ? "Yes" : "No"; + string layers = renderingLayers ? "Yes" : "No"; + yield return new TestCaseData(renderingMode, prepassState, depthPrimingMode, depthInput, renderingLayers) + .SetName($"PrepassGlobalTextures_MatchResourceData({renderingMode}, Prepass:{prepassState}, DepthPriming:{depthPrimingMode}, DepthInput:{depth}, RenderingLayers:{layers})"); + } + } + } + } + } + } + + [TestCaseSource(nameof(PrepassCases))] + public void PrepassGlobalTextures_MatchResourceData(RenderingMode renderingMode, PrepassState prepassState, DepthPrimingMode depthPrimingMode, bool depthInput, bool renderingLayers) + { + m_Camera.cullingMask = prepassState switch + { + PrepassState.SkippedByCullingMask => 0, + PrepassState.SkippedByLayerMask => ~(1 << k_PrepassLayer), + _ => ~0, + }; + + int rendererIndex = System.Array.IndexOf(k_RenderingModes, renderingMode); + ((UniversalRenderer)m_Asset.GetRenderer(rendererIndex)).depthPrimingMode = depthPrimingMode; + m_CameraData.SetRenderer(rendererIndex); + + var feature = m_Features[rendererIndex]; + var capturePass = feature.capturePass; + feature.requireRenderingLayers = renderingLayers; + capturePass.mismatches.Clear(); + capturePass.ConfigureInput(depthInput ? + ScriptableRenderPassInput.Depth | ScriptableRenderPassInput.Normal : ScriptableRenderPassInput.Normal); + + // Deferred produces the normals in the gbuffer pass + capturePass.renderPassEvent = renderingMode == RenderingMode.Deferred ? + RenderPassEvent.AfterRenderingGbuffer : RenderPassEvent.AfterRenderingPrePasses; + + RenderPipeline.SubmitRenderRequest(m_Camera, new RenderPipeline.StandardRequest { destination = m_Destination }); + + Assert.AreSame(capturePass, feature.capturePass, "The renderer was recreated during the render, discarding the test setup"); + Assert.IsEmpty(capturePass.mismatches, "Globals that don't match the resource data"); + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/SkippedPrepassTests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/SkippedPrepassTests.cs.meta new file mode 100644 index 00000000000..ca11f41c85f --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/SkippedPrepassTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: bed106e9b2bf4374cb998c7f735bf555 \ No newline at end of file diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/XRDisplayMSAATests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/XRDisplayMSAATests.cs new file mode 100644 index 00000000000..68325e31bd7 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/XRDisplayMSAATests.cs @@ -0,0 +1,233 @@ +using System.Collections; +using System.Collections.Generic; +using NUnit.Framework; +using UnityEngine.Experimental.Rendering; +using UnityEngine.Rendering.RenderGraphModule; +using UnityEngine.TestTools; + +namespace UnityEngine.Rendering.Universal.Tests +{ + // XR counterpart of RealBackbufferMSAATests: URP keeps the XR eye textures single-sampled while no XR camera + // renders MSAA directly into them (e.g. the camera goes through post-processing). + [TestFixture] + class XRDisplayMSAATests + { + const int k_AssetMsaaSampleCount = 4; + // Downgrade hysteresis + one-frame apply lag (eye textures are reallocated at the next XR frame start) + margin. + const int k_SettleFrames = UniversalRenderPipeline.realBackbufferMSAADowngradeDelayFrames + 1 + 3; + // Upgrades skip the hysteresis: 1 frame to request + 1 frame for the reallocation + 1 frame of margin. + const int k_UpgradeFrames = 3; + + RenderPipelineAsset m_PreviousQualityRenderPipelineAsset; + UniversalRenderPipelineAsset m_Asset; + UniversalRendererData m_RendererData; + Camera m_Camera; + bool m_Intermediate; + + readonly List m_DisabledCameras = new(); + readonly ForceIntermediatePass m_ForceIntermediatePass = new(); + ProbePass m_ProbePass; + + [OneTimeSetUp] + public void OneTimeSetUp() + { + // Captured before any early-out: NUnit runs OneTimeTearDown even when OneTimeSetUp ignores. + m_PreviousQualityRenderPipelineAsset = QualitySettings.renderPipeline; + + if (GraphicsSettings.currentRenderPipeline is not UniversalRenderPipelineAsset) + Assert.Ignore("These tests only run when URP is the active render pipeline."); + if (UniversalRenderer.PlatformRequiresExplicitMsaaResolve()) + Assert.Ignore("Platform resolves MSAA explicitly (no multisampled eye texture); the display target MSAA request is always 1, so there is nothing to test here."); + if (!XRSystem.displayActive) + Assert.Ignore("No active XR display."); + + foreach (var cam in Object.FindObjectsByType(FindObjectsInactive.Exclude)) + { + if (!cam.enabled) + continue; + cam.enabled = false; + m_DisabledCameras.Add(cam); + } + + m_RendererData = ScriptableObject.CreateInstance(); + m_RendererData.renderingMode = RenderingMode.Forward; + m_Asset = ScriptableObject.CreateInstance(); + m_Asset.m_RendererDataList[0] = m_RendererData; + // Pin every setting that feeds RequiresIntermediateColorTexture, so only the force-intermediate pass + // decides whether the camera renders directly. + m_Asset.supportsHDR = false; + m_Asset.supportsCameraOpaqueTexture = false; + m_Asset.supportsCameraDepthTexture = false; + m_Asset.renderScale = 1.0f; + QualitySettings.renderPipeline = m_Asset; + + RenderPipelineManager.beginCameraRendering += OnBeginCameraRendering; + } + + [OneTimeTearDown] + public void OneTimeTearDown() + { + RenderPipelineManager.beginCameraRendering -= OnBeginCameraRendering; + // Restoring the pipeline recreates it, which resets the XR display MSAA to the quality setting. + QualitySettings.renderPipeline = m_PreviousQualityRenderPipelineAsset; + + foreach (var cam in m_DisabledCameras) + { + if (cam != null) + cam.enabled = true; + } + m_DisabledCameras.Clear(); + + if (m_RendererData != null) + Object.DestroyImmediate(m_RendererData); + if (m_Asset != null) + Object.DestroyImmediate(m_Asset); + } + + [SetUp] + public void SetUp() + { + m_Asset.msaaSampleCount = k_AssetMsaaSampleCount; + m_Intermediate = false; + m_ProbePass = new ProbePass(); + + var go = new GameObject("MSAA Test XR Camera"); + m_Camera = go.AddComponent(); + m_Camera.allowMSAA = true; + m_Camera.allowHDR = false; + m_Camera.allowDynamicResolution = false; + var data = go.AddComponent(); + data.SetRenderer(0); + data.renderPostProcessing = false; + } + + [TearDown] + public void TearDown() + { + if (m_Camera != null) + Object.DestroyImmediate(m_Camera.gameObject); + } + + void OnBeginCameraRendering(ScriptableRenderContext context, Camera camera) + { + if (camera != m_Camera) + return; + + var renderer = camera.GetComponent().scriptableRenderer; + if (m_Intermediate) + renderer.EnqueuePass(m_ForceIntermediatePass); + renderer.EnqueuePass(m_ProbePass); + } + + [UnityTest] + public IEnumerator IntermediateToggles_DisplayFollows() + { + // Like toggling post-processing: the final pass becomes a full-screen blit, so the eye textures don't + // need MSAA, and get it back when the camera renders directly again. + yield return TickFrames(k_SettleFrames); + AssertDisplayMSAA(k_AssetMsaaSampleCount, checkEyeTexture: false); + // Where the provider doesn't multisample its eye textures, only the request can be checked. + bool eyeTextureMsaaSupported = m_ProbePass.backbufferMsaaSamples == k_AssetMsaaSampleCount; + + m_Intermediate = true; + yield return TickFrames(k_SettleFrames); + AssertDisplayMSAA(1, eyeTextureMsaaSupported); + + m_Intermediate = false; + yield return TickFrames(k_UpgradeFrames); + AssertDisplayMSAA(k_AssetMsaaSampleCount, eyeTextureMsaaSupported); + } + + [UnityTest] + public IEnumerator AssetMSAAChangedAtRuntime_DisplayFollows() + { + // A runtime asset change must reach the eye textures without recreating the pipeline. + const int k_ChangedSampleCount = 2; + yield return TickFrames(k_SettleFrames); + AssertDisplayMSAA(k_AssetMsaaSampleCount, checkEyeTexture: false); + bool eyeTextureMsaaSupported = m_ProbePass.backbufferMsaaSamples == k_AssetMsaaSampleCount; + + m_Asset.msaaSampleCount = k_ChangedSampleCount; + yield return TickFrames(k_UpgradeFrames); + AssertDisplayMSAA(k_ChangedSampleCount, eyeTextureMsaaSupported); + } + + [UnityTest] + public IEnumerator TileOnlyDeferred_KeepsMSAA_FallsBackToForward() + { + // Tile-only Deferred doesn't support MSAA, but must still request it so the renderer falls back to Forward instead of silently dropping MSAA. + m_RendererData.renderingMode = RenderingMode.Deferred; + m_RendererData.tileOnlyMode = true; + try + { + yield return TickFrames(k_SettleFrames); + var renderer = m_Asset.GetRenderer(0) as UniversalRenderer; + if (renderer == null || !renderer.useTileOnlyMode) + Assert.Ignore("Tile-only mode is not active on this platform."); + + AssertDisplayMSAA(k_AssetMsaaSampleCount, checkEyeTexture: false); + Assert.AreEqual(RenderingMode.Forward, m_ProbePass.renderingModeActual, "Tile-only Deferred with MSAA should fall back to Forward."); + } + finally + { + m_RendererData.renderingMode = RenderingMode.Forward; + m_RendererData.tileOnlyMode = false; + } + } + + void AssertDisplayMSAA(int expectedSamples, bool checkEyeTexture) + { + Assert.IsTrue(m_ProbePass.xrEnabled, "The test camera did not render as an XR camera."); + Assert.AreEqual(!m_Intermediate, m_ProbePass.activeTargetIsBackbuffer, + $"The test camera should render {(m_Intermediate ? "through an intermediate" : "directly to the eye textures")}."); + Assert.AreEqual(expectedSamples, (int)XRSystem.GetDisplayMSAASamples(), "Unexpected XR display MSAA request."); + if (checkEyeTexture) + Assert.AreEqual(expectedSamples, m_ProbePass.backbufferMsaaSamples, "The eye texture URP rendered to has an unexpected MSAA sample count."); + } + + static IEnumerator TickFrames(int count) + { + for (int i = 0; i < count; i++) + yield return null; + } + + class ForceIntermediatePass : ScriptableRenderPass + { + public ForceIntermediatePass() + { + requiresIntermediateTexture = true; + } + + public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) + { + } + } + + // Records the last render of the test camera: whether it rendered as XR, whether directly to the eye + // textures, and the MSAA sample count of the eye texture URP imported as the back buffer. + class ProbePass : ScriptableRenderPass + { + public bool xrEnabled; + public bool activeTargetIsBackbuffer; + public int backbufferMsaaSamples; + // Read while rendering: outside of it, the renderer can't see the XR display MSAA. + public RenderingMode renderingModeActual; + + public ProbePass() + { + renderPassEvent = RenderPassEvent.AfterRenderingOpaques; + } + + public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) + { + var cameraData = frameData.Get(); + var resourceData = frameData.Get(); + xrEnabled = cameraData.xr.enabled; + activeTargetIsBackbuffer = resourceData.isActiveTargetBackBuffer; + backbufferMsaaSamples = renderGraph.GetRenderTargetInfo(resourceData.backBufferColor).msaaSamples; + if (cameraData.renderer is UniversalRenderer universalRenderer) + renderingModeActual = universalRenderer.renderingModeActual; + } + } + } +} diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/XRDisplayMSAATests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/XRDisplayMSAATests.cs.meta new file mode 100644 index 00000000000..3ab46d7c300 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/XRDisplayMSAATests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 347f234cc981746e3bbd178e4d4dbc66 \ No newline at end of file diff --git a/Packages/com.unity.shadergraph/Documentation~/Input-Nodes.md b/Packages/com.unity.shadergraph/Documentation~/Input-Nodes.md index ffeb3873fbc..5f5110ef702 100644 --- a/Packages/com.unity.shadergraph/Documentation~/Input-Nodes.md +++ b/Packages/com.unity.shadergraph/Documentation~/Input-Nodes.md @@ -6,6 +6,7 @@ Supply shaders with essential data such as constants, mesh attributes, gradients | **Topic** | **Description** | |-----------|-----------------| +| [Active Shadow2D Light](active-shadow2d-light-node.md) | Outputs the position and radius of the 2D light that's casting the shadow, for use in Shadow2D shaders. | | [Light Texture](light-texture-node.md) | Outputs a shape light texture from the 2D Renderer for use in Sprite Custom Lit or Sprite Unlit shaders. | ## Basic diff --git a/Packages/com.unity.shadergraph/Documentation~/Scene-Depth-Node.md b/Packages/com.unity.shadergraph/Documentation~/Scene-Depth-Node.md index 1231620992b..fe98f208df1 100644 --- a/Packages/com.unity.shadergraph/Documentation~/Scene-Depth-Node.md +++ b/Packages/com.unity.shadergraph/Documentation~/Scene-Depth-Node.md @@ -4,7 +4,7 @@ The Scene Depth node samples the depth texture of the current camera, using the If you use the Universal Render Pipeline (URP), make sure the depth texture is enabled in the [URP asset](https://docs.unity3d.com/Manual/urp/universalrp-asset.html). Otherwise the Scene Depth node returns a value of 0.5 (mid-grey). -The Scene Depth node works only in the fragment [shader stage](Shader-Stage.md), and might not work if you set **Surface Type** to **Opaque** in the **Graph Inspector** window. +The Scene Depth node works only in the fragment [shader stage](Shader-Stage.md). In URP, the node returns the scene depth only if URP copies the scene depth to the depth texture before it renders the material. To use the Scene Depth node in a shader graph with **Surface Type** set to **Transparent**, set **Depth Texture Mode** to **After Opaques** or **Force Prepass**. If **Surface Type** is **Opaque**, set **Depth Texture Mode** to **Force Prepass**. For more information, refer to [Universal Renderer asset reference for URP](https://docs.unity3d.com/Manual/urp/urp-universal-renderer.html). To find out when the copy happens in a frame, use the [Frame Debugger](https://docs.unity3d.com/Manual/FrameDebugger-landing.html) or the [Render Graph Viewer](https://docs.unity3d.com/Manual/urp/render-graph-view.html). ## Render pipeline support diff --git a/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Custom-Lighting-Components.md b/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Custom-Lighting-Components.md index 65bda775d74..ea03efe53d7 100644 --- a/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Custom-Lighting-Components.md +++ b/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Custom-Lighting-Components.md @@ -42,7 +42,11 @@ The Additional Lights sub graphs compute the lighting contributions of the addit | :--- | :--- | | **LightBasic** | Computes very simple lighting and leaves out most lighting features in order to render as fast as possible. It calculates simple diffuse lighting and a simple form of ambient lighting. It does not support fog, reflections, specular, light cookies, or any other lighting features. But it does render fast and is ideal for low-end mobile devices and XR headsets. | | **LightColorize** | Example of the type of custom behavior you can create when you can control the lighting model. The main directional light renders the scene in grayscale with no color. Color is introduced with point lights so you can control where the scene has color based on where you place the point lights in the scene. | -| **LightSimple** | Same as the URP lighting model, except it uses the Blinn formula for the specular highlights. This makes it slightly cheaper to render than standard URP while looking fairly similar. If you still need all of the lighting features (specular, fog, screen space ambient occlusion, reflections, etc), but you want to make the lighting cheaper, this may be a good choice. | +| **LightCookTorrance** | Combines Lambert diffuse lighting and Cook-Torrance specular highlights with URP ambient lighting, reflections, and fog. It calculates lighting from the main light only. | +| **LightNoir** | Computes simple diffuse lighting from the main and additional lights, plus basic ambient lighting. It then removes all color, increases the contrast, and remaps the result through a gradient to create a high-contrast black-and-white look, similar to film noir. | +| **LightOrenNayar** | Combines Oren-Nayar diffuse lighting with URP ambient lighting, reflections, and fog. It doesn't calculate specular highlights. It calculates lighting from the main light only. | +| **LightSimple** | Same as the URP lighting model, except it uses the Blinn formula for the specular highlights. The Blinn formula makes it slightly cheaper to render than standard URP while looking fairly similar. If you need the full set of lighting features, including specular, fog, screen space ambient occlusion, and reflections, but want cheaper lighting, use this lighting model. | +| **LightStylized** | Combines custom-gradient diffuse lighting, stylized specular highlights, and stylized ambient lighting with fog, for an illustrative look. Use the **Specular** and **Exponent** inputs to control the highlights. It calculates lighting from the main light only. | | **LightToon** | Uses a Posterize operation to break the smooth lighting gradient into distinct bands of shading. It simulates the look of cartoons where lighting is rendered with distinct colors of paint rather than smooth gradients. | | **LightURP** | Closely matches the lighting that the Universal Render Pipeline does by default. If you want to start with the URP lighting and then alter it, this is the node to use. | @@ -60,7 +64,7 @@ The Additional Lights sub graphs compute the lighting contributions of the addit | **DiffuseCustomGradient** | Uses an input texture gradient instead of a dot product calculation to generate the lighting gradient. This allows you to paint the lighting as you see fit. | | **DiffuseHalfLambert** | Uses a Half Lambert formula that creates a lighting gradient that goes from 0 to 1 from the dark side to the bright side of the model. Because the gradient wraps all the way around the model instead of just halfway (as realistic lighting does), it has a softer, more stylized look. | | **DiffuseLambert** | Creates standard diffuse lighting using the dot product between the surface normal and the light vector. If the two vectors are pointing in the same direction, the surface has a diffuse value of 1. If the two vectors are perpendicular, the surface has a value of 0. The dark side of the model (facing away from the light) is clamped so that the result is also 0. | -| **DiffuseOrenNayar** | Uses the Oren Nayar lighting formula which simulates the lighting response of a rough surface like clay or plaster. The math used by this formula is quite expensive when you compare it with the subtle results that it provides, so you may find it sufficient to just use DiffuseLambert instead. | +| **DiffuseOrenNayar** | Uses the Oren-Nayar lighting formula which simulates the lighting response of a rough surface like clay or plaster. The math used by this formula is quite expensive when you compare it with the subtle results that it provides, so you may find it sufficient to just use DiffuseLambert instead. | ## Reflectance @@ -74,11 +78,21 @@ The Additional Lights sub graphs compute the lighting contributions of the addit | **Sub graph** | **Description** | | :--- | :--- | | **SpecularBlinn** | Calculates specular highlights using the Blinn formula. It’s cheaper than a more modern/realistic formula. | -| **SpecularCookTorrance** | Calculates specular highlights using the Cook Torrance formula. This method creates specular highlights that work well for brushed metal surfaces. | +| **SpecularCookTorrence** | Calculates specular highlights using the Cook-Torrance formula. This method creates specular highlights that work well for brushed metal surfaces. | | **SpecularPBR** | Calculates specular highlights using the GGX formula, which is popular in modern PBR lighting models. | | **SpecularStylized** | Calculates specular highlights in a less realistic, more stylized way. This specular works better for an illustrative style. | | **SpecularURP** | Calculates specular highlights using the same formula as the lighting that the Universal Render Pipeline uses. | +## Specular terms + +These sub graphs calculate the individual terms of the specular model that the **SpecularPBR** sub graph uses. They're available in the **Create Node** menu under **Lighting** > **Components** > **Specular** > **PBR**. + +| **Sub graph** | **Description** | +| :--- | :--- | +| **NormalDistributionTrowReitz** | Calculates the normal distribution term using the Trowbridge-Reitz (GGX) formula. The normal distribution term is the proportion of the surface's microfacets (the tiny details that make up a surface) that face the right way to reflect light toward the viewer. It takes the **roughSqr** (roughness squared) and **NdotH** (dot product of the normal and the half angle) inputs. | +| **SchlickFresnelReflectance** | Calculates the Fresnel term using Schlick's approximation. The Fresnel term is the percentage of incoming light that the surface reflects, which increases when you view the surface at a shallow angle. It takes the **viewDir**, **halfAngle**, and **Reflectance** inputs. The default **Reflectance** value is 0.04. | +| **SmithGGXGeometryTerm** | Calculates the geometry term using the Smith GGX formula. The geometry term measures how much the surface's microfacets shadow and mask each other. It takes the **roughSqr** (roughness squared), **nDotL** (dot product of the normal and the light direction), and **nDotV** (dot product of the normal and the view direction) inputs. | + ## Additional resources * [Introduction to lighting model customization](Shader-Graph-Sample-Custom-Lighting-Introduction.md) diff --git a/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Custom-Lighting-Lighting-Models.md b/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Custom-Lighting-Lighting-Models.md index 7f92aa7db4f..da0ba49801e 100644 --- a/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Custom-Lighting-Lighting-Models.md +++ b/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Custom-Lighting-Lighting-Models.md @@ -27,9 +27,17 @@ This lighting model does very simple lighting and leaves out most lighting featu This lighting model is an example of custom behavior type you can create when you can control the lighting model. The main directional light renders the scene in grayscale with no color. Color is introduced with point lights, which allows you to control where the scene has color based on where you place the point lights in the scene. +### Lit Cook Torrance + +This lighting model uses the Cook Torrance formula for specular highlights, which works well for brushed metal surfaces. It uses the same Lambert diffuse lighting, ambient lighting, reflections, and fog as the URP lighting model. It calculates lighting from the main light only. + +### Lit Oren Nayar + +This lighting model uses the Oren Nayar formula for diffuse lighting, which simulates rough surfaces such as clay or plaster. It uses the same ambient lighting, reflections, and fog as the URP lighting model, but doesn't calculate specular highlights. It calculates lighting from the main light only. + ### Lit Simple -This lighting model is the same as the URP lighting model, except it uses the Blinn formula for the specular highlights. This makes it slightly cheaper to render than standard URP while looking fairly similar. If you still need all of the lighting features (specular, fog, screen space ambient occlusion, reflections, etc), but you want to make the lighting cheaper, this may be a good choice. +This lighting model is the same as the URP lighting model, except it uses the Blinn formula for the specular highlights. The Blinn formula makes it slightly cheaper to render than standard URP while looking fairly similar. If you need the full set of lighting features, including specular, fog, screen space ambient occlusion, and reflections, but want cheaper lighting, use this lighting model. ### Lit Toon diff --git a/Packages/com.unity.shadergraph/Documentation~/TableOfContents.md b/Packages/com.unity.shadergraph/Documentation~/TableOfContents.md index 15209f491c9..3572c752f03 100644 --- a/Packages/com.unity.shadergraph/Documentation~/TableOfContents.md +++ b/Packages/com.unity.shadergraph/Documentation~/TableOfContents.md @@ -102,6 +102,7 @@ * [Dropdown](Dropdown-Node.md) * [Input](Input-Nodes.md) * 2D + * [Active Shadow2D Light](active-shadow2d-light-node.md) * [Light Texture](light-texture-node.md) * Basic * [Boolean](Boolean-Node.md) diff --git a/Packages/com.unity.shadergraph/Documentation~/active-shadow2d-light-node.md b/Packages/com.unity.shadergraph/Documentation~/active-shadow2d-light-node.md new file mode 100644 index 00000000000..4182541513d --- /dev/null +++ b/Packages/com.unity.shadergraph/Documentation~/active-shadow2d-light-node.md @@ -0,0 +1,39 @@ +--- +uid: active-shadow2d-light-node +--- + +# Active Shadow2D Light node + +The Active Shadow2D Light node outputs the position and radius of the 2D light that's currently casting the shadow. Use it in a Shadow2D shader graph to change the shape of a shadow based on the light, for example to make shadows longer as the light moves farther away. + +## Render pipeline compatibility + +| **Node** | **Universal Render Pipeline (URP)** | **High Definition Render Pipeline (HDRP)** | +| -------------------- | ------------------------------------- | --------------------------------------------- | +| **Active Shadow2D Light** | Yes | No | + +This node is only available with the **Shadow Caster 2D** shader graph target. + +## Ports + +| **Name** | **Direction** | **Type** | **Description** | +|------|-----------|------|-------------| +| **Position** | Output | Vector 3 | The position of the light GameObject in world space. | +| **Radius** | Output | Float | The radius of a circle, centered on the light position, that contains the whole area the light affects. | + +## Generated code example + +The following example code represents one possible outcome of this node. + +```hlsl +void Unity_ShadowCaster2DLight(out float3 Position, out float Radius) +{ + Position = _LightPos; + Radius = _ShadowRadius; +} +``` + +## Additional resources + +- [Shadow2D shader graph reference for URP](https://docs.unity3d.com/Manual/urp/prebuilt-shader-graphs-urp-shadow2d.html) +- [Create a custom material for 2D shadows](https://docs.unity3d.com/Manual/urp/2d-shadow-custom-material.html) diff --git a/Packages/com.unity.shadergraph/Documentation~/surface-options.md b/Packages/com.unity.shadergraph/Documentation~/surface-options.md index 3db7a009360..43176d5a7da 100644 --- a/Packages/com.unity.shadergraph/Documentation~/surface-options.md +++ b/Packages/com.unity.shadergraph/Documentation~/surface-options.md @@ -14,11 +14,12 @@ Enable **Allow Material Override** to modify a specific set of properties for Un | **Surface Type** | Refer to the URP documentation for the [Lit URP](https://docs.unity3d.com/Manual/urp/lit-shader.html) and [Unlit URP](https://docs.unity3d.com/Manual/urp/unlit-shader.html) shaders.
**Note**: In the Built-In Render Pipeline, this feature has the same behavior as in URP. | | **Render Face** | Specifies which faces of the mesh the shader renders. The options are:
  • **Front**: Renders only front-facing triangles. This is the default.
  • **Back**: Renders only back-facing triangles.
  • **Both**: Renders both front and back faces.
| | **Alpha Clipping** | Refer to the URP documentation for the [Lit URP](https://docs.unity3d.com/Manual/urp/lit-shader.html) and [Unlit URP](https://docs.unity3d.com/Manual/urp/unlit-shader.html) shaders.
**Note**: In the Built-In Render Pipeline, this feature has the same behavior as in URP. | +| **Depth Write** | Determines whether the GPU writes pixels to the [depth buffer](https://en.wikipedia.org/wiki/Z-buffering) when it uses this shader to render geometry. The options are:
  • **Auto** (default): Unity writes pixels to the depth buffer for opaque materials, but not for transparent materials.
  • **Force Enabled**: Unity always writes pixels to the depth buffer.
  • **Force Disabled**: Unity never writes pixels to the depth buffer.
This option's functionality corresponds to the command [ZWrite](https://docs.unity3d.com/Manual/SL-ZWrite.html) in [ShaderLab](https://docs.unity3d.com/Manual/SL-Reference.html). To override this setting in a [RenderStateBlock](https://docs.unity3d.com/ScriptReference/Rendering.RenderStateBlock.html), set the [depthState](https://docs.unity3d.com/ScriptReference/Rendering.RenderStateBlock-depthState.html) property.
**Note**: Applies only to the Built-In Render Pipeline. In URP, use **Override Depth** and **Write Depth** instead. | | **Override Depth** | Enables explicit control over depth writes and the depth test for this Shader Graph. When disabled, depth follows the default behavior for the surface type: enabled for opaque, disabled for transparent. When enabled, **Write Depth** and **Depth Test** become editable.
**Note**: Not applicable to the Built-In Render Pipeline. | | **Write Depth** | Determines whether the GPU writes pixels to the [depth buffer](https://en.wikipedia.org/wiki/Z-buffering) when it uses this shader to render geometry. This option's functionality corresponds to the command [ZWrite](https://docs.unity3d.com/Manual/SL-ZWrite.html) in [ShaderLab](https://docs.unity3d.com/Manual/SL-Reference.html). To override this setting in a [RenderStateBlock](https://docs.unity3d.com/ScriptReference/Rendering.RenderStateBlock.html), set the [depthState](https://docs.unity3d.com/ScriptReference/Rendering.RenderStateBlock-depthState.html).
This property is only available if **Override Depth** is enabled.
**Note**: Not applicable to the Built-In Render Pipeline. | -| **Depth Test** | Sets the conditions under which pixels pass or fail depth testing. The GPU does not draw pixels that fail a depth test. If you choose anything other than **LEqual** (the default), consider also changing the rendering order of this material. The options are:
  • **LEqual** (default): Unity draws the pixel if its depth value is less than or equal to the value in the depth texture.
  • **Never**: Unity never draws pixels of the affected surface.
  • **Less**: Unity draws pixels if their depth coordinates are less than the current depth buffer value.
  • **Greater**: Unity draws pixels if their depth coordinates are greater than the current depth buffer value.
  • **GEqual**: Unity draws pixels if their depth coordinates are greater than or equal to the current depth buffer value.
  • **Equal**: Unity draws pixels if their depth coordinates are equal to the current depth buffer value.
  • **NotEqual**: Unity draws pixels if their depth coordinates are not the same as the current depth buffer value.
  • **Always**: Unity draws this surface to your screen regardless of its z-coordinate.
This option's functionality corresponds to the command [ZTest](https://docs.unity3d.com/Manual/SL-ZTest.html) in ShaderLab. To override this setting in a [RenderStateBlock](https://docs.unity3d.com/ScriptReference/Rendering.RenderStateBlock.html), set the [depthState](https://docs.unity3d.com/ScriptReference/Rendering.RenderStateBlock-depthState.html) property.
This property is only available if **Override Depth** is enabled.
**Note**: Not applicable to the Built-In Render Pipeline. | -| **Override Stencil** | Processes and overrides the Stencil buffer values. When enabled, the [**Stencil** sub-properties](#stencil-subproperties) are available. For more information about how stencil works in shaders, refer to [ShaderLab command: Stencil](https://docs.unity3d.com/Manual/SL-Stencil.html).
**Note**: Not applicable to the Built-In Render Pipeline. | -| **Override Passes** | Controls which passes the depth and stencil state overrides apply to. Toggle each pass independently:
  • **Color Pass**: Apply during the main forward color pass (opaque or transparent).
  • **PrePass**: Apply during the depth or depth-normals prepass. Opaque only.
  • **Shadow Pass**: Apply during the shadow caster pass. Requires the renderer's **Shadowmap Stencil** setting to be enabled, otherwise the shadowmap has no stencil bits to write to.
This property is shown for Opaque surfaces and any time **Allow Material Override** is on.
**Note**: Not applicable to the Built-In Render Pipeline. | +| **Depth Test** | Sets the conditions under which pixels pass or fail depth testing. The GPU does not draw pixels that fail a depth test. If you choose anything other than **LEqual** (the default), consider also changing the rendering order of this material. The options are:
  • **LEqual** (default): Unity draws the pixel if its depth value is less than or equal to the value in the depth texture.
  • **Never**: Unity never draws pixels of the affected surface.
  • **Less**: Unity draws pixels if their depth coordinates are less than the current depth buffer value.
  • **Greater**: Unity draws pixels if their depth coordinates are greater than the current depth buffer value.
  • **GEqual**: Unity draws pixels if their depth coordinates are greater than or equal to the current depth buffer value.
  • **Equal**: Unity draws pixels if their depth coordinates are equal to the current depth buffer value.
  • **NotEqual**: Unity draws pixels if their depth coordinates are not the same as the current depth buffer value.
  • **Always**: Unity draws this surface to your screen regardless of its z-coordinate.
This option's functionality corresponds to the command [ZTest](https://docs.unity3d.com/Manual/SL-ZTest.html) in ShaderLab. To override this setting in a [RenderStateBlock](https://docs.unity3d.com/ScriptReference/Rendering.RenderStateBlock.html), set the [depthState](https://docs.unity3d.com/ScriptReference/Rendering.RenderStateBlock-depthState.html) property.
In URP, this property is available only when you enable **Override Depth**. In the Built-In Render Pipeline, this property is always available. | +| **Override Stencil** | Processes and overrides the Stencil buffer values. When enabled, the [**Stencil** sub-properties](#stencil-subproperties) are available. For more information about how stencil works in shaders, refer to [ShaderLab command: Stencil](https://docs.unity3d.com/Manual/SL-Stencil.html).
This property is available only in the Lit and Unlit Shader Graphs.
**Note**: Not applicable to the Built-In Render Pipeline. | +| **Override Passes** | Controls which passes the depth and stencil state overrides apply to. Toggle each pass independently:
  • **Color Pass**: Apply during the main forward color pass (opaque or transparent).
  • **Depth Prepass**: Apply during the depth or depth-normals prepass. Opaque only.
  • **Shadow Pass**: Apply during the shadow caster pass. Requires the renderer's **Shadowmap Stencil** setting to be enabled, otherwise the shadowmap has no stencil bits to write to.
This property is available only when you enable **Allow Material Override**, **Override Depth**, or **Override Stencil**.
**Note**: Not applicable to the Built-In Render Pipeline. | ## Stencil override sub-properties @@ -30,14 +31,25 @@ When **Render Face** is set to **Both**, the per-face properties (**Compare Func | Property | Behavior | | :--- | :--- | -| **Stencil Ref** | Sets the reference value that **Compare Function** compares against the stencil buffer value for each pixel. Unity writes this value to the buffer if **Pass** is set to **Replace**. Edit the value by typing a decimal number or by clicking individual bit cells (MSB on the left). The valid range matches the user-accessible portion of the stencil byte that the URP renderer reserves for shaders. | -| **Read Mask** | Sets the binary AND mask applied to stencil values before comparison. The default is `0xFF`. | -| **Write Mask** | Sets the binary AND mask applied to stencil values before the stencil write operation (**Pass**, **Fail**, **Z Fail**). The default is `0xFF`. | +| **Stencil Ref** | Sets the reference value that **Compare Function** compares against the stencil buffer value for each pixel. Unity writes this value to the buffer if **Pass** is set to **Replace**. Enter a value from 0 to 15. The valid range matches the user-accessible portion of the stencil byte that the URP renderer reserves for shaders. | +| **Read Mask** | Sets the binary AND mask applied to stencil values before comparison. The default is 15. | +| **Write Mask** | Sets the binary AND mask applied to stencil values before the stencil write operation (**Pass**, **Fail**, **Z Fail**). The default is 15. | | **Compare Function** | Sets the function Unity uses to compare the **Stencil Ref** value with the value in the stencil buffer, for each pixel. For the list of available functions, refer to [CompareFunction](https://docs.unity3d.com/ScriptReference/Rendering.CompareFunction.html). | | **Pass** | Sets the stencil operation Unity performs on the stencil value when the stencil test passes. For the list of available operations, refer to [StencilOp](https://docs.unity3d.com/ScriptReference/Rendering.StencilOp.html). | | **Fail** | Sets the stencil operation Unity performs on the stencil value when the stencil test fails. For the list of available operations, refer to [StencilOp](https://docs.unity3d.com/ScriptReference/Rendering.StencilOp.html) | | **Z Fail** | Sets the stencil operation Unity performs on the stencil value when the stencil test passes but the Z test fails. For the list of available operations, refer to [StencilOp](https://docs.unity3d.com/ScriptReference/Rendering.StencilOp.html) | +## Depth and stencil settings in the Material Inspector + +The depth and stencil settings in the Material Inspector use the same labels and order as in the Graph Inspector, with the following differences: + +- **Override Stencil** appears in the Material Inspector only when you enable both **Allow Material Override** and **Override Stencil** in the Graph Inspector. +- **Override Passes** isn't available in the Material Inspector. +- Unity doesn't save the **Override Stencil** setting with the material. The Material Inspector enables **Override Stencil** only when **Compare Function**, **Pass**, **Fail**, or **Z Fail** differs from its default. If you enable **Override Stencil** and leave these settings at their defaults, **Override Stencil** is disabled again when Unity reloads the Material Inspector, for example after you restart the Unity Editor. Changing only **Stencil Ref**, **Read Mask**, or **Write Mask** doesn't keep **Override Stencil** enabled. +- Disabling **Override Depth** resets **Write Depth** to the default for the surface type and **Depth Test** to **LEqual**. If you enable **Override Depth** again, Unity doesn't restore the previous values. +- Disabling **Override Stencil** resets **Compare Function** to **Always**, and **Pass**, **Fail**, and **Z Fail** to **Keep**, for both faces. **Stencil Ref**, **Read Mask**, and **Write Mask** keep their values. +- When **Render Face** is set to **Both**, **Front Face** and **Back Face** are foldouts, collapsed by default. Expand them to view the per-face settings. + ## Write Color toggle (URP Unlit only) The Unlit Shader Graph has an additional **Write Color** toggle. The toggle is enabled by default. Disable it to reduce the shader to a utility that writes only to the depth and stencil buffers and never to color. Use this to mask geometry into the depth or stencil buffer without affecting the rendered image. diff --git a/Packages/com.unity.shadergraph/Editor/Data/Graphs/CubemapInputMaterialSlot.cs b/Packages/com.unity.shadergraph/Editor/Data/Graphs/CubemapInputMaterialSlot.cs index 58a285908e8..95c553aa443 100644 --- a/Packages/com.unity.shadergraph/Editor/Data/Graphs/CubemapInputMaterialSlot.cs +++ b/Packages/com.unity.shadergraph/Editor/Data/Graphs/CubemapInputMaterialSlot.cs @@ -95,7 +95,10 @@ public void GetSourceAssetDependencies(AssetCollection assetCollection) var guidString = m_Cubemap.guid; if (!string.IsNullOrEmpty(guidString) && GUID.TryParse(guidString, out var guid)) { - assetCollection.AddAssetDependency(guid, AssetCollection.Flags.IncludeInExportPackage); + assetCollection.AddAssetDependency( + guid, + AssetCollection.Flags.ArtifactDependency | + AssetCollection.Flags.IncludeInExportPackage); } } } diff --git a/Packages/com.unity.shadergraph/Editor/Data/Graphs/GraphData.ShaderInterface.cs b/Packages/com.unity.shadergraph/Editor/Data/Graphs/GraphData.ShaderInterface.cs index b863b1db154..a1a3e3c9b55 100644 --- a/Packages/com.unity.shadergraph/Editor/Data/Graphs/GraphData.ShaderInterface.cs +++ b/Packages/com.unity.shadergraph/Editor/Data/Graphs/GraphData.ShaderInterface.cs @@ -1,52 +1,11 @@ using System; using System.Collections.Generic; using Unity.GraphAuthoring.Editor.ProviderSystem; +using UnityEditor.ShaderGraph.ProviderSystem; using UnityEngine; -using UnityEngine.UIElements; namespace UnityEditor.ShaderGraph { - // Serialize Shader Interface mode as a data extension so that the mode doesn't leak into assets that don't use the feature. - [Serializable] - [HasDependencies(typeof(ShaderInterfaceGraphData))] - sealed class ShaderInterfaceGraphData : AbstractShaderGraphDataExtension, IHasDependencies, IHasAssetDependencies - { - [SerializeReference] - IProvider m_ShaderInterface; - - internal IProvider shaderInterface - { - get => m_ShaderInterface; - set => m_ShaderInterface = (IProvider)value?.Clone(); - } - - internal override string displayName => "Shader Interface"; - - internal override void OnPropertiesGUI(VisualElement context, Action onChange, Action registerUndo, GraphData owner) - { - } - - public bool Reload(HashSet changedAssetGuids) - { - if (m_ShaderInterface == null || !changedAssetGuids.Contains(m_ShaderInterface.AssetID.ToString())) - return false; - - m_ShaderInterface.Reload(); - return true; - } - - public void GetSourceAssetDependencies(AssetCollection assetCollection) - { - if (m_ShaderInterface == null || m_ShaderInterface.AssetID == default) - return; - - assetCollection.AddAssetDependency(m_ShaderInterface.AssetID, - AssetCollection.Flags.SourceDependency - | AssetCollection.Flags.ArtifactDependency - | AssetCollection.Flags.IncludeInExportPackage); - } - } - sealed partial class GraphData { // The mode is still in development, so it only takes effect in Internal Mode. @@ -80,7 +39,29 @@ internal bool isShaderInterfaceMode internal IProvider shaderInterface => shaderInterfaceData?.shaderInterface; + internal IReadOnlyList virtualFunctionStacks + => shaderInterfaceData?.stacks ?? (IReadOnlyList)Array.Empty(); + + internal List> loadedVirtualFunctions + { + get + { + List> functions = new(); + if (shaderInterface is ShaderInterfaceProvider { IsValid: true } shaderInterfaceProvider) + foreach (var function in shaderInterfaceProvider.VirtualFunctionProviders) + if (function.IsValid) + functions.Add(function); + return functions; + } + } + + bool m_ShaderInterfaceChanged; + + // Not set by undo and redo, which replace the interface and its stacks wholesale. + internal bool shaderInterfaceChanged => m_ShaderInterfaceChanged; + // Records undo; the window rebuilds its view when the mode changes. + // Output nodes exist only in stacks, so leaving removes them; other local provider nodes become orphans. internal void SwitchShaderInterfaceMode(bool enabled) { if (isShaderInterfaceMode == enabled) @@ -88,13 +69,110 @@ internal void SwitchShaderInterfaceMode(bool enabled) owner?.RegisterCompleteObjectUndo(enabled ? "Enter Shader Interface Mode" : "Exit Shader Interface Mode"); isShaderInterfaceMode = enabled; + if (!enabled) + { + foreach (var output in new List(GetNodes())) + RemoveNodeAndEdgesNoValidate(output); + } + m_ShaderInterfaceChanged = true; + ValidateGraph(); } + // Callers record undo. internal void SetShaderInterface(IProvider provider) { var data = shaderInterfaceData; - if (data != null) - data.shaderInterface = provider; + if (data == null) + return; + + var previous = data.shaderInterface; + data.shaderInterface = provider; + if (previous != null) + data.shaderInterface?.CopyStateFrom(previous); + + // Nodes the new interface doesn't declare stay as orphans, so picking one that declares them again recovers them. + SyncVirtualFunctionStacks(); + m_ShaderInterfaceChanged = true; + ValidateGraph(); + } + + internal bool TryGetVirtualFunctionProvider(string key, out IProvider provider) + { + provider = null; + return shaderInterface is ShaderInterfaceProvider shaderInterfaceProvider && shaderInterfaceProvider.TryGetVirtualFunctionProvider(key, out provider); + } + + // Callers record undo. + internal void SetEnsureBaseCall(string key, bool ensureBaseCall) + { + if (!TryGetVirtualFunctionProvider(key, out var provider) || provider is not VirtualFunctionProvider function) + return; + + function.EnsureBaseCall = ensureBaseCall; + foreach (var node in GetNodes()) + if (node.providerKey == key) + node.Refresh(); + } + + // Callers record undo. + internal void AddLocalProviderNode(AbstractProviderNode node, IProvider provider, Vector2 position) where T : IDefinition + { + node.InitializeFromLocalProvider(provider); + var drawState = node.drawState; + drawState.position = new Rect(position, Vector2.zero); + node.drawState = drawState; + AddNode(node); + } + + // Runs only when the interface changes, never from validation. Orphaned output nodes keep their stacks. + internal void SyncVirtualFunctionStacks() + { + if (!isShaderInterfaceMode) + return; + + var functions = loadedVirtualFunctions; + var outputs = VirtualFunctionOutputNodesByKey(); + AddMissingOutputNodes(functions, outputs); + var data = shaderInterfaceData; + m_ShaderInterfaceChanged |= data.SetStacks(VirtualFunctionStackData.StacksFor(functions, outputs.Keys, data.stacks)); + } + + internal Dictionary VirtualFunctionOutputNodesByKey() + { + Dictionary outputs = new(); + foreach (var output in GetNodes()) + outputs.TryAdd(output.providerKey ?? string.Empty, output); + return outputs; + } + + void AddMissingOutputNodes(List> functions, Dictionary outputs) + { + foreach (var function in functions) + { + var key = function.Info.ProviderKey; + if (outputs.ContainsKey(key)) + continue; + + var output = new VirtualFunctionOutputNode(); + output.InitializeFromLocalProvider(function); + AddNodeNoValidate(output); + outputs.Add(key, output); + } + } + + // Skipped during a replace, which brings its own stacks. + void RemoveFromVirtualFunctionStack(VirtualFunctionOutputNode output) + { + if (!replaceInProgress && shaderInterfaceData?.RemoveFromStack(output.providerKey ?? string.Empty) == true) + m_ShaderInterfaceChanged = true; + } + + void RemoveNodeAndEdgesNoValidate(AbstractMaterialNode node) + { + if (m_NodeEdges.TryGetValue(node.objectId, out var edges)) + foreach (var edge in edges.ToArray()) + RemoveEdgeNoValidate(edge); + RemoveNodeNoValidate(node); } } } diff --git a/Packages/com.unity.shadergraph/Editor/Data/Graphs/GraphData.cs b/Packages/com.unity.shadergraph/Editor/Data/Graphs/GraphData.cs index b1d20ee3da2..bde19e2df8b 100644 --- a/Packages/com.unity.shadergraph/Editor/Data/Graphs/GraphData.cs +++ b/Packages/com.unity.shadergraph/Editor/Data/Graphs/GraphData.cs @@ -11,6 +11,7 @@ using UnityEditor.ShaderGraph.Drawing; using UnityEditor.ShaderGraph.Internal; using UnityEditor.ShaderGraph.Legacy; +using UnityEditor.ShaderGraph.ProviderSystem; using UnityEditor.ShaderGraph.Serialization; using UnityEngine; using UnityEngine.Assertions; @@ -445,8 +446,23 @@ internal bool ReloadDataExtensions(HashSet changedAssetGuids) { bool reloaded = false; foreach (var subData in SubDatas) - if (subData is IHasAssetDependencies dependent) - reloaded |= dependent.Reload(changedAssetGuids); + { + if (subData is not IHasAssetDependencies dependent || !dependent.Reload(changedAssetGuids)) + continue; + reloaded = true; + // A reloaded interface can change what it declares without changing the stacks. + m_ShaderInterfaceChanged |= subData is ShaderInterfaceGraphData; + } + return reloaded; + } + + // Extensions first, since local provider nodes look their providers up through the interface. + internal bool ReloadAssetDependencies(HashSet changedAssetGuids) + { + bool reloaded = ReloadDataExtensions(changedAssetGuids); + foreach (var node in GetNodes()) + reloaded |= node.Reload(changedAssetGuids); + SyncVirtualFunctionStacks(); return reloaded; } @@ -754,6 +770,7 @@ public void ClearChanges() m_PastedStickyNotes.Clear(); m_MostRecentlyCreatedGroup = null; m_MovedContexts = false; + m_ShaderInterfaceChanged = false; } public void AddNode(AbstractMaterialNode node, bool usePreviewPref = true) @@ -1099,6 +1116,9 @@ void RemoveNodeNoValidate(AbstractMaterialNode node) // Remove from ContextData blockNode.contextData.blocks.Remove(blockNode); } + + if (node is VirtualFunctionOutputNode output) + RemoveFromVirtualFunctionStack(output); } void AddEdgeToNodeEdges(IEdge edge) @@ -2541,11 +2561,11 @@ public override void OnAfterDeserialize(string json) // ColorShaderProperty is the only Property case where `GetDefaultReferenceName` was overriden if (MultiJson.ParseType(serializedProperty.typeInfo.fullName) == typeof(ColorShaderProperty)) { - defaultReferenceNameField.SetValue(property, $"Color_{GuidEncoder.Encode(Guid.Parse(input0.m_Guid.m_GuidSerialized))}"); + defaultReferenceNameField.SetValue(property, $"Color_{GuidEncoder.EncodeLegacy(Guid.Parse(input0.m_Guid.m_GuidSerialized))}"); } else { - defaultReferenceNameField.SetValue(property, $"{property.concreteShaderValueType}_{GuidEncoder.Encode(Guid.Parse(input0.m_Guid.m_GuidSerialized))}"); + defaultReferenceNameField.SetValue(property, $"{property.concreteShaderValueType}_{GuidEncoder.EncodeLegacy(Guid.Parse(input0.m_Guid.m_GuidSerialized))}"); } } } @@ -2961,6 +2981,11 @@ void DeserializeContextData(ContextData contextData, ShaderStage stage) } SortActiveTargets(); + + // The interface may have changed since saving; undo and redo also restore graphs through here. + SyncVirtualFunctionStacks(); + // Views are built from the loaded nodes, so the output nodes the sync adds aren't changes to report. + m_AddedNodes.Clear(); } private void ReplaceNodeWithNode(LegacyUnknownTypeNode nodeToReplace, AbstractMaterialNode nodeReplacement) diff --git a/Packages/com.unity.shadergraph/Editor/Data/Graphs/GraphValidation.cs b/Packages/com.unity.shadergraph/Editor/Data/Graphs/GraphValidation.cs index 895a01e7f11..95316192db9 100644 --- a/Packages/com.unity.shadergraph/Editor/Data/Graphs/GraphValidation.cs +++ b/Packages/com.unity.shadergraph/Editor/Data/Graphs/GraphValidation.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Reflection; using UnityEditor.Graphing; +using UnityEditor.ShaderGraph.ProviderSystem; using UnityEngine; namespace UnityEditor.ShaderGraph @@ -125,9 +126,10 @@ public static void ValidateNode(AbstractMaterialNode node) node.SetOverrideActiveState(AbstractMaterialNode.ActiveState.ExplicitInactive); node.owner.AddValidationError(node.objectId, $"{node.name} Node is not allowed by any active targets, and will not be used in generation", Rendering.ShaderCompilerMessageSeverity.Warning); } + // Orphaned provider nodes stay inactive. else { - node.SetOverrideActiveState(AbstractMaterialNode.ActiveState.Implicit); + node.SetOverrideActiveState(node is IProviderNode { isOrphaned: true } ? AbstractMaterialNode.ActiveState.ExplicitInactive : AbstractMaterialNode.ActiveState.Implicit); } } } diff --git a/Packages/com.unity.shadergraph/Editor/Data/Graphs/SerializableCubemap.cs b/Packages/com.unity.shadergraph/Editor/Data/Graphs/SerializableCubemap.cs index 8000cc8de7c..411ea4ebe73 100644 --- a/Packages/com.unity.shadergraph/Editor/Data/Graphs/SerializableCubemap.cs +++ b/Packages/com.unity.shadergraph/Editor/Data/Graphs/SerializableCubemap.cs @@ -96,7 +96,7 @@ public void OnBeforeSerialize() // (m_SerializedCubemap or m_Guid) and doesn't need to be re-serialized. // We must not use the cubemap property getter here because it would // force-load the asset, which is not safe in all contexts (e.g. domain backup). - if (m_Cubemap != null) + if ((object)m_Cubemap != null && string.IsNullOrEmpty(m_SerializedCubemap)) m_SerializedCubemap = EditorJsonUtility.ToJson(new CubemapHelper { cubemap = m_Cubemap }, false); } diff --git a/Packages/com.unity.shadergraph/Editor/Data/Graphs/SerializableMesh.cs b/Packages/com.unity.shadergraph/Editor/Data/Graphs/SerializableMesh.cs index 3e84560c3ee..6fefd36a559 100644 --- a/Packages/com.unity.shadergraph/Editor/Data/Graphs/SerializableMesh.cs +++ b/Packages/com.unity.shadergraph/Editor/Data/Graphs/SerializableMesh.cs @@ -53,7 +53,10 @@ public Mesh mesh public void OnBeforeSerialize() { - m_SerializedMesh = EditorJsonUtility.ToJson(new MeshHelper { mesh = mesh }, false); + if (!string.IsNullOrEmpty(m_SerializedMesh) || (object)m_Mesh == null) + return; + + m_SerializedMesh = EditorJsonUtility.ToJson(new MeshHelper { mesh = m_Mesh }, false); } public void OnAfterDeserialize() diff --git a/Packages/com.unity.shadergraph/Editor/Data/Graphs/SerializableTexture.cs b/Packages/com.unity.shadergraph/Editor/Data/Graphs/SerializableTexture.cs index 0fa209ea59c..603c1e8ee81 100644 --- a/Packages/com.unity.shadergraph/Editor/Data/Graphs/SerializableTexture.cs +++ b/Packages/com.unity.shadergraph/Editor/Data/Graphs/SerializableTexture.cs @@ -92,8 +92,10 @@ public Texture texture public void OnBeforeSerialize() { - var textureHelper = texture ? new TextureHelper { texture = texture } : null; - m_SerializedTexture = EditorJsonUtility.ToJson(textureHelper, false); + if (!string.IsNullOrEmpty(m_SerializedTexture) || (object)m_Texture == null) + return; + + m_SerializedTexture = EditorJsonUtility.ToJson(new TextureHelper { texture = m_Texture }, false); } public void OnAfterDeserialize() diff --git a/Packages/com.unity.shadergraph/Editor/Data/Graphs/SerializableTextureArray.cs b/Packages/com.unity.shadergraph/Editor/Data/Graphs/SerializableTextureArray.cs index cc9f8588942..e076fd30322 100644 --- a/Packages/com.unity.shadergraph/Editor/Data/Graphs/SerializableTextureArray.cs +++ b/Packages/com.unity.shadergraph/Editor/Data/Graphs/SerializableTextureArray.cs @@ -92,7 +92,10 @@ public Texture2DArray textureArray public void OnBeforeSerialize() { - m_SerializedTexture = EditorJsonUtility.ToJson(new TextureHelper { textureArray = textureArray }, false); + if (!string.IsNullOrEmpty(m_SerializedTexture) || (object)m_TextureArray == null) + return; + + m_SerializedTexture = EditorJsonUtility.ToJson(new TextureHelper { textureArray = m_TextureArray }, false); } public void OnAfterDeserialize() diff --git a/Packages/com.unity.shadergraph/Editor/Data/Graphs/Texture2DArrayInputMaterialSlot.cs b/Packages/com.unity.shadergraph/Editor/Data/Graphs/Texture2DArrayInputMaterialSlot.cs index c09a04ed2fc..258b2558ded 100644 --- a/Packages/com.unity.shadergraph/Editor/Data/Graphs/Texture2DArrayInputMaterialSlot.cs +++ b/Packages/com.unity.shadergraph/Editor/Data/Graphs/Texture2DArrayInputMaterialSlot.cs @@ -94,7 +94,10 @@ public void GetSourceAssetDependencies(AssetCollection assetCollection) var guidString = m_TextureArray.guid; if (!string.IsNullOrEmpty(guidString) && GUID.TryParse(guidString, out var guid)) { - assetCollection.AddAssetDependency(guid, AssetCollection.Flags.IncludeInExportPackage); + assetCollection.AddAssetDependency( + guid, + AssetCollection.Flags.ArtifactDependency | + AssetCollection.Flags.IncludeInExportPackage); } } } diff --git a/Packages/com.unity.shadergraph/Editor/Data/Graphs/Texture2DInputMaterialSlot.cs b/Packages/com.unity.shadergraph/Editor/Data/Graphs/Texture2DInputMaterialSlot.cs index 368f0e2c6e0..1a44b6adced 100644 --- a/Packages/com.unity.shadergraph/Editor/Data/Graphs/Texture2DInputMaterialSlot.cs +++ b/Packages/com.unity.shadergraph/Editor/Data/Graphs/Texture2DInputMaterialSlot.cs @@ -105,7 +105,10 @@ public void GetSourceAssetDependencies(AssetCollection assetCollection) var guidString = m_Texture.guid; if (!string.IsNullOrEmpty(guidString) && GUID.TryParse(guidString, out var guid)) { - assetCollection.AddAssetDependency(guid, AssetCollection.Flags.IncludeInExportPackage); + assetCollection.AddAssetDependency( + guid, + AssetCollection.Flags.ArtifactDependency | + AssetCollection.Flags.IncludeInExportPackage); } } } diff --git a/Packages/com.unity.shadergraph/Editor/Data/Graphs/Texture3DInputMaterialSlot.cs b/Packages/com.unity.shadergraph/Editor/Data/Graphs/Texture3DInputMaterialSlot.cs index 7bf364c0832..08e2c705cd3 100644 --- a/Packages/com.unity.shadergraph/Editor/Data/Graphs/Texture3DInputMaterialSlot.cs +++ b/Packages/com.unity.shadergraph/Editor/Data/Graphs/Texture3DInputMaterialSlot.cs @@ -94,7 +94,10 @@ public void GetSourceAssetDependencies(AssetCollection assetCollection) var guidString = m_Texture.guid; if (!string.IsNullOrEmpty(guidString) && GUID.TryParse(guidString, out var guid)) { - assetCollection.AddAssetDependency(guid, AssetCollection.Flags.IncludeInExportPackage); + assetCollection.AddAssetDependency( + guid, + AssetCollection.Flags.ArtifactDependency | + AssetCollection.Flags.IncludeInExportPackage); } } } diff --git a/Packages/com.unity.shadergraph/Editor/Data/Nodes/GuidEncoder.cs b/Packages/com.unity.shadergraph/Editor/Data/Nodes/GuidEncoder.cs index 42fbfe7ff7e..55f49cb48c6 100644 --- a/Packages/com.unity.shadergraph/Editor/Data/Nodes/GuidEncoder.cs +++ b/Packages/com.unity.shadergraph/Editor/Data/Nodes/GuidEncoder.cs @@ -8,5 +8,27 @@ public static string Encode(Guid guid) { return guid.ToString("N"); } + + internal static string EncodeLegacy(Guid guid) + { + string encoded = Convert.ToBase64String(guid.ToByteArray()); + return MonoStringHash(encoded).ToString("X"); + } + + static int MonoStringHash(string value) + { + unchecked + { + int hash1 = 5381; + int hash2 = hash1; + for (int i = 0; i < value.Length; i += 2) + { + hash1 = ((hash1 << 5) + hash1) ^ value[i]; + if (i + 1 < value.Length) + hash2 = ((hash2 << 5) + hash2) ^ value[i + 1]; + } + return hash1 + hash2 * 1566083941; + } + } } } diff --git a/Packages/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/ScreenPositionNode.cs b/Packages/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/ScreenPositionNode.cs index a4d1ef98ac1..f3274d0dca5 100644 --- a/Packages/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/ScreenPositionNode.cs +++ b/Packages/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/ScreenPositionNode.cs @@ -44,6 +44,20 @@ public Mode mode public ScreenSpaceType screenSpaceType => m_ScreenSpaceType; + internal const string k_ClipNotSupportedWarning = "Screen Position node: Clip mode is not supported, using Default instead."; + + public override void OnAfterDeserialize(string json) + { + base.OnAfterDeserialize(json); + + // Clip is no longer a Mode, and the dropdown already shows it as Default. + if (m_ScreenSpaceType == ScreenSpaceType.Clip) + { + Debug.LogWarning(k_ClipNotSupportedWarning); + m_ScreenSpaceType = ScreenSpaceType.Default; + } + } + private const int kOutputSlotId = 0; private const string kOutputSlotName = "Out"; diff --git a/Packages/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/CubemapAssetNode.cs b/Packages/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/CubemapAssetNode.cs index e60dae3c32a..3d93e46b52c 100644 --- a/Packages/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/CubemapAssetNode.cs +++ b/Packages/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/CubemapAssetNode.cs @@ -93,7 +93,10 @@ public void GetSourceAssetDependencies(AssetCollection assetCollection) var guidString = m_Cubemap.guid; if (!string.IsNullOrEmpty(guidString) && GUID.TryParse(guidString, out var guid)) { - assetCollection.AddAssetDependency(guid, AssetCollection.Flags.IncludeInExportPackage); + assetCollection.AddAssetDependency( + guid, + AssetCollection.Flags.ArtifactDependency | + AssetCollection.Flags.IncludeInExportPackage); } } } diff --git a/Packages/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/Texture2DArrayAssetNode.cs b/Packages/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/Texture2DArrayAssetNode.cs index 993efbd4177..d3e91906b3e 100644 --- a/Packages/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/Texture2DArrayAssetNode.cs +++ b/Packages/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/Texture2DArrayAssetNode.cs @@ -94,7 +94,10 @@ public void GetSourceAssetDependencies(AssetCollection assetCollection) var guidString = m_Texture.guid; if (!string.IsNullOrEmpty(guidString) && GUID.TryParse(guidString, out var guid)) { - assetCollection.AddAssetDependency(guid, AssetCollection.Flags.IncludeInExportPackage); + assetCollection.AddAssetDependency( + guid, + AssetCollection.Flags.ArtifactDependency | + AssetCollection.Flags.IncludeInExportPackage); } } } diff --git a/Packages/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/Texture2DAssetNode.cs b/Packages/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/Texture2DAssetNode.cs index 87cbce6cf7c..3cba18a171e 100644 --- a/Packages/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/Texture2DAssetNode.cs +++ b/Packages/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/Texture2DAssetNode.cs @@ -95,7 +95,10 @@ public void GetSourceAssetDependencies(AssetCollection assetCollection) var guidString = m_Texture.guid; if (!string.IsNullOrEmpty(guidString) && GUID.TryParse(guidString, out var guid)) { - assetCollection.AddAssetDependency(guid, AssetCollection.Flags.IncludeInExportPackage); + assetCollection.AddAssetDependency( + guid, + AssetCollection.Flags.ArtifactDependency | + AssetCollection.Flags.IncludeInExportPackage); } } } diff --git a/Packages/com.unity.shadergraph/Editor/Data/Nodes/Input/UI/SDFTextParametersNode.cs b/Packages/com.unity.shadergraph/Editor/Data/Nodes/Input/UI/SDFTextParametersNode.cs index 9abeacdc756..9314c961b9a 100644 --- a/Packages/com.unity.shadergraph/Editor/Data/Nodes/Input/UI/SDFTextParametersNode.cs +++ b/Packages/com.unity.shadergraph/Editor/Data/Nodes/Input/UI/SDFTextParametersNode.cs @@ -1,4 +1,4 @@ -using System.Linq; +using System.Collections.Generic; using UnityEditor.Graphing; using UnityEditor.Rendering.UITK.ShaderGraph; using UnityEngine; @@ -50,7 +50,7 @@ public override void UpdateNodeAfterDeserialization() AddSlot(new Vector2MaterialSlot(ShadowOffsetSlotId, k_ShadowOffsetSlotName, k_ShadowOffsetSlotName, SlotType.Output, Vector2.zero)); AddSlot(new Vector1MaterialSlot(ShadowSoftnessSlotId, k_ShadowSoftnessSlotName, k_ShadowSoftnessSlotName, SlotType.Output, 0.0f)); RemoveSlotsNameNotMatching(k_SlotOrder); - SetSlotOrder(k_SlotOrder.ToList()); + SetSlotOrder(new List(k_SlotOrder)); } static readonly (int slotId, string dimension, string field)[] k_Outputs = diff --git a/Packages/com.unity.shadergraph/Editor/Data/Nodes/UI/DefaultSDFTextNode.cs b/Packages/com.unity.shadergraph/Editor/Data/Nodes/UI/DefaultSDFTextNode.cs index 3f8baa7ee55..9b0c3f636ae 100644 --- a/Packages/com.unity.shadergraph/Editor/Data/Nodes/UI/DefaultSDFTextNode.cs +++ b/Packages/com.unity.shadergraph/Editor/Data/Nodes/UI/DefaultSDFTextNode.cs @@ -1,4 +1,4 @@ -using System.Linq; +using System.Collections.Generic; using UnityEditor.Rendering.UITK.ShaderGraph; using UnityEngine; @@ -44,7 +44,11 @@ public DefaultSDFTextNode() k_InputSlotIdShadowColor, k_InputSlotIdShadowOffset, k_InputSlotIdShadowSoftness }; - static readonly int[] k_SlotOrder = new[] { k_InputSlotIdTint }.Concat(k_OverrideSlotIds).Append(k_OutputSlotId).ToArray(); + static readonly int[] k_SlotOrder = + { + k_InputSlotIdTint, k_InputSlotIdDilate, k_InputSlotIdSharpness, k_InputSlotIdOutlineColor, k_InputSlotIdOutlineDilate, + k_InputSlotIdShadowColor, k_InputSlotIdShadowOffset, k_InputSlotIdShadowSoftness, k_OutputSlotId + }; public sealed override void UpdateNodeAfterDeserialization() { @@ -58,7 +62,7 @@ public sealed override void UpdateNodeAfterDeserialization() AddSlot(new Vector1MaterialSlot(k_InputSlotIdShadowSoftness, k_InputSlotNameShadowSoftness, k_InputSlotNameShadowSoftness, SlotType.Input, 0.0f) { CustomBinding = k_DefaultBinding }); AddSlot(new ColorRGBAMaterialSlot(k_OutputSlotId, k_OutputSlotName, k_OutputSlotName, SlotType.Output, Vector4.one, ShaderStageCapability.Fragment)); RemoveSlotsNameNotMatching(k_SlotOrder); - SetSlotOrder(k_SlotOrder.ToList()); + SetSlotOrder(new List(k_SlotOrder)); } public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMode) @@ -91,7 +95,7 @@ public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMo sb.AppendLine("Unity_UIE_EvaluateSdfTextNode_Input.textCoreLoc = round(IN.textCoreLoc);"); sb.AppendLine("Unity_UIE_EvaluateSdfTextNode_Input.opacity = 1.0;"); - if (!k_OverrideSlotIds.Any(id => GetInputNodeFromSlot(id) != null)) + if (!HasAnyOverride()) { sb.AppendLine("CommonFragOutput Unity_UIE_EvaluateSdfTextNode_Output = uie_std_frag_sdf_text(Unity_UIE_EvaluateSdfTextNode_Input);"); sb.AppendLine("{0} = Unity_UIE_EvaluateSdfTextNode_Output.color;", outputVarName); @@ -114,6 +118,16 @@ public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMo } } + bool HasAnyOverride() + { + foreach (int slotId in k_OverrideSlotIds) + { + if (GetInputNodeFromSlot(slotId) != null) + return true; + } + return false; + } + void AppendParamOverride(ShaderStringBuilder sb, GenerationMode generationMode, int slotId, string fieldName, string transform = null) { if (GetInputNodeFromSlot(slotId) == null) diff --git a/Packages/com.unity.shadergraph/Editor/Data/Nodes/Utility/SubGraphNode.cs b/Packages/com.unity.shadergraph/Editor/Data/Nodes/Utility/SubGraphNode.cs index 6a9bb7639e7..52dd99a1389 100644 --- a/Packages/com.unity.shadergraph/Editor/Data/Nodes/Utility/SubGraphNode.cs +++ b/Packages/com.unity.shadergraph/Editor/Data/Nodes/Utility/SubGraphNode.cs @@ -616,6 +616,10 @@ public override void ValidateNode() { owner.AddValidationError(objectId, $"Could not find Sub Graph asset with GUID {assetGuid}."); } + else if (AssetDatabase.AssetPathExists(assetPath) && AssetDatabase.GetMainAssetEntityId(assetPath) == EntityId.None) + { + // Sub Graph is not imported yet; its artifact dependency reimports this graph once it is + } else { owner.AddValidationError(objectId, $"Could not load Sub Graph asset at \"{assetPath}\" with GUID {assetGuid}."); diff --git a/Packages/com.unity.shadergraph/Editor/Drawing/Inspector/InspectorView.cs b/Packages/com.unity.shadergraph/Editor/Drawing/Inspector/InspectorView.cs index 2ee411fe809..476ffab0bb1 100644 --- a/Packages/com.unity.shadergraph/Editor/Drawing/Inspector/InspectorView.cs +++ b/Packages/com.unity.shadergraph/Editor/Drawing/Inspector/InspectorView.cs @@ -50,6 +50,9 @@ void RegisterPropertyDrawer(Type newPropertyDrawerType) return; } + if (newPropertyDrawerType.IsAbstract) + return; + var newPropertyDrawerAttribute = newPropertyDrawerType.GetCustomAttribute(); if (newPropertyDrawerAttribute != null) diff --git a/Packages/com.unity.shadergraph/Editor/Drawing/MaterialGraphEditWindow.cs b/Packages/com.unity.shadergraph/Editor/Drawing/MaterialGraphEditWindow.cs index a56d0c582f5..a0c70272001 100644 --- a/Packages/com.unity.shadergraph/Editor/Drawing/MaterialGraphEditWindow.cs +++ b/Packages/com.unity.shadergraph/Editor/Drawing/MaterialGraphEditWindow.cs @@ -328,14 +328,7 @@ void Update() } } - var nodesWithDependencies = graphObject.graph.GetNodes(); - foreach (var node in nodesWithDependencies) - { - var reloaded = node.Reload(m_ChangedFileDependencyGUIDs); - reloadedSomething |= reloaded; - } - - reloadedSomething |= materialGraph.ReloadDataExtensions(m_ChangedFileDependencyGUIDs); + reloadedSomething |= materialGraph.ReloadAssetDependencies(m_ChangedFileDependencyGUIDs); var subGraphNodes = graphObject.graph.GetNodes(); if (subGraphNodes.Count() > 0) @@ -453,6 +446,8 @@ void OnEnable() void OnDisable() { + graphEditorView = null; + messageManager.ClearAll(); m_MessageManager = null; diff --git a/Packages/com.unity.shadergraph/Editor/Drawing/MaterialGraphPreviewGenerator.cs b/Packages/com.unity.shadergraph/Editor/Drawing/MaterialGraphPreviewGenerator.cs index 5f572be02a1..9ee5dd1654c 100644 --- a/Packages/com.unity.shadergraph/Editor/Drawing/MaterialGraphPreviewGenerator.cs +++ b/Packages/com.unity.shadergraph/Editor/Drawing/MaterialGraphPreviewGenerator.cs @@ -51,8 +51,8 @@ public MaterialGraphPreviewGenerator() // Explicitly use forward rendering for all previews // (deferred fails when generating some static previews at editor launch; and we never want // vertex lit previews if that is chosen in the player settings) - m_Camera.renderingPath = RenderingPath.Forward; #pragma warning disable CS0618 + m_Camera.renderingPath = RenderingPath.Forward; m_Camera.useOcclusionCulling = false; #pragma warning restore CS0618 m_Camera.scene = m_Scene; @@ -210,10 +210,12 @@ public void DoRenderPreview(RenderTexture renderTexture, Material mat, Mesh mesh null, false); +#pragma warning disable CS0618 // Type or member is obsolete var oldAllowPipes = Unsupported.useScriptableRenderPipeline; Unsupported.useScriptableRenderPipeline = allowSRP; m_Camera.Render(); Unsupported.useScriptableRenderPipeline = oldAllowPipes; +#pragma warning restore CS0618 RenderTexture.active = previousRenderTexure; diff --git a/Packages/com.unity.shadergraph/Editor/Drawing/PreviewManager.cs b/Packages/com.unity.shadergraph/Editor/Drawing/PreviewManager.cs index 023aec20d8a..2952b52d982 100644 --- a/Packages/com.unity.shadergraph/Editor/Drawing/PreviewManager.cs +++ b/Packages/com.unity.shadergraph/Editor/Drawing/PreviewManager.cs @@ -96,6 +96,10 @@ void SetupUITKPanelSettings() m_PreviewPanelSettings.clearDepthStencil = true; m_PreviewPanelSettings.isTransient = true; m_PreviewPanelSettings.disableNoThemeWarning = true; + // The graph may read any optional channel (UV1-3, Normal, Tangent). Enable them all so the panel's + // vertex layout always provides them (zero-filled), otherwise Metal logs "Missing vertex input". + m_PreviewPanelSettings.extraVertexChannels = ExtraVertexChannels.TexCoord1 | ExtraVertexChannels.TexCoord2 | + ExtraVertexChannels.TexCoord3 | ExtraVertexChannels.Normal | ExtraVertexChannels.Tangent; var root = m_PreviewPanelSettings.panel.visualTree; root.StretchToParentSize(); var previewElementUxml = Resources.Load("UXML/UITKMasterNodePreview"); @@ -644,7 +648,6 @@ bool TimedNodesShouldUpdate(EditorWindow editorWindow) private static readonly ProfilerMarker RenderPreviewsMarker = new ProfilerMarker("RenderPreviews"); private static int k_spriteProps = Shader.PropertyToID("unity_SpriteProps"); private static int k_spriteColor = Shader.PropertyToID("unity_SpriteColor"); - private static int k_rendererColor = Shader.PropertyToID("_RendererColor"); private float previewTime = 0; public void RenderPreviews(EditorWindow editorWindow, bool requestShaders = true) @@ -822,7 +825,6 @@ public void RenderPreviews(EditorWindow editorWindow, bool requestShaders = true //but I dont believe such a place exists and would be too costly to add. masterRenderData.shaderData.mat.SetVector(k_spriteProps, new Vector4(1, 1, -1, 0)); masterRenderData.shaderData.mat.SetVector(k_spriteColor, new Vector4(1, 1, 1, 1)); - masterRenderData.shaderData.mat.SetVector(k_rendererColor, new Vector4(1, 1, 1, 1)); RenderPreview(masterRenderData, mesh, previewTransform, perMaterialPreviewProperties); } @@ -1346,10 +1348,12 @@ void RenderPreview(PreviewRenderData renderData, Mesh mesh, Matrix4x4 transform, Graphics.DrawMesh(mesh, transform, renderData.shaderData.mat, 1, m_SceneResources.camera, 0, m_SharedPreviewPropertyBlock, ShadowCastingMode.Off, false, null, false); } +#pragma warning disable CS0618 // Type or member is obsolete var previousUseSRP = Unsupported.useScriptableRenderPipeline; Unsupported.useScriptableRenderPipeline = (renderData == m_MasterRenderData); m_SceneResources.camera.Render(); Unsupported.useScriptableRenderPipeline = previousUseSRP; +#pragma warning restore CS0618 } Graphics.Blit(temp, renderData.renderTexture, m_SceneResources.blitNoAlphaMaterial); @@ -1382,10 +1386,12 @@ void InitializeSRPIfNeeded() m_SceneResources.camera.targetTexture = temp; +#pragma warning disable CS0618 // Type or member is obsolete var previousUseSRP = Unsupported.useScriptableRenderPipeline; Unsupported.useScriptableRenderPipeline = true; m_SceneResources.camera.Render(); Unsupported.useScriptableRenderPipeline = previousUseSRP; +#pragma warning restore CS0618 RenderTexture.ReleaseTemporary(temp); diff --git a/Packages/com.unity.shadergraph/Editor/Drawing/SearchWindowProvider.cs b/Packages/com.unity.shadergraph/Editor/Drawing/SearchWindowProvider.cs index 72c8a1e7b9d..cd3aad2b787 100644 --- a/Packages/com.unity.shadergraph/Editor/Drawing/SearchWindowProvider.cs +++ b/Packages/com.unity.shadergraph/Editor/Drawing/SearchWindowProvider.cs @@ -214,7 +214,7 @@ public void GenerateNodeEntries() if (!provider.IsValid) continue; - if (!ProviderTypeCache.TryCreateModel(provider.ProviderKey, out var model) || model is not ProviderNode node) + if (!ProviderModels.TryCreate(provider.Info, out var model) || model is not ProviderNode node) node = new ProviderNode(); node.InitializeFromProvider(provider); @@ -232,6 +232,11 @@ public void GenerateNodeEntries() AddEntries(node, title.ToArray(), nodeEntries); } } + if (m_Graph.isShaderInterfaceMode) + { + foreach (var (path, node) in LocalProviderSearchEntries.For(m_Graph)) + AddEntries(node, path, nodeEntries); + } Profiler.EndSample(); Profiler.BeginSample("SearchWindowProvider.GenerateNodeEntries.IterateGraphInputs"); @@ -281,6 +286,11 @@ void SortEntries(List nodeEntries) // - Art/Adjustments/Contrast nodeEntries.Sort((entry1, entry2) => { + bool isLocal1 = entry1.node is IProviderNode { isLocal: true }; + bool isLocal2 = entry2.node is IProviderNode { isLocal: true }; + if (isLocal1 != isLocal2) + return isLocal1 ? -1 : 1; + for (var i = 0; i < entry1.title.Length; i++) { if (i >= entry2.title.Length) @@ -405,7 +415,7 @@ public Searcher.Searcher LoadSearchWindow() var nodeDatabase = SearcherDatabase.Create(root, string.Empty, false); - return new Searcher.Searcher(nodeDatabase, new SearchWindowAdapter("Create Node")); + return new Searcher.Searcher(nodeDatabase, new LocalsSearchWindowAdapter("Create Node")); } public bool OnSearcherSelectEntry(SearcherItem entry, Vector2 screenMousePosition) @@ -483,7 +493,14 @@ public AbstractMaterialNode CopyNodeForGraph(AbstractMaterialNode oldNode) { newNode.ChangeVersion(oldNode.sgVersion); } - if (newNode is ProviderNode providerNode) + if (oldNode is IProviderNode { isLocal: true } localNode) + { + // Like property nodes below, it resolves through the graph so its title is known before it's added. + newNode.owner = m_Graph; + ((IProviderNode)newNode).InitializeFromNode(localNode); + newNode.owner = null; + } + else if (newNode is ProviderNode providerNode) { providerNode.InitializeFromProvider(((ProviderNode)oldNode).Provider); } diff --git a/Packages/com.unity.shadergraph/Editor/Drawing/Views/GraphEditorView.cs b/Packages/com.unity.shadergraph/Editor/Drawing/Views/GraphEditorView.cs index 3dee4d930c7..b148bae1072 100644 --- a/Packages/com.unity.shadergraph/Editor/Drawing/Views/GraphEditorView.cs +++ b/Packages/com.unity.shadergraph/Editor/Drawing/Views/GraphEditorView.cs @@ -17,6 +17,7 @@ using Unity.Profiling; using UnityEditor.ShaderGraph.Internal; +using UnityEditor.ShaderGraph.ProviderSystem; using UnityEditor.Experimental; using UnityEditor.PackageManager.UI; using UnityEngine.Pool; @@ -232,8 +233,7 @@ public GraphEditorView(EditorWindow editorWindow, GraphData graph, MessageManage if ((ShaderGraphPreferences.allowShaderInterfaceMode || m_Graph.isShaderInterfaceMode) && !m_Graph.isSubGraph) { menu.AddSeparator(""); - menu.AddItem(new GUIContent("Shader Interface Mode (Experimental)"), m_Graph.isShaderInterfaceMode, - () => m_Graph.SwitchShaderInterfaceMode(!m_Graph.isShaderInterfaceMode)); + menu.AddItem(new GUIContent("Shader Interface Mode (Experimental)"), m_Graph.isShaderInterfaceMode, ToggleShaderInterfaceMode); } if (!isCheckedOut() && Provider.enabled && Provider.isActive) { @@ -366,8 +366,7 @@ public GraphEditorView(EditorWindow editorWindow, GraphData graph, MessageManage m_BuiltForShaderInterfaceMode = m_Graph.isShaderInterfaceMode; // Shader interface mode keeps the target contexts and blocks in the data, but doesn't show or update them. - m_HideBlocks = m_Graph.isShaderInterfaceMode; - if (!m_Graph.isSubGraph && !m_HideBlocks) + if (!m_Graph.isSubGraph && !m_BuiltForShaderInterfaceMode) { AddContexts(); } @@ -384,9 +383,16 @@ public GraphEditorView(EditorWindow editorWindow, GraphData graph, MessageManage AddStickyNote(stickyNote); } + if (m_BuiltForShaderInterfaceMode) + { + m_VirtualFunctionStackLayout = new VirtualFunctionStackLayout(m_GraphView, m_Graph); + m_LocalProviderHighlight = new LocalProviderHighlight(m_GraphView); + } + AddNodes(graph.GetNodes()); - if (!m_HideBlocks) + if (!m_BuiltForShaderInterfaceMode) AddBlocks(graph.GetNodes()); + m_VirtualFunctionStackLayout?.Refresh(); AddEdges(graph.edges); Add(content); @@ -409,10 +415,28 @@ public GraphEditorView(EditorWindow editorWindow, GraphData graph, MessageManage } bool m_BuiltForShaderInterfaceMode; - bool m_HideBlocks; + VirtualFunctionStackLayout m_VirtualFunctionStackLayout; + LocalProviderHighlight m_LocalProviderHighlight; internal bool isOutOfDateForMode => m_BuiltForShaderInterfaceMode != m_Graph.isShaderInterfaceMode; + bool ShowsNode(AbstractMaterialNode node) => node switch + { + BlockNode => !m_BuiltForShaderInterfaceMode, + VirtualFunctionOutputNode => m_BuiltForShaderInterfaceMode, + _ => true, + }; + + void ToggleShaderInterfaceMode() + { + bool leaving = m_Graph.isShaderInterfaceMode; + if (leaving + && m_Graph.GetNodes().Any(output => m_Graph.GetEdges(output).Any()) + && !EditorUtility.DisplayDialog("Exit Shader Interface Mode", "Leaving Shader Interface mode removes the virtual function output nodes and their connections.", "Exit", "Cancel")) + return; + m_Graph.SwitchShaderInterfaceMode(!leaving); + } + private void CreateBlackboard() { var blackboardViewModel = new BlackboardViewModel() { parentView = graphView, model = m_Graph, title = assetName }; @@ -747,6 +771,12 @@ GraphViewChange GraphViewChanged(GraphViewChange graphViewChange) var rect = element.parent.ChangeCoordinatesTo(m_GraphView.contentViewContainer, element.GetPosition()); contextView.contextData.position = rect.position; } + + if (element is VirtualFunctionStackView stackView) + { + var rect = element.parent.ChangeCoordinatesTo(m_GraphView.contentViewContainer, element.GetPosition()); + stackView.stackData.position = rect.position; + } } } @@ -965,6 +995,15 @@ public void HandleGraphChanges(bool wasUndoRedoPerformed) AddNode(node, lookupTable: lookupTable); } + // Undo and redo replace every node and stack, and update the inspector themselves. + if (m_VirtualFunctionStackLayout != null && (m_Graph.shaderInterfaceChanged || wasUndoRedoPerformed)) + { + m_VirtualFunctionStackLayout.Refresh(); + m_SearchWindowProvider.regenerateEntries = true; + if (!wasUndoRedoPerformed) + m_InspectorView.TriggerInspectorUpdate(m_GraphView.selection); + } + foreach (var groupChange in m_Graph.parentGroupChanges) { GraphElement graphElement = null; @@ -1134,7 +1173,11 @@ void HandleRemovedNodes(Dictionary lookupTable = null) { nodeView.Dispose(); - if (node is BlockNode blockNode) + if (node is VirtualFunctionOutputNode && (nodeView as Node)?.GetFirstAncestorOfType() is { } stack) + { + stack.RemoveElement((Node)nodeView); + } + else if (node is BlockNode blockNode) { var context = m_GraphView.GetContext(blockNode.contextData); // blocknode may be floating and not actually in the stacknode's visual hierarchy. @@ -1194,8 +1237,7 @@ void UpdateBadges() void AddNode(AbstractMaterialNode node, bool usePrebuiltVisualGroupMap = false, Dictionary lookupTable = null) { - // Blocks live in the target contexts, which aren't shown in Shader Interface mode. - if (node is BlockNode && m_HideBlocks) + if (!ShowsNode(node)) return; var materialNode = node; @@ -1245,6 +1287,10 @@ void AddNode(AbstractMaterialNode node, bool usePrebuiltVisualGroupMap = false, m_GraphView.AddElement(materialNodeView); materialNodeView.Initialize(materialNode, m_PreviewManager, m_EdgeConnectorListener, graphView); + if (node is VirtualFunctionOutputNode output) + m_VirtualFunctionStackLayout?.AdoptOutputView(materialNodeView, output); + if (node is IProviderNode { isLocal: true }) + m_LocalProviderHighlight?.Attach(materialNodeView); m_ColorManager.UpdateNodeView(materialNodeView); nodeView = materialNodeView; } @@ -1461,7 +1507,7 @@ Edge AddEdge(IEdge edge, bool useVisualNodeMap = false, bool updateNodePorts = t return null; } - if (targetNode is BlockNode && m_HideBlocks) + if (!ShowsNode(targetNode)) return null; var targetSlot = targetNode.FindInputSlot(edge.inputSlot.slotId); @@ -1695,6 +1741,9 @@ public void Dispose() m_GraphView = null; } + m_LocalProviderHighlight = null; + m_VirtualFunctionStackLayout = null; + m_BlackboardController?.Dispose(); m_BlackboardController = null; diff --git a/Packages/com.unity.shadergraph/Editor/Drawing/Views/MaterialGraphView.cs b/Packages/com.unity.shadergraph/Editor/Drawing/Views/MaterialGraphView.cs index 1f1d7dc0869..c4e1a2fb680 100644 --- a/Packages/com.unity.shadergraph/Editor/Drawing/Views/MaterialGraphView.cs +++ b/Packages/com.unity.shadergraph/Editor/Drawing/Views/MaterialGraphView.cs @@ -11,6 +11,7 @@ using UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers; using UnityEditor.ShaderGraph.Drawing.Views; using UnityEditor.ShaderGraph.Internal; +using UnityEditor.ShaderGraph.ProviderSystem; using UnityEditor.ShaderGraph.Serialization; using UnityEngine.UIElements; using Edge = UnityEditor.Experimental.GraphView.Edge; @@ -347,21 +348,8 @@ public override void BuildContextualMenu(ContextualMenuPopulateEvent evt) evt.menu.AppendSeparator(); evt.menu.AppendAction("Open Sub Graph", OpenSubGraph, (a) => DropdownMenuAction.Status.Normal); } - if (selection.OfType().Count() == 1 - && selection.OfType().First().node is ProviderSystem.ProviderNode providerNode - && providerNode.isValid - && (providerNode.Provider?.IsValid ?? false) - && providerNode.Provider.AssetID != default) - { - evt.menu.AppendSeparator(); - - void PingSource(DropdownMenuAction action) - { - var asset = AssetDatabase.LoadAssetByGUID(providerNode.Provider.AssetID); - EditorGUIUtility.PingObject(asset); - } - evt.menu.AppendAction("Show Source in Project", PingSource, (a) => DropdownMenuAction.Status.Normal); - } + if (selection.OfType().Count() == 1) + AddProviderNodeActions(evt, selection.OfType().First()); } evt.menu.AppendSeparator(); if (evt.target is StickyNote) @@ -383,7 +371,7 @@ void PingSource(DropdownMenuAction action) if (selectedObject is Group) return DropdownMenuAction.Status.Disabled; GraphElement ge = selectedObject as GraphElement; - if (ge.userData is BlockNode) + if (ge.userData is BlockNode or VirtualFunctionOutputNode) { return DropdownMenuAction.Status.Disabled; } @@ -712,31 +700,43 @@ void ApplyColor(Color pickedColor) ColorPicker.Show(ApplyColor, defaultColor, true, false); } + void AddProviderNodeActions(ContextualMenuPopulateEvent evt, IShaderNodeView nodeView) + { + if (nodeView.node is IProviderNode { Provider: { } provider } && provider.AssetID != default && !string.IsNullOrEmpty(AssetDatabase.GUIDToAssetPath(provider.AssetID))) + { + evt.menu.AppendSeparator(); + evt.menu.AppendAction("Show Source in Project", _ => EditorGUIUtility.PingObject(AssetDatabase.LoadAssetByGUID(provider.AssetID)), _ => DropdownMenuAction.Status.Normal); + } + + VirtualFunctionNodeMenu.AddActions(this, evt, nodeView); + } + protected internal override bool canDeleteSelection { get { return selection.Any(x => { - if (x is ContextView) return false; //< context view must not be deleted. ( eg, Vertex, Fragment ) + if (x is ContextView or VirtualFunctionStackView) return false; //< contexts (Vertex, Fragment) and virtual function stacks must not be deleted. return !(x is IShaderNodeView nodeView) || nodeView.node.canDeleteNode; }); } } public void GroupSelection() { + var groupItems = selection.OfType().Select(e => e.userData).OfType().Where(item => item is not VirtualFunctionOutputNode).ToList(); + if (groupItems.Count == 0) + return; + var title = "New Group"; var groupData = new GroupData(title, new Vector2(10f, 10f)); graph.owner.RegisterCompleteObjectUndo("Create Group Node"); graph.CreateGroup(groupData); - foreach (var element in selection.OfType()) + foreach (var groupItem in groupItems) { - if (element.userData is IGroupItem groupItem) - { - graph.SetGroup(groupItem, groupData); - } + graph.SetGroup(groupItem, groupData); } } @@ -840,7 +840,7 @@ void SeeDocumentation(DropdownMenuAction action) { var node = selection.OfType().First().node; if (node.documentationURL != null) - System.Diagnostics.Process.Start(node.documentationURL); + Application.OpenURL(node.documentationURL); } void OpenSubGraph(DropdownMenuAction action) diff --git a/Packages/com.unity.shadergraph/Editor/Drawing/Views/MaterialNodeView.cs b/Packages/com.unity.shadergraph/Editor/Drawing/Views/MaterialNodeView.cs index 7bce344d5d2..2d2614d6de7 100644 --- a/Packages/com.unity.shadergraph/Editor/Drawing/Views/MaterialNodeView.cs +++ b/Packages/com.unity.shadergraph/Editor/Drawing/Views/MaterialNodeView.cs @@ -239,6 +239,10 @@ public void SetActive(bool state) { port.AddToClassList(portDisabledString); } + foreach (var portInputView in inputContainer.Query().ToList()) + { + portInputView.AddToClassList(disabledString); + } } else { @@ -255,6 +259,10 @@ public void SetActive(bool state) { port.RemoveFromClassList(portDisabledString); } + foreach (var portInputView in inputContainer.Query().ToList()) + { + portInputView.RemoveFromClassList(disabledString); + } } } @@ -346,10 +354,9 @@ void OnProviderDoubleClick(MouseDownEvent evt) { if (evt.clickCount == 2 && evt.button == 0) { - var providerNode = node as ProviderSystem.ProviderNode; - if (providerNode.Provider.IsValid && providerNode.Provider.AssetID != default) + if (node is ProviderSystem.ProviderNode { Provider: { } provider } && provider.AssetID != default + && AssetDatabase.GUIDToAssetPath(provider.AssetID) is { Length: > 0 } path) { - var path = AssetDatabase.GUIDToAssetPath(providerNode.Provider.AssetID); GraphUtil.OpenFile(path); } // Stop the double click event from starting a drag action on the node diff --git a/Packages/com.unity.shadergraph/Editor/Drawing/Views/PreviewSceneResources.cs b/Packages/com.unity.shadergraph/Editor/Drawing/Views/PreviewSceneResources.cs index 83dc216d6b5..01afd7db1c1 100644 --- a/Packages/com.unity.shadergraph/Editor/Drawing/Views/PreviewSceneResources.cs +++ b/Packages/com.unity.shadergraph/Editor/Drawing/Views/PreviewSceneResources.cs @@ -51,8 +51,8 @@ public PreviewSceneResources() // Explicitly use forward rendering for all previews // (deferred fails when generating some static previews at editor launch; and we never want // vertex lit previews if that is chosen in the player settings) - camera.renderingPath = RenderingPath.Forward; #pragma warning disable CS0618 + camera.renderingPath = RenderingPath.Forward; camera.useOcclusionCulling = false; #pragma warning restore CS0618 camera.scene = m_Scene; diff --git a/Packages/com.unity.shadergraph/Editor/Generation/Processors/GenerationUtils.cs b/Packages/com.unity.shadergraph/Editor/Generation/Processors/GenerationUtils.cs index 12d20008818..7622b487fa8 100644 --- a/Packages/com.unity.shadergraph/Editor/Generation/Processors/GenerationUtils.cs +++ b/Packages/com.unity.shadergraph/Editor/Generation/Processors/GenerationUtils.cs @@ -703,6 +703,7 @@ static ConditionalField[] GetConditionalFieldsFromPixelRequirements(ShaderGraphR new ConditionalField(StructFields.SurfaceDescriptionInputs.textCoreLoc, requirements.requiresUITK), new ConditionalField(StructFields.SurfaceDescriptionInputs.layoutUV, requirements.requiresUITK), new ConditionalField(StructFields.SurfaceDescriptionInputs.circle, requirements.requiresUITK), + new ConditionalField(StructFields.SurfaceDescriptionInputs.opacity, requirements.requiresUITK), new ConditionalField(Fields.ObjectToWorld, requirements.requiresTransforms.Contains(NeededTransform.ObjectToWorld)), new ConditionalField(Fields.WorldToObject, requirements.requiresTransforms.Contains(NeededTransform.WorldToObject)), @@ -1021,6 +1022,14 @@ internal static void GenerateSurfaceInputStruct(ShaderStringBuilder sb, ShaderGr { sb.AppendLine("uint {0};", ShaderGeneratorNames.InstanceID); } + + if (requirements.requiresUITK) + { + foreach (var field in StructFields.SurfaceDescriptionInputs.uitkFields) + { + sb.AppendLine($"{field.type} {field.name};"); + } + } } } @@ -1076,6 +1085,14 @@ internal static void GenerateSurfaceInputTransferCode(ShaderStringBuilder sb, Sh { sb.AppendLine($"{variableName}.{ShaderGeneratorNames.InstanceID} = IN.{ShaderGeneratorNames.InstanceID};"); } + + if (requirements.requiresUITK) + { + foreach (var field in StructFields.SurfaceDescriptionInputs.uitkFields) + { + sb.AppendLine($"{variableName}.{field.name} = IN.{field.name};"); + } + } } internal static void GenerateSurfaceDescriptionStruct(ShaderStringBuilder surfaceDescriptionStruct, List slots, string structName = "SurfaceDescription", IActiveFieldsSet activeFields = null, bool isSubgraphOutput = false, bool virtualTextureFeedback = false) diff --git a/Packages/com.unity.shadergraph/Editor/Generation/TargetResources/StructFields.cs b/Packages/com.unity.shadergraph/Editor/Generation/TargetResources/StructFields.cs index c12f4cddfc6..35de61d33ec 100644 --- a/Packages/com.unity.shadergraph/Editor/Generation/TargetResources/StructFields.cs +++ b/Packages/com.unity.shadergraph/Editor/Generation/TargetResources/StructFields.cs @@ -309,6 +309,10 @@ public struct SurfaceDescriptionInputs public static FieldDescriptor textCoreLoc = new FieldDescriptor(SurfaceDescriptionInputs.name, "textCoreLoc", "", ShaderValueType.Float2, subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor layoutUV = new FieldDescriptor(SurfaceDescriptionInputs.name, "layoutUV", "", ShaderValueType.Float2, subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor circle = new FieldDescriptor(SurfaceDescriptionInputs.name, "circle", "", ShaderValueType.Float4, subscriptOptions: StructFieldOptions.Optional); + public static FieldDescriptor opacity = new FieldDescriptor(SurfaceDescriptionInputs.name, "opacity", "", ShaderValueType.Float, subscriptOptions: StructFieldOptions.Optional); + + // Must stay below the UITK fields it references + public static readonly FieldDescriptor[] uitkFields = { color, uvClip, typeTexSettings, textCoreLoc, layoutUV, circle, opacity }; // VFX public static FieldDescriptor worldToElement = new FieldDescriptor(SurfaceDescriptionInputs.name, "worldToElement", "", ShaderValueType.Matrix4, subscriptOptions: StructFieldOptions.Optional); diff --git a/Packages/com.unity.shadergraph/Editor/Generation/TargetResources/Structs.cs b/Packages/com.unity.shadergraph/Editor/Generation/TargetResources/Structs.cs index 68012b3ef4e..b37e8173e00 100644 --- a/Packages/com.unity.shadergraph/Editor/Generation/TargetResources/Structs.cs +++ b/Packages/com.unity.shadergraph/Editor/Generation/TargetResources/Structs.cs @@ -170,6 +170,7 @@ internal static class Structs StructFields.SurfaceDescriptionInputs.textCoreLoc, StructFields.SurfaceDescriptionInputs.layoutUV, StructFields.SurfaceDescriptionInputs.circle, + StructFields.SurfaceDescriptionInputs.opacity, } }; } diff --git a/Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/Editor/ShaderGraph/Includes/BuiltInCanvasPass.hlsl b/Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/Editor/ShaderGraph/Includes/BuiltInCanvasPass.hlsl index b5a4db21b83..bbb7756ff32 100644 --- a/Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/Editor/ShaderGraph/Includes/BuiltInCanvasPass.hlsl +++ b/Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/Editor/ShaderGraph/Includes/BuiltInCanvasPass.hlsl @@ -74,9 +74,9 @@ Varyings BuildVaryings(Attributes input) float2 pixelSize = output.positionCS.w; pixelSize /= float2(1, 1) * abs(mul((float2x2)UNITY_MATRIX_P, _ScreenParams.xy)); - float4 clampedRect = clamp(_ClipRect, -2e10, 2e10); - float2 maskUV = (input.positionOS.xy - clampedRect.xy) / (clampedRect.zw - clampedRect.xy); - output.texCoord1 = float4(input.positionOS.xy * 2 - clampedRect.xy - clampedRect.zw, 0.25 / (0.25 * float2(_UIMaskSoftnessX, _UIMaskSoftnessY) + abs(pixelSize.xy))); + // Canvas position and pixel size, both linear in the vertex so they interpolate exactly under perspective. + // The fragment turns them into each edge's fade, so tilted masks keep their edges. + output.texCoord1 = float4(input.positionOS.xy, abs(pixelSize.xy)); #else output.texCoord1 = input.uv1; #endif @@ -152,12 +152,13 @@ half4 frag(PackedVaryings packedInput) : SV_TARGET #ifdef UNITY_UI_CLIP_RECT //mask = Uv2 - float2 softness = float2(_UIMaskSoftnessX, _UIMaskSoftnessY); - float2 halfPixelBias = 0.5 - 0.5 * softness * unpacked.texCoord1.zw; - half2 m = saturate((_ClipRect.zw - _ClipRect.xy - abs(unpacked.texCoord1.xy)) * unpacked.texCoord1.zw + halfPixelBias); - half2 hardThreshold = 0.5 + 1e-3 * step(0, unpacked.texCoord1.xy); - m = lerp(m, step(hardThreshold, m), step(softness, 0)); - color.a *= m.x * m.y; + // Each edge fades over its own distance and softness: left, bottom, right, top. + float4 clampedRect = clamp(_ClipRect, -2e10, 2e10); + float4 edgeDistance = float4(unpacked.texCoord1.xy - clampedRect.xy, clampedRect.zw - unpacked.texCoord1.xy); + half4 soft = saturate((edgeDistance + unpacked.texCoord1.zwzw) / (0.5 * _UIMaskSoftness + 2 * unpacked.texCoord1.zwzw)); + half4 hard = half4(edgeDistance.xy >= 0, edgeDistance.zw > 0); + half4 m = _UIMaskSoftness > 0 ? soft : hard; + color.a *= min(m.x, m.z) * min(m.y, m.w); #endif #if _BUILTIN_ALPHATEST_ON diff --git a/Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/Editor/ShaderGraph/Includes/SpriteUnlitPass.hlsl b/Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/Editor/ShaderGraph/Includes/SpriteUnlitPass.hlsl index 3f5ed656f12..fd64a69b1ff 100644 --- a/Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/Editor/ShaderGraph/Includes/SpriteUnlitPass.hlsl +++ b/Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/Editor/ShaderGraph/Includes/SpriteUnlitPass.hlsl @@ -1,10 +1,35 @@ -half4 _RendererColor; + +#ifdef UNITY_INSTANCING_ENABLED + + UNITY_INSTANCING_BUFFER_START(PerDrawSprite) + UNITY_DEFINE_INSTANCED_PROP(float4, unity_SpritePropsArray) + UNITY_DEFINE_INSTANCED_PROP(float4, unity_SpriteColorArray) + UNITY_INSTANCING_BUFFER_END(PerDrawSprite) + #define unity_SpriteProps UNITY_ACCESS_INSTANCED_PROP(PerDrawSprite, unity_SpritePropsArray) + #define unity_SpriteColor UNITY_ACCESS_INSTANCED_PROP(PerDrawSprite, unity_SpriteColorArray) + +#else + + float4 unity_SpriteColor; + float4 unity_SpriteProps; + +#endif + +float3 UnityFlipSprite(float3 pos, float2 flip) +{ + uint flipBits = asuint(flip.x); + float fx = (flipBits & 1u) ? -1.0f : 1.0f; + float fy = (flipBits & 2u) ? -1.0f : 1.0f; + return float3(pos.xy * float2(fx, fy), pos.z); +} PackedVaryings vert(Attributes input) { Varyings output = (Varyings)0; + UNITY_SETUP_INSTANCE_ID(input); + input.positionOS = UnityFlipSprite(input.positionOS, unity_SpriteProps.xy); output = BuildVaryings(input); - output.color *= _RendererColor; + output.color *= unity_SpriteColor; PackedVaryings packedOutput = PackVaryings(output); return packedOutput; } diff --git a/Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/Editor/ShaderPreprocessor.cs b/Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/Editor/ShaderPreprocessor.cs index 64c5ca7610d..93091869fb5 100644 --- a/Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/Editor/ShaderPreprocessor.cs +++ b/Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/Editor/ShaderPreprocessor.cs @@ -474,6 +474,7 @@ private static ShaderFeatures GetSupportedShaderFeatures() ShaderFeatures shaderFeatures; shaderFeatures = ShaderFeatures.MainLight; +#pragma warning disable CS0618 // Type or member is obsolete ShadowQuality shadows = QualitySettings.shadows; if (shadows != ShadowQuality.Disable) { @@ -482,6 +483,7 @@ private static ShaderFeatures GetSupportedShaderFeatures() if (shadows != ShadowQuality.HardOnly) shaderFeatures |= ShaderFeatures.SoftShadows; } +#pragma warning restore CS0618 shaderFeatures |= ShaderFeatures.AdditionalLightShadows; // These are both always "on", and dictated by the number of lights diff --git a/Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/ShaderLibrary/Input.hlsl b/Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/ShaderLibrary/Input.hlsl index e14279d7768..73458fb71ed 100644 --- a/Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/ShaderLibrary/Input.hlsl +++ b/Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/ShaderLibrary/Input.hlsl @@ -45,7 +45,7 @@ half4 _SubtractiveShadowColor; float4 _ScaledScreenParams; float4 _MainLightPosition; -half4 _MainLightColor; +float4 _MainLightColor; half4 _MainLightOcclusionProbes; // xyz are currently unused @@ -63,7 +63,7 @@ StructuredBuffer _AdditionalLightsIndices; CBUFFER_START(AdditionalLights) #endif float4 _AdditionalLightsPosition[MAX_VISIBLE_LIGHTS]; -half4 _AdditionalLightsColor[MAX_VISIBLE_LIGHTS]; +float4 _AdditionalLightsColor[MAX_VISIBLE_LIGHTS]; half4 _AdditionalLightsAttenuation[MAX_VISIBLE_LIGHTS]; half4 _AdditionalLightsSpotDir[MAX_VISIBLE_LIGHTS]; half4 _AdditionalLightsOcclusionProbes[MAX_VISIBLE_LIGHTS]; diff --git a/Packages/com.unity.shadergraph/Editor/Generation/Targets/Canvas/CanvasProperties.cs b/Packages/com.unity.shadergraph/Editor/Generation/Targets/Canvas/CanvasProperties.cs index 73b8b171fc3..f8ad4fcab2c 100644 --- a/Packages/com.unity.shadergraph/Editor/Generation/Targets/Canvas/CanvasProperties.cs +++ b/Packages/com.unity.shadergraph/Editor/Generation/Targets/Canvas/CanvasProperties.cs @@ -94,6 +94,16 @@ static class CanvasProperties overrideHLSLDeclaration = false, }; + public static readonly Vector4ShaderProperty UIMaskSoftness = new Vector4ShaderProperty() + { + overrideReferenceName = "_UIMaskSoftness", + displayName = "UIMaskSoftness", + hidden = true, + value = new Vector4(1.0f, 1.0f, 1.0f, 1.0f), + generatePropertyBlock = true, + overrideHLSLDeclaration = false, + }; + public static readonly Vector4ShaderProperty ClipRect = new Vector4ShaderProperty() { overrideReferenceName = "_ClipRect", diff --git a/Packages/com.unity.shadergraph/Editor/Generation/Targets/Canvas/CanvasSubTarget.cs b/Packages/com.unity.shadergraph/Editor/Generation/Targets/Canvas/CanvasSubTarget.cs index 0e07fad576b..fec8f4ac08e 100644 --- a/Packages/com.unity.shadergraph/Editor/Generation/Targets/Canvas/CanvasSubTarget.cs +++ b/Packages/com.unity.shadergraph/Editor/Generation/Targets/Canvas/CanvasSubTarget.cs @@ -119,6 +119,7 @@ public void CollectRenderStateShaderProperties(PropertyCollector collector, Gene collector.AddShaderProperty(CanvasProperties.ClipRect); collector.AddShaderProperty(CanvasProperties.UIMaskSoftnessX); collector.AddShaderProperty(CanvasProperties.UIMaskSoftnessY); + collector.AddShaderProperty(CanvasProperties.UIMaskSoftness); } public override void GetFields(ref TargetFieldContext context) diff --git a/Packages/com.unity.shadergraph/Editor/Generation/Targets/UITK/Templates/BuildUIVertexDescriptionInputs.template.hlsl b/Packages/com.unity.shadergraph/Editor/Generation/Targets/UITK/Templates/BuildUIVertexDescriptionInputs.template.hlsl index 9580ee24200..d94b49cd563 100644 --- a/Packages/com.unity.shadergraph/Editor/Generation/Targets/UITK/Templates/BuildUIVertexDescriptionInputs.template.hlsl +++ b/Packages/com.unity.shadergraph/Editor/Generation/Targets/UITK/Templates/BuildUIVertexDescriptionInputs.template.hlsl @@ -52,8 +52,7 @@ VertexDescriptionInputs BuildVertexDescriptionInputs(Attributes input) output.typeTexSettings.x = uie_element_frag_type(input.uv4); output.typeTexSettings.y = uie_element_texture_slot(input.uv4); - // Text-settings location and extra dilate (static fields) so the SDF Text Parameters node works in - // the vertex stage; uie_std_vert resolves the same values for text vertices. + // Read by the SDF Text Parameters node in the vertex stage. output.textCoreLoc = uie_element_textcore_loc(input.uv4); output.circle = input.uv5; diff --git a/Packages/com.unity.shadergraph/Editor/Generation/Targets/UITK/UIStructs.cs b/Packages/com.unity.shadergraph/Editor/Generation/Targets/UITK/UIStructs.cs index 56c6b700a66..cd2c0357960 100644 --- a/Packages/com.unity.shadergraph/Editor/Generation/Targets/UITK/UIStructs.cs +++ b/Packages/com.unity.shadergraph/Editor/Generation/Targets/UITK/UIStructs.cs @@ -91,8 +91,7 @@ internal static class UIStructs // Type node reads IN.typeTexSettings.x (the render type) and the Element Texture Size node // reads IN.typeTexSettings.y (the texture slot) in the vertex stage. new FieldDescriptor("VertexDescriptionInputs", "typeTexSettings", "", ShaderValueType.Float4, subscriptOptions: StructFieldOptions.Static), - // Text-settings location, mirrors SurfaceDescriptionInputs.textCoreLoc so the SDF Text - // Parameters node reads IN.textCoreLoc in the vertex stage. + // Read by the SDF Text Parameters node in the vertex stage. new FieldDescriptor("VertexDescriptionInputs", "textCoreLoc", "", ShaderValueType.Float2, subscriptOptions: StructFieldOptions.Static), // optionals diff --git a/Packages/com.unity.shadergraph/Editor/Generation/Templates/BuildSurfaceDescriptionInputs.template.hlsl b/Packages/com.unity.shadergraph/Editor/Generation/Templates/BuildSurfaceDescriptionInputs.template.hlsl index fc9bf479392..766b1aa3fa0 100644 --- a/Packages/com.unity.shadergraph/Editor/Generation/Templates/BuildSurfaceDescriptionInputs.template.hlsl +++ b/Packages/com.unity.shadergraph/Editor/Generation/Templates/BuildSurfaceDescriptionInputs.template.hlsl @@ -89,7 +89,11 @@ SurfaceDescriptionInputs BuildSurfaceDescriptionInputs(Varyings input) $SurfaceDescriptionInputs.typeTexSettings: output.typeTexSettings = input.texCoord5; $SurfaceDescriptionInputs.textCoreLoc: output.textCoreLoc = input.texCoord6.xy; $SurfaceDescriptionInputs.layoutUV: output.layoutUV = input.texCoord6.zw; +#if defined(VARYINGS_NEED_OPACITY) $SurfaceDescriptionInputs.opacity: output.opacity = input.opacity; +#else + $SurfaceDescriptionInputs.opacity: output.opacity = 1.0; +#endif $SurfaceDescriptionInputs.circle: output.circle = input.texCoord7; diff --git a/Packages/com.unity.shadergraph/Editor/Importers/ShaderGraphAssetPostProcessor.cs b/Packages/com.unity.shadergraph/Editor/Importers/ShaderGraphAssetPostProcessor.cs index d1ac5be085e..9c6ff816e3d 100644 --- a/Packages/com.unity.shadergraph/Editor/Importers/ShaderGraphAssetPostProcessor.cs +++ b/Packages/com.unity.shadergraph/Editor/Importers/ShaderGraphAssetPostProcessor.cs @@ -56,30 +56,6 @@ static void DisplayDeletionDialog(string[] deletedAssets) } } - void OnPreprocessAsset() - { - ShaderGraphImporter sgImporter = assetImporter as ShaderGraphImporter; - if (sgImporter != null) - { - // Before importing, clear shader messages for any existing old shaders, if any. - // This is a terrible way to do it, but currently how the shader message system works at the moment. - - // to workaround a bug with LoadAllAssetsAtPath(), which crashes if the asset has not yet been imported - // we first call LoadAssetAtPath<>, which handles assets not yet imported by returning null - if (AssetDatabase.LoadAssetAtPath(assetPath) != null) - { - var oldArtifacts = AssetDatabase.LoadAllAssetsAtPath(assetPath); - foreach (var artifact in oldArtifacts) - { - if ((artifact != null) && (artifact is Shader oldShader)) - { - ShaderUtil.ClearShaderMessages(oldShader); - } - } - } - } - } - static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { RegisterShaders(importedAssets); diff --git a/Packages/com.unity.shadergraph/Editor/Importers/ShaderGraphImporter.cs b/Packages/com.unity.shadergraph/Editor/Importers/ShaderGraphImporter.cs index 6252c5442df..1e0eeea0e5a 100644 --- a/Packages/com.unity.shadergraph/Editor/Importers/ShaderGraphImporter.cs +++ b/Packages/com.unity.shadergraph/Editor/Importers/ShaderGraphImporter.cs @@ -17,7 +17,7 @@ namespace UnityEditor.ShaderGraph { [ExcludeFromPreset] - [ScriptedImporter(135, Extension, -902)] + [ScriptedImporter(136, Extension, -902)] [CoreRPHelpURL("Shader-Graph-Asset", "com.unity.shadergraph")] class ShaderGraphImporter : ScriptedImporter { @@ -322,21 +322,23 @@ public override void OnImportAsset(AssetImportContext ctx) var sgMetadata = ScriptableObject.CreateInstance(); sgMetadata.hideFlags = HideFlags.HideInHierarchy; - sgMetadata.assetDependencies = new List(); + sgMetadata.assetDependencies = new List>(); foreach (var asset in assetCollection.assets) { if (asset.Value.HasFlag(AssetCollection.Flags.IncludeInExportPackage)) { - // this sucks that we have to fully load these assets just to set the reference, - // which then gets serialized as the GUID that we already have here. :P - var dependencyPath = AssetDatabase.GUIDToAssetPath(asset.Key); - if (!string.IsNullOrEmpty(dependencyPath)) + if (string.IsNullOrEmpty(dependencyPath)) + continue; + + var entityId = AssetDatabase.GetMainAssetEntityId(dependencyPath); + if (entityId == EntityId.None) { - sgMetadata.assetDependencies.Add( - AssetDatabase.LoadAssetAtPath(dependencyPath, typeof(UnityEngine.Object))); + continue; } + + sgMetadata.assetDependencies.Add(new LazyLoadReference { entityId = entityId }); } } diff --git a/Packages/com.unity.shadergraph/Editor/Importers/ShaderGraphIndexerExtension.cs b/Packages/com.unity.shadergraph/Editor/Importers/ShaderGraphIndexerExtension.cs index decbebe49f7..00c1c5c71a2 100644 --- a/Packages/com.unity.shadergraph/Editor/Importers/ShaderGraphIndexerExtension.cs +++ b/Packages/com.unity.shadergraph/Editor/Importers/ShaderGraphIndexerExtension.cs @@ -15,11 +15,11 @@ static void ShaderGraphIndexer(CustomObjectIndexerTarget context, ObjectIndexer } } - [CustomObjectIndexer(typeof(ShaderGraphImporter), version = 2)] + [CustomObjectIndexer(typeof(ShaderGraphImporter), version = 3)] internal static void ShaderGraphImporterIndexer(CustomObjectIndexerTarget context, ObjectIndexer indexer) => ShaderGraphIndexer(context, indexer); - [CustomObjectIndexer(typeof(Shader), version = 2)] + [CustomObjectIndexer(typeof(Shader), version = 3)] internal static void ShaderGraphShaderIndexer(CustomObjectIndexerTarget context, ObjectIndexer indexer) => ShaderGraphIndexer(context, indexer); } diff --git a/Packages/com.unity.shadergraph/Editor/Importers/ShaderGraphMetadata.cs b/Packages/com.unity.shadergraph/Editor/Importers/ShaderGraphMetadata.cs index fa7a0bd1948..f9f9823becb 100644 --- a/Packages/com.unity.shadergraph/Editor/Importers/ShaderGraphMetadata.cs +++ b/Packages/com.unity.shadergraph/Editor/Importers/ShaderGraphMetadata.cs @@ -138,7 +138,7 @@ class ShaderGraphMetadata : ScriptableObject // these asset dependencies are stored here as a way for "Export Package..." to discover them // and automatically pull them in to the .unitypackage - public List assetDependencies; + public List> assetDependencies; public List categoryDatas; } diff --git a/Packages/com.unity.shadergraph/Editor/Importers/ShaderSubGraphImporter.cs b/Packages/com.unity.shadergraph/Editor/Importers/ShaderSubGraphImporter.cs index 0b7ce428fe3..d6ec3fc6bda 100644 --- a/Packages/com.unity.shadergraph/Editor/Importers/ShaderSubGraphImporter.cs +++ b/Packages/com.unity.shadergraph/Editor/Importers/ShaderSubGraphImporter.cs @@ -20,7 +20,7 @@ namespace UnityEditor.ShaderGraph { [ExcludeFromPreset] - [ScriptedImporter(31, Extension, -905, AllowCaching = true)] + [ScriptedImporter(32, Extension, -905, AllowCaching = true)] [CoreRPHelpURL("Sub-graph", "com.unity.shadergraph")] class ShaderSubGraphImporter : ScriptedImporter { @@ -129,7 +129,7 @@ public override void OnImportAsset(AssetImportContext ctx) var metadata = ScriptableObject.CreateInstance(); metadata.hideFlags = HideFlags.HideInHierarchy; - metadata.assetDependencies = new List(); + metadata.assetDependencies = new List>(); AssetCollection assetCollection = new AssetCollection(); MinimalGraphData.GatherMinimalDependenciesFromFile(assetPath, assetCollection); @@ -138,15 +138,17 @@ public override void OnImportAsset(AssetImportContext ctx) { if (asset.Value.HasFlag(AssetCollection.Flags.IncludeInExportPackage)) { - // this sucks that we have to fully load these assets just to set the reference, - // which then gets serialized as the GUID that we already have here. :P - var dependencyPath = AssetDatabase.GUIDToAssetPath(asset.Key); - if (!string.IsNullOrEmpty(dependencyPath)) + if (string.IsNullOrEmpty(dependencyPath)) + continue; + + var entityId = AssetDatabase.GetMainAssetEntityId(dependencyPath); + if (entityId == EntityId.None) { - metadata.assetDependencies.Add( - AssetDatabase.LoadAssetAtPath(dependencyPath, typeof(UnityEngine.Object))); + continue; } + + metadata.assetDependencies.Add(new LazyLoadReference { entityId = entityId }); } } ctx.AddObjectToAsset("Metadata", metadata); diff --git a/Packages/com.unity.shadergraph/Editor/Importers/ShaderSubGraphMetadata.cs b/Packages/com.unity.shadergraph/Editor/Importers/ShaderSubGraphMetadata.cs index ccea2bd6844..05b380db6a2 100644 --- a/Packages/com.unity.shadergraph/Editor/Importers/ShaderSubGraphMetadata.cs +++ b/Packages/com.unity.shadergraph/Editor/Importers/ShaderSubGraphMetadata.cs @@ -5,6 +5,6 @@ namespace UnityEditor.ShaderGraph { class ShaderSubGraphMetadata : ScriptableObject { - public List assetDependencies; + public List> assetDependencies; } } diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/CodeFunctionProvider.cs b/Packages/com.unity.shadergraph/Editor/ProviderSystem/CodeFunctionProvider.cs index 59952135cec..aa8dc68cf8f 100644 --- a/Packages/com.unity.shadergraph/Editor/ProviderSystem/CodeFunctionProvider.cs +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/CodeFunctionProvider.cs @@ -12,7 +12,7 @@ sealed class CodeFunctionProvider : IProvider readonly MethodInfo m_method; readonly string m_body; - public string ProviderKey => $"{m_method.DeclaringType.FullName}.{m_method.Name}"; + public ProviderInfo Info => new($"{m_method.DeclaringType.FullName}.{m_method.Name}"); public IShaderFunction Definition { get; private set; } internal CodeFunctionProvider(MethodInfo method, string body) diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector.meta new file mode 100644 index 00000000000..52f297220ef --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 494d5af705484a1397187af7c8572d8e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector/AbstractProviderNodePropertyDrawer.cs b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector/AbstractProviderNodePropertyDrawer.cs new file mode 100644 index 00000000000..0e2d944306c --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector/AbstractProviderNodePropertyDrawer.cs @@ -0,0 +1,67 @@ +using System; +using System.Reflection; +using Unity.GraphAuthoring.Editor.ProviderSystem; +using UnityEditor.ShaderGraph.ProviderSystem; +using UnityEngine; +using UnityEngine.UIElements; + +namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers +{ + abstract class AbstractProviderNodePropertyDrawer : IPropertyDrawer, IGetNodePropertyDrawerPropertyData where T : IDefinition + { + Action m_SetNodesAsDirtyCallback; + Action m_UpdateNodeViewsCallback; + + public Action inspectorUpdateDelegate { get; set; } + + void IGetNodePropertyDrawerPropertyData.GetPropertyData(Action setNodesAsDirtyCallback, Action updateNodeViewsCallback) + { + m_SetNodesAsDirtyCallback = setNodesAsDirtyCallback; + m_UpdateNodeViewsCallback = updateNodeViewsCallback; + } + + public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject, InspectableAttribute attribute) + { + var node = (AbstractProviderNode)actualObject; + var sheet = new PropertySheet(PropertyDrawerUtils.CreateLabel($"{node.name} Node", 0, FontStyle.Bold)); + PropertyDrawerUtils.AddDefaultNodeProperties(sheet, node, m_SetNodesAsDirtyCallback, m_UpdateNodeViewsCallback); + if (!node.isOrphaned) + { + AddDescription(ProviderInspectorUtils.AddSection(sheet, "Description"), node); + + var settings = new VisualElement(); + AddSettings(settings, node, m_SetNodesAsDirtyCallback, m_UpdateNodeViewsCallback); + if (settings.childCount > 0) + ProviderInspectorUtils.AddSection(sheet, "Settings").Add(settings); + } + ProviderInspectorUtils.AddMessages(sheet, node.messages); + return sheet; + } + + void IPropertyDrawer.DisposePropertyDrawer() + { + } + + void AddDescription(VisualElement section, AbstractProviderNode node) + { + var provider = node.Provider; + ProviderInspectorUtils.AddValue(section, "Key", provider.Info.ProviderKey); + AddDescriptionValues(section, node); + if (provider.Definition is IShaderFunction function) + ProviderInspectorUtils.AddBlock(section, "Signature", ShaderObjectUtils.QualifySignature(function)); + AddDescriptionBlocks(section, node); + } + + private protected virtual void AddDescriptionValues(VisualElement section, AbstractProviderNode node) + { + } + + private protected virtual void AddDescriptionBlocks(VisualElement section, AbstractProviderNode node) + { + } + + private protected virtual void AddSettings(VisualElement section, AbstractProviderNode node, Action setNodesAsDirtyCallback, Action updateNodeViewsCallback) + { + } + } +} diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector/AbstractProviderNodePropertyDrawer.cs.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector/AbstractProviderNodePropertyDrawer.cs.meta new file mode 100644 index 00000000000..875d565059d --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector/AbstractProviderNodePropertyDrawer.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 8e476852975ae46e4b8a88e66aaff02d \ No newline at end of file diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector/ProviderInspectorUtils.cs b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector/ProviderInspectorUtils.cs new file mode 100644 index 00000000000..00f5f4d0d05 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector/ProviderInspectorUtils.cs @@ -0,0 +1,74 @@ +using System.Collections.Generic; +using System.Text; +using UnityEditor.ShaderGraph.Drawing; +using UnityEngine.UIElements; + +namespace UnityEditor.ShaderGraph.ProviderSystem +{ + static class ProviderInspectorUtils + { + const string kClass = "sg-provider-inspector"; + + internal static VisualElement AddSection(VisualElement parentElement, string title) + { + var section = new VisualElement(); + ProviderStyleSheets.Add(section, ProviderStyleSheets.kProviderInspector); + var header = new Label(title); + header.AddToClassList($"{kClass}__header"); + section.Add(header); + + var rows = new VisualElement(); + rows.AddToClassList($"{kClass}__rows"); + section.Add(rows); + parentElement.Add(section); + return rows; + } + + internal static void AddValue(VisualElement section, string label, string value) + { + var text = new Label(value); + text.selection.isSelectable = true; + text.AddToClassList($"{kClass}__value"); + var row = new PropertyRow(new Label(label)); + row.Add(text); + section.Add(row); + } + + internal static void AddBlock(VisualElement section, string label, string value) + { + var caption = new Label(label); + caption.AddToClassList($"{kClass}__caption"); + section.Add(caption); + section.Add(new HelpBoxRow(value, MessageType.None)); + } + + internal static void AddSetting(VisualElement section, string label, string tooltip, VisualElement field) + { + var row = new PropertyRow(new Label(label) { tooltip = tooltip }); + row.Add(field); + section.Add(row); + } + + internal static void AddMessages(VisualElement parentElement, IReadOnlyList messages) + { + if (messages.Count == 0) + return; + + var section = AddSection(parentElement, "Messages"); + StringBuilder sb = new(); + for (int i = 0; i < messages.Count;) + { + var subject = messages[i].subject; + var worstSeverity = messages[i].severity; + sb.Clear(); + for (; i < messages.Count && messages[i].subject == subject; i++) + { + sb.AppendLine(messages[i].ToString()); + if (messages[i].severity > worstSeverity) + worstSeverity = messages[i].severity; + } + section.Add(new HelpBoxRow(sb.ToString().TrimEnd(), worstSeverity)); + } + } + } +} diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector/ProviderInspectorUtils.cs.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector/ProviderInspectorUtils.cs.meta new file mode 100644 index 00000000000..22fb1ed4582 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector/ProviderInspectorUtils.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 805dde380d2964562b813c35452568c7 \ No newline at end of file diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector/ProviderNodePropertyDrawer.cs b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector/ProviderNodePropertyDrawer.cs new file mode 100644 index 00000000000..6618e07c22e --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector/ProviderNodePropertyDrawer.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; +using UnityEngine.UIElements; +using UnityEditor.ShaderGraph.ProviderSystem; +using Unity.GraphAuthoring.Editor.ProviderSystem; + +namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers +{ + [SGPropertyDrawer(typeof(ProviderNode))] + class ProviderNodePropertyDrawer : AbstractProviderNodePropertyDrawer + { + private protected override void AddDescriptionValues(VisualElement section, AbstractProviderNode node) + { + if (node.Provider.AssetID != default) + ProviderInspectorUtils.AddValue(section, "Source", AssetDatabase.GUIDToAssetPath(node.Provider.AssetID)); + } + + private protected override void AddDescriptionBlocks(VisualElement section, AbstractProviderNode node) + { + if (node.Provider.AssetID != default) + ProviderInspectorUtils.AddBlock(section, "Definition", ShaderObjectUtils.GenerateCode(node.Provider.Definition, false, false)); + } + + private protected override void AddSettings(VisualElement section, AbstractProviderNode nodeBase, Action setNodesAsDirtyCallback, Action updateNodeViewsCallback) + { + var node = (ProviderNode)nodeBase; + var versionCandidates = node.Header?.versionCandidates; + if (versionCandidates == null || versionCandidates.Length < 1) + return; + + string currentVersion = node.Header.version; + var choices = new List(versionCandidates.Length); + int currentIdx = 0; + for (int i = 0; i < versionCandidates.Length; i++) + { + choices.Add(versionCandidates[i].version); + if (versionCandidates[i].version == currentVersion) + currentIdx = i; + } + + var versionDropdown = new DropdownField(choices, currentIdx); + versionDropdown.RegisterValueChangedCallback(_ => + { + int newIdx = versionDropdown.index; + if (versionCandidates[newIdx].version == node.Header.version) + return; + + setNodesAsDirtyCallback?.Invoke(); + node.owner.owner.RegisterCompleteObjectUndo($"Change {node.name} Version"); + node.InitializeFromProvider(versionCandidates[newIdx].provider); + node.owner.ValidateGraph(); + updateNodeViewsCallback?.Invoke(); + inspectorUpdateDelegate?.Invoke(); + }); + ProviderInspectorUtils.AddSetting(section, "Version", null, versionDropdown); + } + } +} diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/ProviderNodePropertyDrawer.cs.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector/ProviderNodePropertyDrawer.cs.meta similarity index 100% rename from Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/ProviderNodePropertyDrawer.cs.meta rename to Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector/ProviderNodePropertyDrawer.cs.meta diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/ShaderInterfaceSettings.cs b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector/ShaderInterfaceSettings.cs similarity index 90% rename from Packages/com.unity.shadergraph/Editor/ProviderSystem/ShaderInterfaceSettings.cs rename to Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector/ShaderInterfaceSettings.cs index e7c99f09f77..324d54cbf3f 100644 --- a/Packages/com.unity.shadergraph/Editor/ProviderSystem/ShaderInterfaceSettings.cs +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector/ShaderInterfaceSettings.cs @@ -48,7 +48,7 @@ internal ShaderInterfaceSettings(GraphData graph) { m_Graph = graph; name = "shaderInterfaceSettings"; - styleSheets.Add(AssetDatabase.LoadAssetAtPath("Packages/com.unity.shadergraph/Editor/UIResources/Styles/ShaderInterfaceSettings.uss")); + ProviderStyleSheets.Add(this, ProviderStyleSheets.kShaderInterfaceSettings); Rebuild(); } @@ -66,7 +66,7 @@ void Rebuild() var provider = m_Graph.shaderInterface; var pickerLine = new VisualElement(); pickerLine.AddToClassList($"{k_Class}__picker-line"); - pickerLine.Add(CreatePicker(provider?.ProviderKey)); + pickerLine.Add(CreatePicker(provider != null ? provider.Info.ProviderKey ?? DescribeAsset(provider) : null)); Add(CreateRow("Interface", pickerLine)); if (provider == null) @@ -77,19 +77,22 @@ void Rebuild() if (!provider.IsValid) { - Add(new HelpBoxRow($"Shader interface '{provider.ProviderKey}' can't be found or failed to load. Select another interface or restore its source file.", MessageType.Warning)); + Add(new HelpBoxRow($"Shader interface '{DescribeAsset(provider)}' can't be found or failed to load. Select another interface or restore its source file.", MessageType.Warning)); return; } m_InterfaceKey = provider.AssetID.ToString(); pickerLine.Add(CreateShowInProjectButton(AssetDatabase.GUIDToAssetPath(provider.AssetID))); + List messages = new(); + ProviderMessageUtils.Collect(provider.Messages, provider.Definition, messages); + ProviderInspectorUtils.AddMessages(this, messages); AddDefinition(provider.Definition); } void AddDefinition(IShaderInterface definition) { - if (definition.BaseShaderID != default) - Add(CreateRow("Base Shader", CreateReadOnlyAssetField(AssetDatabase.GUIDToAssetPath(definition.BaseShaderID)))); + if (definition.BaseShaderAssetID != default) + Add(CreateRow("Base Shader", CreateReadOnlyAssetField(AssetDatabase.GUIDToAssetPath(definition.BaseShaderAssetID)))); AddProperties(definition.Fields); @@ -142,7 +145,7 @@ bool AddDeclarations(VisualElement parent, Scope scope) bool AddFunctions(VisualElement parent, Scope scope) { - var functions = m_Functions.FindAll(f => scope.Contains(f.Scopes)); + var functions = m_Functions.FindAll(f => scope.Contains(f.Passes)); if (functions.Count == 0) return false; @@ -158,7 +161,7 @@ bool AddStructs(VisualElement parent, Scope scope) foreach (var partialStruct in m_Structs) { var fields = FieldsIn(partialStruct, scope); - if (fields.Count > 0 || scope.Contains(partialStruct.Scopes)) + if (fields.Count > 0 || scope.Contains(partialStruct.Passes)) structs.Add((partialStruct, fields)); } @@ -179,7 +182,7 @@ static List FieldsIn(IPartialStruct partialStruct, Scope sco { List fields = new(); foreach (var field in partialStruct.Fields) - if (field is IShaderStructField structField && scope.Contains(structField.Scopes)) + if (field is IShaderStructField structField && scope.Contains(structField.Passes)) fields.Add(structField); return fields; } @@ -195,13 +198,13 @@ void AddAll(IEnumerable scopes) AddAll(m_Passes); foreach (var function in m_Functions) - AddAll(function.Scopes); + AddAll(function.Passes); foreach (var partialStruct in m_Structs) { - AddAll(partialStruct.Scopes); + AddAll(partialStruct.Passes); foreach (var field in partialStruct.Fields) if (field is IShaderStructField structField) - AddAll(structField.Scopes); + AddAll(structField.Passes); } return indices; } @@ -281,6 +284,12 @@ static void ShowInProject(string path) EditorGUIUtility.PingObject(asset); } + static string DescribeAsset(IProvider provider) + { + var path = AssetDatabase.GUIDToAssetPath(provider.AssetID); + return string.IsNullOrEmpty(path) ? provider.AssetID.ToString() : path; + } + Button CreatePicker(string interfaceName) { var picker = new Button(); @@ -310,7 +319,7 @@ void ShowSearcher(VisualElement picker) List items = new(); foreach (var provider in library.MainProviders()) - items.Add(new SearcherItem(provider.ProviderKey, AssetDatabase.GUIDToAssetPath(provider.AssetID), userData: provider)); + items.Add(new SearcherItem(provider.Info.ProviderKey, AssetDatabase.GUIDToAssetPath(provider.AssetID), userData: provider)); var searcher = new Searcher.Searcher(SearcherDatabase.Create(items, string.Empty, false), new SearchWindowAdapter("Select Shader Interface")); SearcherWindow.Show(host, searcher, item => SelectInterface(item?.UserData as IProvider), picker.worldBound.center, null); diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/ShaderInterfaceSettings.cs.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector/ShaderInterfaceSettings.cs.meta similarity index 100% rename from Packages/com.unity.shadergraph/Editor/ProviderSystem/ShaderInterfaceSettings.cs.meta rename to Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector/ShaderInterfaceSettings.cs.meta diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector/VirtualFunctionNodePropertyDrawer.cs b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector/VirtualFunctionNodePropertyDrawer.cs new file mode 100644 index 00000000000..f32f287fcef --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector/VirtualFunctionNodePropertyDrawer.cs @@ -0,0 +1,36 @@ +using System; +using Unity.GraphAuthoring.Editor.ProviderSystem; +using UnityEditor.ShaderGraph.ProviderSystem; +using UnityEngine.UIElements; + +namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers +{ + [SGPropertyDrawer(typeof(AbstractVirtualFunctionNode))] + class VirtualFunctionNodePropertyDrawer : AbstractProviderNodePropertyDrawer + { + private protected override void AddDescriptionValues(VisualElement section, AbstractProviderNode node) + => ProviderInspectorUtils.AddValue(section, "Context", AbstractVirtualFunctionNode.ContextLabel(AbstractVirtualFunctionNode.ContextOf(node.Provider.Definition))); + + private protected override void AddSettings(VisualElement section, AbstractProviderNode node, Action setNodesAsDirtyCallback, Action updateNodeViewsCallback) + { + var provider = node.Provider; + var definition = provider.Definition; + bool hasBase = AbstractVirtualFunctionNode.HasBase(definition); + var toggle = new Toggle { value = definition.EnsureBaseCall }; + toggle.SetEnabled(hasBase); + toggle.RegisterValueChangedCallback(evt => + { + setNodesAsDirtyCallback?.Invoke(); + node.owner.owner?.RegisterCompleteObjectUndo(evt.newValue ? "Ensure Base Call" : "Don't Ensure Base Call"); + node.owner.SetEnsureBaseCall(provider.Info.ProviderKey, evt.newValue); + updateNodeViewsCallback?.Invoke(); + inspectorUpdateDelegate?.Invoke(); + }); + + var tooltip = hasBase + ? "Calls the base implementation first, unless a Base node already calls it." + : "A pure virtual function has no base implementation to call."; + ProviderInspectorUtils.AddSetting(section, "Ensure Base Call", tooltip, toggle); + } + } +} diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector/VirtualFunctionNodePropertyDrawer.cs.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector/VirtualFunctionNodePropertyDrawer.cs.meta new file mode 100644 index 00000000000..6e0c97c2683 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Inspector/VirtualFunctionNodePropertyDrawer.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 1ebe60793190749818c3b0ab6c2d37d5 \ No newline at end of file diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/AbstractProviderNode.cs b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/AbstractProviderNode.cs new file mode 100644 index 00000000000..c0a67210400 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/AbstractProviderNode.cs @@ -0,0 +1,200 @@ +using System; +using System.Collections.Generic; +using Unity.GraphAuthoring.Editor.ProviderSystem; +using UnityEditor.Graphing; +using UnityEngine; + +namespace UnityEditor.ShaderGraph.ProviderSystem +{ + // A node backed by a provider. + internal interface IProviderNode + { + IProvider Provider { get; } + + bool isOrphaned { get; } + + bool isLocal { get; } + + void InitializeFromNode(IProviderNode source); + } + + [Serializable] + internal abstract class AbstractProviderNode : AbstractMaterialNode, IProviderNode, IHasAssetDependencies where T : IDefinition + { + [SerializeReference] + IProvider m_provider; + + // Set instead of a copy when the graph's shader interface owns the provider. + [SerializeField] + string m_providerKey; + + internal IProvider Provider => isLocal ? FindLocalProvider() : m_provider; + + IProvider FindLocalProvider() + => owner?.shaderInterface is ShaderInterfaceProvider shaderInterface && TryFind(shaderInterface, m_providerKey, out var provider) ? provider : null; + + IProvider IProviderNode.Provider => Provider; + + // Saved graphs store a missing key as an empty string. + internal bool isLocal => !string.IsNullOrEmpty(m_providerKey); + + bool IProviderNode.isLocal => isLocal; + + internal string providerKey => m_providerKey; + + // Only node types that override this can refer to an interface's provider. + private protected virtual bool TryFind(ShaderInterfaceProvider shaderInterface, string key, out IProvider provider) + { + provider = null; + return false; + } + + // Subgraphs have no shader interface to refer to. + public override bool allowedInSubGraph => !isLocal; + + internal bool isOrphaned => Provider is not { IsValid: true }; + + bool IProviderNode.isOrphaned => isOrphaned; + + // An orphan generates nothing, but its errors still fail the import when it feeds what was generated. + internal override bool wasUsedByGenerator => base.wasUsedByGenerator || (isOrphaned && FeedsUsedNode()); + + // Orphans further down are skipped: what they feed is already in the list. + bool FeedsUsedNode() + { + List downstream = new(); + NodeUtils.CollectNodesNodeFeedsInto(downstream, this, NodeUtils.IncludeSelf.Exclude); + foreach (var node in downstream) + { + if (node is not IProviderNode { isOrphaned: true } && node.wasUsedByGenerator) + return true; + } + return false; + } + + internal IReadOnlyList messages { get; private set; } = Array.Empty(); + + internal override bool ExposeToSearcher => false; + + // Owns a copy of the provider. + internal void InitializeFromProvider(IProvider provider) + { + m_providerKey = null; + m_provider = (IProvider)provider?.Clone(); + Refresh(); + } + + // Refers to the shader interface's provider by its key. + internal void InitializeFromLocalProvider(IProvider provider) + { + m_provider = null; + m_providerKey = provider?.Info.ProviderKey; + Refresh(provider); + } + + // Takes another node's source: its key when it's local, else a copy of its provider. + internal void InitializeFromNode(AbstractProviderNode source) + { + if (!source.isLocal) + { + InitializeFromProvider(source.Provider); + return; + } + m_provider = null; + m_providerKey = source.m_providerKey; + Refresh(source.Provider ?? Provider); + } + + void IProviderNode.InitializeFromNode(IProviderNode source) + { + if (source is AbstractProviderNode node) + InitializeFromNode(node); + } + + private protected abstract void BuildModel(T definition); + + private protected virtual string missingProviderMessage => "Node is in an invalid state and cannot recover."; + + // A local node follows the interface's asset, so it still refreshes when the interface drops its key. + UnityEngine.GUID sourceAssetID => isLocal ? owner?.shaderInterface?.AssetID ?? default : m_provider?.AssetID ?? default; + + // Names what the interface should declare, such as "virtual function". + private protected string NotDeclaredMessage(string declaration) => owner?.shaderInterface == null + ? "No shader interface is selected." + : $"No {declaration} '{m_providerKey}' is declared by shader interface '{owner.shaderInterface.Info.ProviderKey}'."; + + private protected virtual void AddNodeMessages(IProvider provider, List messages) + { + } + + internal void UpdateModel() => UpdateModel(Provider); + + void UpdateModel(IProvider provider) + { + List collected = new(); + if (provider == null) + collected.Add(new NodeMessage(null, missingProviderMessage, MessageType.Error)); + else + { + ProviderMessageUtils.Collect(provider.Messages, provider.Definition as IFieldCollection, collected); + if (provider.IsValid) + BuildModel(provider.Definition); + else if (collected.Count == 0) + collected.Add(new NodeMessage(null, NotLoadedMessage(provider), MessageType.Error)); + } + AddNodeMessages(provider, collected); + messages = collected; + } + + static string NotLoadedMessage(IProvider provider) => provider.AssetID == default + ? $"'{provider.Info.ProviderKey}' could not be loaded." + : $"'{provider.Info.ProviderKey}' could not be loaded from '{AssetDatabase.GUIDToAssetPath(provider.AssetID)}'."; + + internal void Refresh() => Refresh(Provider); + + // For a node that isn't in a graph yet, so it can't look its provider up. + private protected void Refresh(IProvider provider) + { + UpdateModel(provider); + ValidateNode(); + Dirty(ModificationScope.Graph); + } + + public bool Reload(HashSet changedAssetGuids) + { + var assetID = sourceAssetID; + if (assetID == default || !changedAssetGuids.Contains(assetID.ToString())) + return false; + + Provider?.Reload(); + Refresh(); + return true; + } + + public override void UpdateNodeAfterDeserialization() + { + base.UpdateNodeAfterDeserialization(); + Refresh(); + } + + public override void Concretize() + { + SetOverrideActiveState(isOrphaned ? ActiveState.ExplicitInactive : ActiveState.Implicit); + UpdateModel(); + base.Concretize(); + } + + public override void ValidateNode() + { + base.ValidateNode(); + foreach (var message in messages) + { + var compilerSeverity = message.severity == MessageType.Error ? Rendering.ShaderCompilerMessageSeverity.Error : Rendering.ShaderCompilerMessageSeverity.Warning; + if (isOrphaned) + owner?.AddSetupError(objectId, message.ToString(), compilerSeverity); + else + owner?.AddValidationError(objectId, message.ToString(), compilerSeverity); + } + } + } +} diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/AbstractProviderNode.cs.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/AbstractProviderNode.cs.meta new file mode 100644 index 00000000000..0ba3373dfe6 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/AbstractProviderNode.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 8e9205fd1781d4d1ca53a5639ec2cd80 \ No newline at end of file diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/AbstractVirtualFunctionNode.cs b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/AbstractVirtualFunctionNode.cs new file mode 100644 index 00000000000..26d86303703 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/AbstractVirtualFunctionNode.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Generic; +using Unity.GraphAuthoring.Editor.ProviderSystem; +using UnityEditor.Graphing; + +namespace UnityEditor.ShaderGraph.ProviderSystem +{ + [Serializable] + internal abstract class AbstractVirtualFunctionNode : AbstractProviderNode + { + internal const string kNoContextLabel = "No Context"; + + internal abstract string shortName { get; } + + private protected abstract SlotLayout slotLayout { get; } + + private protected override string missingProviderMessage => NotDeclaredMessage("virtual function"); + + public override bool hasPreview => false; + + public override bool canSetPrecision => false; + + public override string documentationURL => Provider?.Definition?.Presentation.HelpUrl is { Length: > 0 } url ? url : base.documentationURL; + + internal static string ContextOf(IVirtualFunction definition) => definition.Presentation.Context ?? string.Empty; + + internal static string ContextLabel(string context) => string.IsNullOrEmpty(context) ? kNoContextLabel : context; + + internal static bool HasBase(IVirtualFunction definition) => !definition.IsPureVirtual; + + internal static List NodesFor(IVirtualFunction definition) + { + List nodes = new() { new VirtualFunctionInputNode() }; + if (HasBase(definition)) + nodes.Add(new VirtualFunctionBaseNode()); + return nodes; + } + + internal virtual string TitleFor(IVirtualFunction definition) => $"{definition.Presentation.DisplayName} {shortName}"; + + private protected override bool TryFind(ShaderInterfaceProvider shaderInterface, string key, out IProvider provider) + => shaderInterface.TryGetVirtualFunctionProvider(key, out provider); + + private protected sealed override void BuildModel(IVirtualFunction definition) + { + name = TitleFor(definition); + synonyms = SearchTerms(definition); + ProviderSlotUtils.Rebuild(this, definition, slotLayout); + } + + string[] SearchTerms(IVirtualFunction definition) + { + var presentation = definition.Presentation; + List terms = new() { presentation.DisplayName, "virtual function", "local", shortName.ToLowerInvariant() }; + var context = ContextOf(definition); + if (context.Length > 0) + terms.Add(context); + foreach (var term in presentation.SearchTerms ?? Array.Empty()) + if (!terms.Contains(term)) + terms.Add(term); + return terms.ToArray(); + } + + // Until virtual functions generate code, nodes downstream read the default values of the outputs. + protected internal override string GetOutputForSlot(SlotReference fromSocketRef, ConcreteSlotValueType valueType, GenerationMode generationMode) + => FindOutputSlot(fromSocketRef.slotId)?.GetDefaultValue(generationMode) ?? string.Empty; + } +} diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/AbstractVirtualFunctionNode.cs.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/AbstractVirtualFunctionNode.cs.meta new file mode 100644 index 00000000000..598d727ed64 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/AbstractVirtualFunctionNode.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 80519ae9e6c524f6bb912e6ce34bd0d4 \ No newline at end of file diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/ExpressionNode.cs b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/ExpressionNode.cs index 1232cc368cc..0ed0c44c966 100644 --- a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/ExpressionNode.cs +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/ExpressionNode.cs @@ -29,7 +29,7 @@ enum SupportedTypes { Vector1, Vector2, Vector3, Vector4 } [EnumControl("Type")] SupportedTypes SelectedType { - get => FromTypeName(TypedProvider.ShaderType); + get => FromTypeName(TypedProvider.TypeName); set { TypedProvider.UpdateExpression(hlslFunctionName, Expression, ToTypeName(value), s_keywordFilter); @@ -45,7 +45,7 @@ internal string Expression { if (value == null) // Text control can misbehave in undo redo scenarios; we'll need to visit that separately. return; - TypedProvider.UpdateExpression(hlslFunctionName, value, TypedProvider.ShaderType, s_keywordFilter); + TypedProvider.UpdateExpression(hlslFunctionName, value, TypedProvider.TypeName, s_keywordFilter); Refresh(); } } @@ -54,9 +54,9 @@ public ExpressionNode() { } public override void UpdateNodeAfterDeserialization() { - // Ensure the keyword filter is in place before base calls Refresh() → Provider.Reload(). + // Ensure the keyword filter is in place before base refreshes from the provider. // Handles fresh nodes and graphs saved before [SerializeReference] was introduced. - TypedProvider?.UpdateExpression(hlslFunctionName, TypedProvider.Expression, TypedProvider.ShaderType, s_keywordFilter); + TypedProvider?.UpdateExpression(hlslFunctionName, TypedProvider.Expression, TypedProvider.TypeName, s_keywordFilter); base.UpdateNodeAfterDeserialization(); } diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/Header/FunctionHeader.cs b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/Header/FunctionHeader.cs index cc606ade7d4..6e61cbcfc2a 100644 --- a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/Header/FunctionHeader.cs +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/Header/FunctionHeader.cs @@ -30,14 +30,13 @@ internal class FunctionHeader internal (IProvider provider, string label)[] groupCandidates { get; private set; } internal (IProvider provider, string version)[] versionCandidates { get; private set; } - internal IReadOnlyList<(string subject, string text, MessageType severity)> messages { get; private set; } - internal FunctionHeader(IShaderFunction func, IProvider provider) : this(func, provider, false) { } FunctionHeader(IShaderFunction func, IProvider provider, bool skipGroup) { + var info = provider.Info; referenceName = func.Name; - version = provider.Version; + version = info.Version; var presentation = func.Presentation; displayName = presentation.DisplayName; @@ -51,10 +50,10 @@ internal FunctionHeader(IShaderFunction func, IProvider provider) : this(func, p helpUrl = presentation.HelpUrl; - if (provider.Group != null) + if (info.Group != null) { groupDropdownEntryName = displayName; - displayName = presentation.GroupDisplayName ?? provider.Group; + displayName = presentation.GroupDisplayName ?? info.Group; searchName = displayName; groupLabel = presentation.GroupLabel ?? "Variant"; @@ -64,7 +63,7 @@ internal FunctionHeader(IShaderFunction func, IProvider provider) : this(func, p if (!skipGroup && ProviderLibrary.TryGetInstance(out var lib)) { bool first = true; - foreach (var groupProvider in lib.ProvidersByGroup(provider.Group)) + foreach (var groupProvider in lib.ProvidersByGroup(info.Group)) { var groupHeader = new FunctionHeader(groupProvider.Definition, groupProvider, true); if (first) // Main provider's information wins. @@ -94,36 +93,16 @@ internal FunctionHeader(IShaderFunction func, IProvider provider) : this(func, p // Version: List<(IProvider provider, string version)> rawVersions = new(); - if (ProviderLibrary.TryGetInstance(out var versionLib)) - { - foreach(var versionedProvider in versionLib.ProvidersByVersion(provider.ProviderKey)) - rawVersions.Add((versionedProvider, versionedProvider.Version)); + if (info.ProviderKey != null && ProviderLibrary.TryGetInstance(out var versionLib)) + { + foreach (var versionedProvider in versionLib.ProvidersByVersion(info.ProviderKey)) + rawVersions.Add((versionedProvider, versionedProvider.Info.Version)); } else { - rawVersions.Add((provider as IProvider, provider.Version)); + rawVersions.Add((provider as IProvider, version)); } versionCandidates = rawVersions.ToArray(); - - messages = CollectMessages(func, provider); - } - - static List<(string, string, MessageType)> CollectMessages(IShaderFunction func, IProvider provider) - { - List<(string, string, MessageType)> messages = new(); - if (provider.Messages == null) - return messages; - - List subjects = new() { null }; - foreach (var param in func.Parameters) - if (!subjects.Contains(param.Name)) - subjects.Add(param.Name); - - foreach (var subject in subjects) - foreach (var message in provider.Messages) - if (message.Subject == subject) - messages.Add((subject, message.Text, (MessageType)message.Severity)); - return messages; } } } diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/NodeMessage.cs b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/NodeMessage.cs new file mode 100644 index 00000000000..27866e558d4 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/NodeMessage.cs @@ -0,0 +1,19 @@ +namespace UnityEditor.ShaderGraph.ProviderSystem +{ + // A null subject is about the whole node. + readonly struct NodeMessage + { + internal string subject { get; } + internal string text { get; } + internal MessageType severity { get; } + + internal NodeMessage(string subject, string text, MessageType severity) + { + this.subject = subject; + this.text = text; + this.severity = severity; + } + + public override string ToString() => subject != null ? $"'{subject}': {text}" : text; + } +} diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/NodeMessage.cs.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/NodeMessage.cs.meta new file mode 100644 index 00000000000..58b346e4e3b --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/NodeMessage.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: adf80ca0412b14661aa3697deda4cc31 \ No newline at end of file diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/ProviderMessageUtils.cs b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/ProviderMessageUtils.cs new file mode 100644 index 00000000000..0363cea0422 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/ProviderMessageUtils.cs @@ -0,0 +1,28 @@ +using System.Collections.Generic; +using Unity.GraphAuthoring.Editor.ProviderSystem; + +namespace UnityEditor.ShaderGraph.ProviderSystem +{ + static class ProviderMessageUtils + { + internal static void Collect(IReadOnlyList messages, IFieldCollection definition, List collected) + { + if (messages == null) + return; + + List subjects = new() { null }; + if (definition != null) + foreach (var field in definition.Fields) + if (!subjects.Contains(field.Name)) + subjects.Add(field.Name); + foreach (var message in messages) + if (!subjects.Contains(message.Subject)) + subjects.Add(message.Subject); + + foreach (var subject in subjects) + foreach (var message in messages) + if (message.Subject == subject) + collected.Add(new NodeMessage(subject, message.Text, (MessageType)message.Severity)); + } + } +} diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/ProviderMessageUtils.cs.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/ProviderMessageUtils.cs.meta new file mode 100644 index 00000000000..443b242e999 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/ProviderMessageUtils.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 430495790815b4fea86bebb3440fae2c \ No newline at end of file diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/ProviderNode.cs b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/ProviderNode.cs index fd866c05d93..0ed41bc4304 100644 --- a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/ProviderNode.cs +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/ProviderNode.cs @@ -6,16 +6,13 @@ namespace UnityEditor.ShaderGraph.ProviderSystem { - // A Base Node serving as the entry point for Provider based function definitions. - // This Model object can work with any sort of function provider, interpret the function definition, - // and generate a valid model representation of that object. This abstracts the need for node definitions - // to be aware of how the model functions. + // Calls a function from any function provider; its slots follow the function's definition. // NOTE: There exists an ExpressionProvider currently, so it's not a problem to have Models that are specializations, // but ideally the expression input type would be gracefully handled in a generic way and it wouldn't be necessary. [Serializable] [HasDependencies(typeof(MinimalProviderNode))] - internal class ProviderNode : AbstractMaterialNode, IHasAssetDependencies, IGeneratesBodyCode, IGeneratesFunction + internal class ProviderNode : AbstractProviderNode, IGeneratesBodyCode, IGeneratesFunction { [Serializable] internal class MinimalProviderNode : IHasDependencies @@ -40,13 +37,8 @@ public void GetSourceAssetDependencies(AssetCollection assetCollection) [GroupVariantControl] internal ProviderNode groupVariantSentinel => this; - [SerializeReference] - IProvider m_provider; - internal FunctionHeader Header { get; private set; } - internal IProvider Provider => m_provider; - const int kReservedOutputSlot = ProviderSlotUtils.kReturnSlotId; public override bool hasPreview => true; @@ -57,73 +49,22 @@ public void GetSourceAssetDependencies(AssetCollection assetCollection) public override string documentationURL => Header?.helpUrl ?? base.documentationURL; - internal override bool ExposeToSearcher => false; - public ProviderNode() { name = "Provider Based Node"; } - internal void InitializeFromProvider(IProvider provider) - { - this.m_provider = (IProvider)provider.Clone(); - UpdateModel(); - } - - public override void UpdateNodeAfterDeserialization() + private protected override void BuildModel(IShaderFunction definition) { - base.UpdateNodeAfterDeserialization(); - Refresh(); + Header = new FunctionHeader(definition, Provider); + name = Header.displayName; + synonyms = Header.searchTerms; + ProviderSlotUtils.Rebuild(this, definition); } - public override void Concretize() - { - UpdateModel(); - base.Concretize(); - } - - public bool Reload(HashSet changedAssetGuids) - { - // Scripted providers don't react to asset changes — their definition is in-memory. - if (Provider.AssetID != default && changedAssetGuids.Contains(Provider.AssetID.ToString())) - { - Refresh(); - return true; - } - return false; - } - - protected void Refresh() - { - Provider?.Reload(); - UpdateModel(); - ValidateNode(); - Dirty(ModificationScope.Graph); - } - - internal void UpdateModel() - { - if (Provider == null || Provider.Definition == null || !Provider.IsValid) - return; - - Header = new FunctionHeader(Provider.Definition, Provider); - - var header = Header; - this.name = header.displayName; - this.synonyms = header.searchTerms; - - ProviderSlotUtils.Rebuild(this, Provider.Definition); - } - - static Rendering.ShaderCompilerMessageSeverity ToCompilerSeverity(MessageType severity) => severity switch - { - MessageType.Error => Rendering.ShaderCompilerMessageSeverity.Error, - _ => Rendering.ShaderCompilerMessageSeverity.Warning, - }; - public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMode) { - if (this.Provider == null || this.Provider.Definition == null) + if (isOrphaned) return; // Apply legacy precision/dynamic only before code generation/usage. @@ -192,32 +133,11 @@ public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMo public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode generationMode) { - if (Provider == null || !Provider.IsValid || Provider.Definition == null) + if (isOrphaned) return; HeaderUtils.TryApplyLegacyPrecisionTokens(Provider.Definition, PrecisionUtil.Token, lastKnownDynamicVectorLength, out var func); DefinitionCodeGenerator.CollectFunctions(func, registry); } - - public override void ValidateNode() - { - base.ValidateNode(); - if (Provider == null) - { - owner?.AddSetupError(this.objectId, "Node is in an invalid state and cannot recover."); - return; - } - else if (Provider.AssetID != default && (Provider.Definition == null || !Provider.Definition.IsValid)) - { - var path = AssetDatabase.GUIDToAssetPath(Provider.AssetID); - owner?.AddSetupError(this.objectId, $"Data for '{Provider.ProviderKey}' expected in '{path}'."); - return; - } - else if (Header != null) - { - foreach (var (_, text, severity) in Header.messages) - owner?.AddValidationError(this.objectId, text, ToCompilerSeverity(severity)); - } - } } } diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/ProviderNodePropertyDrawer.cs b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/ProviderNodePropertyDrawer.cs deleted file mode 100644 index 34204750558..00000000000 --- a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/ProviderNodePropertyDrawer.cs +++ /dev/null @@ -1,99 +0,0 @@ -using System; -using System.Collections.Generic; -using UnityEngine.UIElements; -using UnityEditor.UIElements; -using UnityEditor.Graphing; -using UnityEditor.ShaderGraph.ProviderSystem; -using Unity.GraphAuthoring.Editor.ProviderSystem; -using System.Text; - -namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers -{ - [SGPropertyDrawer(typeof(ProviderNode))] - class ProviderNodeNodePropertyDrawer : AbstractMaterialNodePropertyDrawer - { - private ProviderNode node; - - internal override void AddCustomNodeProperties(VisualElement parentElement, AbstractMaterialNode nodeBase, Action setNodesAsDirtyCallback, Action updateNodeViewsCallback) - { - node = nodeBase as ProviderNode; - var provider = node.Provider; - bool hasAssetSource = provider.AssetID != default; - string sourcePath = hasAssetSource ? AssetDatabase.GUIDToAssetPath(provider.AssetID) : null; - string providerKey = provider.ProviderKey; - - if (!provider.IsValid) - { - var errorMessage = hasAssetSource - ? $"Could not find '{providerKey}' in '{sourcePath}'." - : $"Could not find '{providerKey}'."; - parentElement.Add(new HelpBoxRow(errorMessage, MessageType.Error)); - return; - } - - var versionCandidates = node.Header?.versionCandidates; - if (versionCandidates != null && versionCandidates.Length >= 1) - { - string currentVersion = node.Header.version; - var choices = new List(versionCandidates.Length); - int currentIdx = 0; - for (int i = 0; i < versionCandidates.Length; i++) - { - choices.Add(versionCandidates[i].version); - if (versionCandidates[i].version == currentVersion) - currentIdx = i; - } - - var versionDropdown = new DropdownField("Version", choices, currentIdx); - versionDropdown.RegisterValueChangedCallback(_ => - { - int newIdx = versionDropdown.index; - if (versionCandidates[newIdx].version == node.Header.version) - return; - - setNodesAsDirtyCallback?.Invoke(); - node.owner.owner.RegisterCompleteObjectUndo($"Change {node.name} Version"); - node.InitializeFromProvider(versionCandidates[newIdx].provider); - node.ValidateNode(); - node.Dirty(ModificationScope.Graph); - updateNodeViewsCallback?.Invoke(); - inspectorUpdateDelegate?.Invoke(); - }); - parentElement.Add(versionDropdown); - } - - if (hasAssetSource) - { - parentElement.Add(new Label("Provider Key")); - parentElement.Add(new HelpBoxRow(providerKey, MessageType.None)); - - parentElement.Add(new Label("Source Path")); - parentElement.Add(new HelpBoxRow(sourcePath, MessageType.None)); - - string qualifiedSignature = ShaderObjectUtils.QualifySignature(node.Provider.Definition); - parentElement.Add(new Label("Qualified Signature")); - parentElement.Add(new HelpBoxRow(qualifiedSignature, MessageType.None)); - - string code = ShaderObjectUtils.GenerateCode(provider.Definition, false, false); - parentElement.Add(new Label("Expected Definition")); - parentElement.Add(new HelpBoxRow(code, MessageType.None)); - } - - var messages = node.Header?.messages; - StringBuilder sb = new(); - for (int i = 0; messages != null && i < messages.Count;) - { - var subject = messages[i].subject; - var worstSeverity = MessageType.Warning; - sb.Clear(); - for (; i < messages.Count && messages[i].subject == subject; i++) - { - sb.AppendLine(messages[i].text); - if (messages[i].severity > worstSeverity) worstSeverity = messages[i].severity; - } - parentElement.Add(new Label(subject == null ? "Function Hint Messages" : $"Parameter '{subject}' Hint Messages")); - parentElement.Add(new HelpBoxRow(sb.ToString(), worstSeverity)); - } - } - } -} diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/ProviderSlotUtils.cs b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/ProviderSlotUtils.cs index a16bf21b585..bb3d6c64e19 100644 --- a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/ProviderSlotUtils.cs +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/ProviderSlotUtils.cs @@ -4,30 +4,45 @@ namespace UnityEditor.ShaderGraph.ProviderSystem { + // An unconnected input that has an incoming value (a Base argument, an Output inout) passes it through. + internal enum SlotLayout + { + AsDeclared, + AsDeclaredPassthrough, + + // Out and inout parameters and the return value, as inputs. + OutputsAsInputs, + + // In and inout parameters, as outputs. + InputsAsOutputs, + } + static class ProviderSlotUtils { internal const int kReturnSlotId = 0; - internal static void Rebuild(AbstractMaterialNode node, IFieldCollection definition) + internal static void Rebuild(AbstractMaterialNode node, IFieldCollection definition, SlotLayout layout = SlotLayout.AsDeclared) { var previousIds = PreviousSlotIds(node); HashSet usedIds = new(); List slots = new(); // Return type is a special case. - if (definition is IShaderFunction function && !ShaderObjectUtils.IsVoid(function.ReturnType)) + if (layout != SlotLayout.InputsAsOutputs && definition is IShaderFunction function && !ShaderObjectUtils.IsVoid(function.ReturnType)) { usedIds.Add(kReturnSlotId); - slots.Add(HeaderUtils.MakeSlotFromField(ShaderObjectUtils.MakeReturnField(function, HeaderUtils.kReturnSlotName), kReturnSlotId, SlotType.Output)); + var direction = layout == SlotLayout.OutputsAsInputs ? SlotType.Input : SlotType.Output; + slots.Add(HeaderUtils.MakeSlotFromField(ShaderObjectUtils.MakeReturnField(function, HeaderUtils.kReturnSlotName), kReturnSlotId, direction)); } foreach (var field in definition.Fields) { if (!previousIds.TryGetValue(field.Name, out var ids)) continue; - if (field.IsInput && ids.input > -1) + var (asInput, asOutput) = Sides(field, layout); + if (asInput && ids.input > -1) usedIds.Add(ids.input); - if (field.IsOutput && ids.output > -1) + if (asOutput && ids.output > -1) usedIds.Add(ids.output); } @@ -44,15 +59,29 @@ int NewId() if (!previousIds.TryGetValue(field.Name, out var ids)) ids = (-1, -1); - if (field.IsInput) - slots.Add(HeaderUtils.MakeSlotFromField(field, ids.input > -1 ? ids.input : NewId(), SlotType.Input)); - if (field.IsOutput) + var (asInput, asOutput) = Sides(field, layout); + if (asInput) + { + var slot = HeaderUtils.MakeSlotFromField(field, ids.input > -1 ? ids.input : NewId(), SlotType.Input); + // Instead of a value, an input that passes the incoming argument shows the parameter's direction. + if (field.IsInput && layout is SlotLayout.AsDeclaredPassthrough or SlotLayout.OutputsAsInputs) + slot.CustomBinding = field.IsOutput ? "inout" : "in"; + slots.Add(slot); + } + if (asOutput) slots.Add(HeaderUtils.MakeSlotFromField(field, ids.output > -1 ? ids.output : NewId(), SlotType.Output)); } Apply(node, slots); } + static (bool asInput, bool asOutput) Sides(IShaderField field, SlotLayout layout) => layout switch + { + SlotLayout.OutputsAsInputs => (field.IsOutput, false), + SlotLayout.InputsAsOutputs => (false, field.IsInput), + _ => (field.IsInput, field.IsOutput), + }; + internal static void Apply(AbstractMaterialNode node, IReadOnlyList slots) { List order = new(); @@ -62,7 +91,16 @@ internal static void Apply(AbstractMaterialNode node, IReadOnlyList m_ShaderInterface; + + [SerializeField] + List m_Stacks = new(); + + internal IProvider shaderInterface + { + get => m_ShaderInterface; + set => m_ShaderInterface = (IProvider)value?.Clone(); + } + + internal IReadOnlyList stacks => m_Stacks; + + internal override string displayName => "Shader Interface"; + + internal bool SetStacks(List stacks) + { + bool same = stacks.Count == m_Stacks.Count; + for (int i = 0; same && i < stacks.Count; ++i) + same = m_Stacks[i].Matches(stacks[i]); + if (same) + return false; + + m_Stacks = stacks; + return true; + } + + internal bool RemoveFromStack(string providerKey) + { + var stack = m_Stacks.Find(s => s.Holds(providerKey)); + if (stack == null) + return false; + stack.Remove(providerKey); + if (stack.providerKeys.Count == 0) + m_Stacks.Remove(stack); + return true; + } + + internal override void OnPropertiesGUI(VisualElement context, Action onChange, Action registerUndo, GraphData owner) + { + } + + public bool Reload(HashSet changedAssetGuids) + { + if (m_ShaderInterface == null || !changedAssetGuids.Contains(m_ShaderInterface.AssetID.ToString())) + return false; + + m_ShaderInterface.Reload(); + return true; + } + + public void GetSourceAssetDependencies(AssetCollection assetCollection) + { + if (m_ShaderInterface == null || m_ShaderInterface.AssetID == default) + return; + + assetCollection.AddAssetDependency(m_ShaderInterface.AssetID, + AssetCollection.Flags.SourceDependency + | AssetCollection.Flags.ArtifactDependency + | AssetCollection.Flags.IncludeInExportPackage); + } + } +} diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/ShaderInterfaceGraphData.cs.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/ShaderInterfaceGraphData.cs.meta new file mode 100644 index 00000000000..cb8f561edf5 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/ShaderInterfaceGraphData.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f2813516930574acb876ae1859f8ac69 \ No newline at end of file diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/VirtualFunctionBaseNode.cs b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/VirtualFunctionBaseNode.cs new file mode 100644 index 00000000000..b86b0d0f26b --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/VirtualFunctionBaseNode.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using Unity.GraphAuthoring.Editor.ProviderSystem; + +namespace UnityEditor.ShaderGraph.ProviderSystem +{ + [Serializable] + internal class VirtualFunctionBaseNode : AbstractVirtualFunctionNode + { + internal override string shortName => "Base"; + + private protected override SlotLayout slotLayout => SlotLayout.AsDeclaredPassthrough; + + public VirtualFunctionBaseNode() + { + name = "Virtual Function Base"; + } + + private protected override void AddNodeMessages(IProvider provider, List messages) + { + if (provider is { IsValid: true } && !HasBase(provider.Definition)) + messages.Add(new NodeMessage(null, $"'{name}' calls a pure virtual function, which has no base implementation.", MessageType.Error)); + } + } +} diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/VirtualFunctionBaseNode.cs.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/VirtualFunctionBaseNode.cs.meta new file mode 100644 index 00000000000..70e029ce088 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/VirtualFunctionBaseNode.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 9415362e3a490476ea992cf770147a60 \ No newline at end of file diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/VirtualFunctionInputNode.cs b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/VirtualFunctionInputNode.cs new file mode 100644 index 00000000000..d9a8b8507c5 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/VirtualFunctionInputNode.cs @@ -0,0 +1,17 @@ +using System; + +namespace UnityEditor.ShaderGraph.ProviderSystem +{ + [Serializable] + internal class VirtualFunctionInputNode : AbstractVirtualFunctionNode + { + internal override string shortName => "Input"; + + private protected override SlotLayout slotLayout => SlotLayout.InputsAsOutputs; + + public VirtualFunctionInputNode() + { + name = "Virtual Function Input"; + } + } +} diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/VirtualFunctionInputNode.cs.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/VirtualFunctionInputNode.cs.meta new file mode 100644 index 00000000000..6e9d22f5d9a --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/VirtualFunctionInputNode.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 5bd479e1a2e174944ba3a5d77597398b \ No newline at end of file diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/VirtualFunctionOutputNode.cs b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/VirtualFunctionOutputNode.cs new file mode 100644 index 00000000000..9977f8740a9 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/VirtualFunctionOutputNode.cs @@ -0,0 +1,28 @@ +using System; +using Unity.GraphAuthoring.Editor.ProviderSystem; + +namespace UnityEditor.ShaderGraph.ProviderSystem +{ + // The graph keeps one per virtual function, in its context's stack. + [Serializable] + internal class VirtualFunctionOutputNode : AbstractVirtualFunctionNode + { + internal override string shortName => "Output"; + + private protected override SlotLayout slotLayout => SlotLayout.OutputsAsInputs; + + public override bool canDeleteNode => isOrphaned; + + public override bool canCopyNode => false; + + public override bool canCutNode => false; + + public VirtualFunctionOutputNode() + { + name = "Virtual Function Output"; + } + + // Its stack already says what it is. + internal override string TitleFor(IVirtualFunction definition) => definition.Presentation.DisplayName; + } +} diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/VirtualFunctionOutputNode.cs.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/VirtualFunctionOutputNode.cs.meta new file mode 100644 index 00000000000..783e24d51e6 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/VirtualFunctionOutputNode.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c4bd102543a9645e387f9126def68dae \ No newline at end of file diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/VirtualFunctionStackData.cs b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/VirtualFunctionStackData.cs new file mode 100644 index 00000000000..55902f881d2 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/VirtualFunctionStackData.cs @@ -0,0 +1,182 @@ +using System; +using System.Collections.Generic; +using Unity.GraphAuthoring.Editor.ProviderSystem; +using UnityEngine; + +namespace UnityEditor.ShaderGraph.ProviderSystem +{ + // Holds its output nodes by provider key, in order. + [Serializable] + sealed class VirtualFunctionStackData + { + [SerializeField] + string m_Context; + + [SerializeField] + List m_ProviderKeys = new(); + + [SerializeField] + Vector2 m_Position; + + [SerializeField] + bool m_IsPlaced; + + internal VirtualFunctionStackData(string context, List providerKeys) + { + m_Context = context ?? string.Empty; + m_ProviderKeys = providerKeys; + } + + internal string context => m_Context ?? string.Empty; + + internal IReadOnlyList providerKeys => m_ProviderKeys; + + internal bool isPlaced => m_IsPlaced; + + internal Vector2 position + { + get => m_Position; + set + { + m_Position = value; + m_IsPlaced = true; + } + } + + internal bool Holds(string providerKey) => m_ProviderKeys.Contains(providerKey); + + internal void Remove(string providerKey) => m_ProviderKeys.Remove(providerKey); + + internal bool Matches(VirtualFunctionStackData other) + { + if (context != other.context || m_ProviderKeys.Count != other.m_ProviderKeys.Count) + return false; + for (int i = 0; i < m_ProviderKeys.Count; ++i) + if (m_ProviderKeys[i] != other.m_ProviderKeys[i]) + return false; + return true; + } + + // Orphans follow the declared functions, in the stack they were in before. + internal static List StacksFor(List> functions, ICollection outputKeys, IReadOnlyList previousStacks) + { + List stacks = new(); + HashSet placed = new(); + + void Place(string context, string key) + { + if (!placed.Add(key)) + return; + var stack = stacks.Find(s => s.context == context); + if (stack == null) + { + stack = new VirtualFunctionStackData(context, new List()); + var previous = FindStack(previousStacks, context); + if (previous is { isPlaced: true }) + stack.position = previous.position; + stacks.Add(stack); + } + stack.m_ProviderKeys.Add(key); + } + + foreach (var function in Order(functions)) + Place(AbstractVirtualFunctionNode.ContextOf(function.Definition), function.Info.ProviderKey); + foreach (var stack in previousStacks) + foreach (var key in stack.providerKeys) + if (outputKeys.Contains(key)) + Place(stack.context, key); + foreach (var key in outputKeys) + Place(string.Empty, key); + return stacks; + } + + internal static void PlaceNew(IReadOnlyList stacks, IReadOnlyList sizes) + { + const float kSpacing = 60; + + bool anyPlaced = false; + float bottom = 0; + float left = 0; + for (int i = 0; i < stacks.Count; ++i) + { + if (!stacks[i].isPlaced) + continue; + var position = stacks[i].position; + bottom = anyPlaced ? Mathf.Max(bottom, position.y + sizes[i].y) : position.y + sizes[i].y; + left = anyPlaced ? Mathf.Min(left, position.x) : position.x; + anyPlaced = true; + } + + for (int i = 0; i < stacks.Count; ++i) + { + if (stacks[i].isPlaced) + continue; + stacks[i].position = anyPlaced ? new Vector2(left, bottom + kSpacing) : Vector2.zero; + bottom = stacks[i].position.y + sizes[i].y; + left = stacks[i].position.x; + anyPlaced = true; + } + } + + static VirtualFunctionStackData FindStack(IReadOnlyList stacks, string context) + { + foreach (var stack in stacks) + if (stack.context == context) + return stack; + return null; + } + + // Authored context orders first, then other contexts, then none; within each, authored orders first; ties keep the interface's order. + static List> Order(List> functions) + { + Dictionary contexts = new(); + for (int i = 0; i < functions.Count; ++i) + { + var presentation = functions[i].Definition.Presentation; + var context = AbstractVirtualFunctionNode.ContextOf(functions[i].Definition); + if (!contexts.TryGetValue(context, out var known)) + contexts.Add(context, (presentation.ContextOrder, i)); + else if (CompareOrders(presentation.ContextOrder, known.order) < 0) + contexts[context] = (presentation.ContextOrder, known.firstIndex); + } + + int CompareContexts(string a, string b) + { + if (a == b) + return 0; + if ((a.Length == 0) != (b.Length == 0)) + return a.Length == 0 ? 1 : -1; + var (orderA, firstA) = contexts[a]; + var (orderB, firstB) = contexts[b]; + int byOrder = CompareOrders(orderA, orderB); + return byOrder != 0 ? byOrder : firstA.CompareTo(firstB); + } + + List indices = new(); + for (int i = 0; i < functions.Count; ++i) + indices.Add(i); + indices.Sort((a, b) => + { + var definitionA = functions[a].Definition; + var definitionB = functions[b].Definition; + int byContext = CompareContexts(AbstractVirtualFunctionNode.ContextOf(definitionA), AbstractVirtualFunctionNode.ContextOf(definitionB)); + if (byContext != 0) + return byContext; + int byOrder = CompareOrders(definitionA.Presentation.OrderInContext, definitionB.Presentation.OrderInContext); + return byOrder != 0 ? byOrder : a.CompareTo(b); + }); + + List> ordered = new(); + foreach (var index in indices) + ordered.Add(functions[index]); + return ordered; + } + + static int CompareOrders(int? a, int? b) + { + if (a.HasValue != b.HasValue) + return a.HasValue ? -1 : 1; + return (a ?? 0).CompareTo(b ?? 0); + } + } +} diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/VirtualFunctionStackData.cs.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/VirtualFunctionStackData.cs.meta new file mode 100644 index 00000000000..15b14e3835c --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Model/VirtualFunctionStackData.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c6286ae95bd314791a303b02329c4457 \ No newline at end of file diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/ProviderModels.cs b/Packages/com.unity.shadergraph/Editor/ProviderSystem/ProviderModels.cs new file mode 100644 index 00000000000..79af18c4a5a --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/ProviderModels.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using Unity.GraphAuthoring.Editor.ProviderSystem; +using UnityEngine; + +namespace UnityEditor.ShaderGraph.ProviderSystem +{ + [AttributeUsage(AttributeTargets.Class)] + sealed class ProviderModelAttribute : Attribute + { + internal readonly string ProviderKey; + internal ProviderModelAttribute(string providerKey) { ProviderKey = providerKey; } + } + + static class ProviderModels + { + static Dictionary s_modelsByKey; + + internal static bool TryCreate(ProviderInfo info, out object model) + { + if (s_modelsByKey == null) + { + s_modelsByKey = new(); + foreach (var type in TypeCache.GetTypesWithAttribute()) + { + var key = type.GetCustomAttribute().ProviderKey; + if (string.IsNullOrEmpty(key)) + Debug.LogError($"'{type.Name}' is marked as a provider model but has no provider key."); + else if (!s_modelsByKey.TryAdd(key, type)) + Debug.LogError($"Attempted to register '{type.Name}' with provider key '{key}', but key is already registered to '{s_modelsByKey[key]}'."); + } + } + + if (info.ProviderKey != null && s_modelsByKey.TryGetValue(info.ProviderKey, out var modelType)) + { + model = Activator.CreateInstance(modelType, true); + return true; + } + model = null; + return false; + } + } +} diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/ProviderModels.cs.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/ProviderModels.cs.meta new file mode 100644 index 00000000000..7a49e86302d --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/ProviderModels.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e2252b052a8dd481babe391e134a190f \ No newline at end of file diff --git a/Packages/com.unity.shadergraph/Editor/UIResources/Styles.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Styles.meta similarity index 100% rename from Packages/com.unity.shadergraph/Editor/UIResources/Styles.meta rename to Packages/com.unity.shadergraph/Editor/ProviderSystem/Styles.meta diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Styles/LocalProviderHighlight.uss b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Styles/LocalProviderHighlight.uss new file mode 100644 index 00000000000..a45d6be9723 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Styles/LocalProviderHighlight.uss @@ -0,0 +1,3 @@ +.sg-local-provider-highlighted #selection-border { + background-color: rgba(68, 192, 255, 0.08); +} diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Styles/LocalProviderHighlight.uss.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Styles/LocalProviderHighlight.uss.meta new file mode 100644 index 00000000000..7c49c90d2f7 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Styles/LocalProviderHighlight.uss.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: eaa9a72a638941dfaca39b820fe01d89 +ScriptedImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 2 + userData: + assetBundleName: + assetBundleVariant: + script: {fileID: 12385, guid: 0000000000000000e000000000000000, type: 0} + disableValidation: 0 + unsupportedSelectorAction: 0 diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Styles/ProviderInspector.uss b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Styles/ProviderInspector.uss new file mode 100644 index 00000000000..5eaed591cca --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Styles/ProviderInspector.uss @@ -0,0 +1,22 @@ +/* Header and caption insets line up with PropertyRow's labels. */ +.sg-provider-inspector__header { + -unity-font-style: bold; + margin-top: 10px; + padding-left: 8px; +} + +.sg-provider-inspector__rows { + margin-left: 12px; +} + +.sg-provider-inspector__value { + flex-grow: 1; + -unity-font-style: normal; + -unity-text-align: middle-left; + white-space: normal; +} + +.sg-provider-inspector__caption { + margin-top: 4px; + padding-left: 8px; +} diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Styles/ProviderInspector.uss.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Styles/ProviderInspector.uss.meta new file mode 100644 index 00000000000..d186342d634 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Styles/ProviderInspector.uss.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 321be908b1b64146ab9471f88aa34c18 +ScriptedImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 2 + userData: + assetBundleName: + assetBundleVariant: + script: {fileID: 12385, guid: 0000000000000000e000000000000000, type: 0} + disableValidation: 0 + unsupportedSelectorAction: 0 diff --git a/Packages/com.unity.shadergraph/Editor/UIResources/Styles/ShaderInterfaceSettings.uss b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Styles/ShaderInterfaceSettings.uss similarity index 100% rename from Packages/com.unity.shadergraph/Editor/UIResources/Styles/ShaderInterfaceSettings.uss rename to Packages/com.unity.shadergraph/Editor/ProviderSystem/Styles/ShaderInterfaceSettings.uss diff --git a/Packages/com.unity.shadergraph/Editor/UIResources/Styles/ShaderInterfaceSettings.uss.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Styles/ShaderInterfaceSettings.uss.meta similarity index 100% rename from Packages/com.unity.shadergraph/Editor/UIResources/Styles/ShaderInterfaceSettings.uss.meta rename to Packages/com.unity.shadergraph/Editor/ProviderSystem/Styles/ShaderInterfaceSettings.uss.meta diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Styles/VirtualFunctionNodeDragger.uss b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Styles/VirtualFunctionNodeDragger.uss new file mode 100644 index 00000000000..8932c1d5480 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Styles/VirtualFunctionNodeDragger.uss @@ -0,0 +1,9 @@ +.sg-virtual-function-node-ghost { + position: absolute; + padding: 6px 10px; + border-radius: 6px; + background-color: var(--unity-colors-default-background); + color: var(--unity-colors-default-text); + -unity-font-style: bold; + opacity: 0.8; +} diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Styles/VirtualFunctionNodeDragger.uss.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Styles/VirtualFunctionNodeDragger.uss.meta new file mode 100644 index 00000000000..94150e64876 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Styles/VirtualFunctionNodeDragger.uss.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: c74cc759982574a67baa8f781704a760 +ScriptedImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 2 + userData: + assetBundleName: + assetBundleVariant: + script: {fileID: 12385, guid: 0000000000000000e000000000000000, type: 0} + disableValidation: 0 + unsupportedSelectorAction: 0 diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views.meta new file mode 100644 index 00000000000..6af26a5fb08 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 42549dbd3b6344dd9941dd0ec7790810 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/GroupVariantControl.cs b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/GroupVariantControl.cs similarity index 89% rename from Packages/com.unity.shadergraph/Editor/ProviderSystem/GroupVariantControl.cs rename to Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/GroupVariantControl.cs index 8566b1c97b6..d1732065327 100644 --- a/Packages/com.unity.shadergraph/Editor/ProviderSystem/GroupVariantControl.cs +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/GroupVariantControl.cs @@ -59,9 +59,9 @@ int CurrentIndex() { var candidates = m_Node.Header?.groupCandidates; if (candidates == null) return 0; - var key = m_Node.Provider?.ProviderKey; + var key = m_Node.Provider?.Info.ProviderKey; for (int i = 0; i < candidates.Length; i++) - if (candidates[i].provider.ProviderKey == key) + if (candidates[i].provider.Info.ProviderKey == key) return i; return 0; } @@ -71,13 +71,12 @@ void OnSelectionChanged(ChangeEvent evt) var candidates = m_Node.Header?.groupCandidates; if (candidates == null) return; int newIdx = m_Dropdown.index; - if (candidates[newIdx].provider.ProviderKey == m_Node.Provider?.ProviderKey) + if (candidates[newIdx].provider.Info.ProviderKey == m_Node.Provider?.Info.ProviderKey) return; m_Node.owner.owner.RegisterCompleteObjectUndo($"Change {m_Node.name} Variant"); m_Node.InitializeFromProvider(candidates[newIdx].provider); - m_Node.ValidateNode(); - m_Node.Dirty(ModificationScope.Graph); + m_Node.owner.ValidateGraph(); } } } diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/GroupVariantControl.cs.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/GroupVariantControl.cs.meta similarity index 100% rename from Packages/com.unity.shadergraph/Editor/ProviderSystem/GroupVariantControl.cs.meta rename to Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/GroupVariantControl.cs.meta diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/LocalProviderHighlight.cs b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/LocalProviderHighlight.cs new file mode 100644 index 00000000000..d68043c0b53 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/LocalProviderHighlight.cs @@ -0,0 +1,51 @@ +using System.Collections.Generic; +using UnityEditor.ShaderGraph.Drawing; +using UnityEngine.UIElements; + +namespace UnityEditor.ShaderGraph.ProviderSystem +{ + // Hovering a local provider node highlights the other nodes of the same provider, the way hovering a property highlights its nodes. + sealed class LocalProviderHighlight + { + // Not Shader Graph's "hovered", whose node style adds a border. + internal const string kHighlightedClass = "sg-local-provider-highlighted"; + + readonly MaterialGraphView m_GraphView; + readonly List m_Highlighted = new(); + + internal LocalProviderHighlight(MaterialGraphView graphView) + { + m_GraphView = graphView; + } + + internal void Attach(MaterialNodeView view) + { + ProviderStyleSheets.Add(view, ProviderStyleSheets.kLocalProviderHighlight); + view.RegisterCallback(_ => Enter(view)); + view.RegisterCallback(_ => Leave()); + } + + void Enter(MaterialNodeView hovered) + { + Leave(); + if (hovered.node is not IProviderNode { isLocal: true, Provider: { } provider }) + return; + + m_GraphView.nodes.ForEach(view => + { + if (view != hovered && view is MaterialNodeView { node: IProviderNode { isLocal: true } node } nodeView && node.Provider == provider) + { + nodeView.AddToClassList(kHighlightedClass); + m_Highlighted.Add(nodeView); + } + }); + } + + void Leave() + { + foreach (var view in m_Highlighted) + view.RemoveFromClassList(kHighlightedClass); + m_Highlighted.Clear(); + } + } +} diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/LocalProviderHighlight.cs.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/LocalProviderHighlight.cs.meta new file mode 100644 index 00000000000..3fc8067e634 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/LocalProviderHighlight.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 039061cd0c6a49b6946ad79564ea1055 \ No newline at end of file diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/LocalProviderSearchEntries.cs b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/LocalProviderSearchEntries.cs new file mode 100644 index 00000000000..d9575f10def --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/LocalProviderSearchEntries.cs @@ -0,0 +1,35 @@ +using System.Collections.Generic; + +namespace UnityEditor.ShaderGraph.ProviderSystem +{ + static class LocalProviderSearchEntries + { + // Listed first, with only this header in italics. + internal const string kCategory = "Locals"; + + internal static List<(string[] path, AbstractMaterialNode node)> For(GraphData graph) + { + List<(string[], AbstractMaterialNode)> entries = new(); + HashSet paths = new(); + foreach (var provider in graph.loadedVirtualFunctions) + { + var context = AbstractVirtualFunctionNode.ContextLabel(AbstractVirtualFunctionNode.ContextOf(provider.Definition)); + foreach (var node in AbstractVirtualFunctionNode.NodesFor(provider.Definition)) + { + node.InitializeFromLocalProvider(provider); + entries.Add((Unique(paths, new[] { kCategory, "Virtual Functions", context, node.name }), node)); + } + } + return entries; + } + + // The searcher merges entries with the same path, so later ones are numbered like the library's. + static string[] Unique(HashSet paths, string[] path) + { + var name = path[path.Length - 1]; + for (int i = 1; !paths.Add(string.Join("/", path)); ++i) + path[path.Length - 1] = $"{name}, ({i})"; + return path; + } + } +} diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/LocalProviderSearchEntries.cs.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/LocalProviderSearchEntries.cs.meta new file mode 100644 index 00000000000..e3a04e5b393 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/LocalProviderSearchEntries.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c3dace2a5d6ab4c5f966217cdad19d2d \ No newline at end of file diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/LocalsSearchWindowAdapter.cs b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/LocalsSearchWindowAdapter.cs new file mode 100644 index 00000000000..b946ec26f04 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/LocalsSearchWindowAdapter.cs @@ -0,0 +1,31 @@ +using UnityEditor.Searcher; +using UnityEngine; +using UnityEngine.UIElements; + +namespace UnityEditor.ShaderGraph.ProviderSystem +{ + // The node searcher's adapter, which sets the Locals category apart. + class LocalsSearchWindowAdapter : SearchWindowAdapter + { + internal LocalsSearchWindowAdapter(string title) : base(title) + { + } + + public override VisualElement Bind(VisualElement element, SearcherItem item, ItemExpanderState expanderState, string query) + { + var expander = base.Bind(element, item, expanderState, query); + StyleLocalsCategory(element, item); + return expander; + } + + // Rows are reused, so every row sets the style. + static void StyleLocalsCategory(VisualElement row, SearcherItem item) + { + var labels = row.Q("labelsContainer"); + if (labels == null) + return; + bool isLocals = item.Depth == 0 && item.Name == LocalProviderSearchEntries.kCategory; + labels.style.unityFontStyleAndWeight = isLocals ? new StyleEnum(FontStyle.Italic) : new StyleEnum(StyleKeyword.Null); + } + } +} diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/LocalsSearchWindowAdapter.cs.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/LocalsSearchWindowAdapter.cs.meta new file mode 100644 index 00000000000..5c1a7eb4570 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/LocalsSearchWindowAdapter.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f2058bc27b19f4ded8c0a1709ed9a870 \ No newline at end of file diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/ProviderStyleSheets.cs b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/ProviderStyleSheets.cs new file mode 100644 index 00000000000..8af539d050f --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/ProviderStyleSheets.cs @@ -0,0 +1,25 @@ +using UnityEngine; +using UnityEngine.UIElements; + +namespace UnityEditor.ShaderGraph.ProviderSystem +{ + static class ProviderStyleSheets + { + internal const string kLocalProviderHighlight = "LocalProviderHighlight"; + internal const string kProviderInspector = "ProviderInspector"; + internal const string kShaderInterfaceSettings = "ShaderInterfaceSettings"; + internal const string kVirtualFunctionNodeDragger = "VirtualFunctionNodeDragger"; + + const string kFolder = "Packages/com.unity.shadergraph/Editor/ProviderSystem/Styles/"; + + internal static void Add(VisualElement element, string name) + { + var path = kFolder + name + ".uss"; + var sheet = AssetDatabase.LoadAssetAtPath(path); + if (sheet != null) + element.styleSheets.Add(sheet); + else + Debug.LogWarning($"Style sheet '{path}' could not be loaded."); + } + } +} diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/ProviderStyleSheets.cs.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/ProviderStyleSheets.cs.meta new file mode 100644 index 00000000000..16440ba9a4d --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/ProviderStyleSheets.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 9403845002d114da3ae3b6f3add49717 \ No newline at end of file diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/VirtualFunctionNodeDragger.cs b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/VirtualFunctionNodeDragger.cs new file mode 100644 index 00000000000..7197ae7fcfa --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/VirtualFunctionNodeDragger.cs @@ -0,0 +1,138 @@ +using UnityEditor.Experimental.GraphView; +using UnityEditor.ShaderGraph.Drawing.Views; +using UnityEngine; +using UnityEngine.UIElements; + +namespace UnityEditor.ShaderGraph.ProviderSystem +{ + sealed class VirtualFunctionNodeDragger : Manipulator + { + const float kDragThreshold = 8; + + readonly GraphView m_GraphView; + readonly VirtualFunctionOutputNode m_Output; + + Vector2 m_PressPosition; + bool m_Pressed; + Label m_Ghost; + AbstractVirtualFunctionNode m_Input; + AbstractVirtualFunctionNode m_Base; + AbstractVirtualFunctionNode m_Shown; + + internal VirtualFunctionNodeDragger(GraphView graphView, VirtualFunctionOutputNode output) + { + m_GraphView = graphView; + m_Output = output; + } + + protected override void RegisterCallbacksOnTarget() + { + target.RegisterCallback(OnMouseDown); + target.RegisterCallback(OnMouseMove); + target.RegisterCallback(OnMouseUp); + target.RegisterCallback(OnMouseCaptureOut); + target.RegisterCallback(OnKeyDown); + } + + protected override void UnregisterCallbacksFromTarget() + { + target.UnregisterCallback(OnMouseDown); + target.UnregisterCallback(OnMouseMove); + target.UnregisterCallback(OnMouseUp); + target.UnregisterCallback(OnMouseCaptureOut); + target.UnregisterCallback(OnKeyDown); + } + + AbstractVirtualFunctionNode NodeToCreate(bool actionKey) => actionKey && m_Base != null ? m_Base : m_Input; + + void OnMouseDown(MouseDownEvent evt) + { + // Inline input fields sit outside the node's bounds, so presses on them don't start a drag. + if (evt.button != (int)MouseButton.LeftMouse || evt.altKey || target is not GraphElement node || !node.HitTest(node.WorldToLocal(evt.mousePosition))) + return; + + // Non-movable nodes must stop the click, or GraphView's rectangle selector clears the selection. + evt.StopPropagation(); + if (m_Output.isOrphaned || target.panel?.GetCapturingElement(PointerId.mousePointerId) != null) + return; + + m_PressPosition = evt.mousePosition; + m_Pressed = true; + target.CaptureMouse(); + } + + void OnMouseMove(MouseMoveEvent evt) + { + if (!m_Pressed) + return; + + if (m_Ghost == null) + { + if ((evt.mousePosition - m_PressPosition).magnitude < kDragThreshold) + return; + m_Input = new VirtualFunctionInputNode(); + m_Base = AbstractVirtualFunctionNode.HasBase(m_Output.Provider.Definition) ? new VirtualFunctionBaseNode() : null; + m_Ghost = CreateGhost(); + m_GraphView.Add(m_Ghost); + } + + m_Shown = NodeToCreate(evt.actionKey); + m_Ghost.text = m_Shown.TitleFor(m_Output.Provider.Definition); + var position = m_GraphView.WorldToLocal(evt.mousePosition); + m_Ghost.style.left = position.x; + m_Ghost.style.top = position.y; + evt.StopPropagation(); + } + + void OnMouseUp(MouseUpEvent evt) + { + if (!m_Pressed || evt.button != (int)MouseButton.LeftMouse) + return; + + var node = m_Shown; + End(); + if (node != null && !m_Output.isOrphaned && IsCanvas(m_GraphView.panel.Pick(evt.mousePosition))) + { + var graph = m_Output.owner; + graph.owner?.RegisterCompleteObjectUndo("Add " + node.TitleFor(m_Output.Provider.Definition)); + graph.AddLocalProviderNode(node, m_Output.Provider, m_GraphView.contentViewContainer.WorldToLocal(evt.mousePosition)); + } + evt.StopPropagation(); + } + + // The blackboard, inspector and preview sit inside the graph view, so they're ruled out by type. + bool IsCanvas(VisualElement picked) => picked?.GetFirstOfType() == m_GraphView + && picked.GetFirstOfType() == null && picked.GetFirstOfType() == null; + + void OnMouseCaptureOut(MouseCaptureOutEvent evt) => End(); + + void OnKeyDown(KeyDownEvent evt) + { + if (!m_Pressed || evt.keyCode != KeyCode.Escape) + return; + + End(); + evt.StopPropagation(); + } + + void End() + { + m_Pressed = false; + m_Ghost?.RemoveFromHierarchy(); + m_Ghost = null; + m_Input = null; + m_Base = null; + m_Shown = null; + if (target.HasMouseCapture()) + target.ReleaseMouse(); + } + + static Label CreateGhost() + { + var ghost = new Label { pickingMode = PickingMode.Ignore }; + ProviderStyleSheets.Add(ghost, ProviderStyleSheets.kVirtualFunctionNodeDragger); + ghost.AddToClassList("sg-virtual-function-node-ghost"); + return ghost; + } + } +} diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/VirtualFunctionNodeDragger.cs.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/VirtualFunctionNodeDragger.cs.meta new file mode 100644 index 00000000000..0e2e1edf7a6 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/VirtualFunctionNodeDragger.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 5bd06e71a96914b0395bbb39e043e735 \ No newline at end of file diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/VirtualFunctionNodeMenu.cs b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/VirtualFunctionNodeMenu.cs new file mode 100644 index 00000000000..8438085c47b --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/VirtualFunctionNodeMenu.cs @@ -0,0 +1,55 @@ +using UnityEditor.Experimental.GraphView; +using UnityEditor.ShaderGraph.Drawing; +using UnityEngine; +using UnityEngine.UIElements; + +namespace UnityEditor.ShaderGraph.ProviderSystem +{ + static class VirtualFunctionNodeMenu + { + const float kOffsetFromStack = 250; + const float kNodeSpacing = 150; + + internal static void AddActions(MaterialGraphView graphView, ContextualMenuPopulateEvent evt, IShaderNodeView nodeView) + { + if (!graphView.graph.isShaderInterfaceMode || nodeView.node is not AbstractVirtualFunctionNode { isOrphaned: false } node) + return; + + evt.menu.AppendSeparator(); + if (node is not VirtualFunctionOutputNode output) + evt.menu.AppendAction("Go to Output Node", _ => GoToOutputNode(graphView, node)); + else if (nodeView is Node view) + AddCreateActions(graphView, evt, output, view); + } + + internal static void GoToOutputNode(MaterialGraphView graphView, AbstractVirtualFunctionNode node) + { + if (!graphView.graph.VirtualFunctionOutputNodesByKey().TryGetValue(node.providerKey, out var output) || graphView.GetNodeByGuid(output.objectId) is not Node view) + return; + graphView.ClearSelection(); + graphView.AddToSelection(view); + graphView.FrameSelection(); + } + + static void AddCreateActions(MaterialGraphView graphView, ContextualMenuPopulateEvent evt, VirtualFunctionOutputNode output, Node view) + { + var stack = view.GetFirstAncestorOfType(); + var outputPosition = view.ChangeCoordinatesTo(graphView.contentViewContainer, Vector2.zero); + var position = new Vector2((stack?.GetPosition().xMin ?? outputPosition.x) - kOffsetFromStack, outputPosition.y); + + var graph = graphView.graph; + var definition = output.Provider.Definition; + var nodes = AbstractVirtualFunctionNode.NodesFor(definition); + for (int i = 0; i < nodes.Count; ++i) + { + var node = nodes[i]; + var nodePosition = position + new Vector2(0, i * kNodeSpacing); + evt.menu.AppendAction($"Create {node.shortName} Node", _ => + { + graph.owner?.RegisterCompleteObjectUndo("Add " + node.TitleFor(definition)); + graph.AddLocalProviderNode(node, output.Provider, nodePosition); + }); + } + } + } +} diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/VirtualFunctionNodeMenu.cs.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/VirtualFunctionNodeMenu.cs.meta new file mode 100644 index 00000000000..710b1275f73 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/VirtualFunctionNodeMenu.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 2e444e17a44414c6990cf227571d15ea \ No newline at end of file diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/VirtualFunctionStackLayout.cs b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/VirtualFunctionStackLayout.cs new file mode 100644 index 00000000000..1e435ae3602 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/VirtualFunctionStackLayout.cs @@ -0,0 +1,130 @@ +using System; +using System.Collections.Generic; +using UnityEditor.Experimental.GraphView; +using UnityEditor.ShaderGraph.Drawing; +using UnityEngine; +using UnityEngine.UIElements; + +namespace UnityEditor.ShaderGraph.ProviderSystem +{ + sealed class VirtualFunctionStackLayout + { + readonly MaterialGraphView m_GraphView; + readonly GraphData m_Graph; + readonly Dictionary m_Stacks = new(); + readonly List m_Chain = new(); + + internal VirtualFunctionStackLayout(MaterialGraphView graphView, GraphData graph) + { + m_GraphView = graphView; + m_Graph = graph; + } + + internal void AdoptOutputView(MaterialNodeView view, VirtualFunctionOutputNode output) + { + view.capabilities &= ~Capabilities.Movable; + view.AddManipulator(new VirtualFunctionNodeDragger(m_GraphView, output)); + } + + internal void Refresh() + { + var outputs = m_Graph.VirtualFunctionOutputNodesByKey(); + HashSet contexts = new(); + foreach (var stackData in m_Graph.virtualFunctionStacks) + { + contexts.Add(stackData.context); + if (m_Stacks.TryGetValue(stackData.context, out var stack)) + stack.Bind(stackData); + else + { + stack = new VirtualFunctionStackView(stackData); + stack.RegisterCallback(_ => PlaceNewStacks()); + m_GraphView.AddElement(stack); + m_Stacks.Add(stackData.context, stack); + } + + for (int i = 0; i < stackData.providerKeys.Count; ++i) + { + if (outputs.TryGetValue(stackData.providerKeys[i], out var output) && m_GraphView.GetNodeByGuid(output.objectId) is Node view) + PlaceInStack(view, stack, i); + } + } + + List removed = new(); + foreach (var pair in m_Stacks) + if (!contexts.Contains(pair.Key)) + removed.Add(pair.Key); + foreach (var context in removed) + { + m_GraphView.RemoveElement(m_Stacks[context]); + m_Stacks.Remove(context); + } + + Chain(); + PlaceNewStacks(); + } + + void PlaceInStack(Node view, VirtualFunctionStackView stack, int index) + { + var current = view.GetFirstAncestorOfType(); + if (current == stack && stack.IndexOf(view) == index) + return; + + if (current != null) + current.RemoveElement(view); + else + m_GraphView.RemoveElement(view); + stack.InsertElement(Math.Min(index, stack.childCount), view); + } + + void Chain() + { + foreach (var edge in m_Chain) + m_GraphView.RemoveElement(edge); + m_Chain.Clear(); + + var stacks = m_Graph.virtualFunctionStacks; + for (int i = 0; i < stacks.Count; ++i) + { + var view = m_Stacks[stacks[i].context]; + view.inputPort.style.display = i > 0 ? DisplayStyle.Flex : DisplayStyle.None; + view.outputPort.style.display = i < stacks.Count - 1 ? DisplayStyle.Flex : DisplayStyle.None; + } + + for (int i = 1; i < stacks.Count; ++i) + { + var edge = new Edge + { + output = m_Stacks[stacks[i - 1].context].outputPort, + input = m_Stacks[stacks[i].context].inputPort, + pickingMode = PickingMode.Ignore, + }; + m_GraphView.AddElement(edge); + m_Chain.Add(edge); + } + } + + // Waits for a layout while sizes are unknown; derived positions aren't recorded for undo. + void PlaceNewStacks() + { + var stacks = m_Graph.virtualFunctionStacks; + bool anyNew = false; + foreach (var stackData in stacks) + anyNew |= !stackData.isPlaced; + if (!anyNew) + return; + + List sizes = new(); + foreach (var stackData in stacks) + { + if (!m_Stacks.TryGetValue(stackData.context, out var stack) || float.IsNaN(stack.layout.width)) + return; + sizes.Add(stack.layout.size); + } + + VirtualFunctionStackData.PlaceNew(stacks, sizes); + foreach (var stackData in stacks) + m_Stacks[stackData.context].Bind(stackData); + } + } +} diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/VirtualFunctionStackLayout.cs.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/VirtualFunctionStackLayout.cs.meta new file mode 100644 index 00000000000..7b174e2a0cd --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/VirtualFunctionStackLayout.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 93a15f100244840a58200c46ecf6e95c \ No newline at end of file diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/VirtualFunctionStackView.cs b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/VirtualFunctionStackView.cs new file mode 100644 index 00000000000..8c3cdbd025a --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/VirtualFunctionStackView.cs @@ -0,0 +1,58 @@ +using UnityEditor.Experimental.GraphView; +using UnityEngine; +using UnityEngine.UIElements; + +namespace UnityEditor.ShaderGraph.ProviderSystem +{ + sealed class VirtualFunctionStackView : StackNode + { + internal VirtualFunctionStackData stackData { get; private set; } + + internal Port inputPort { get; } + internal Port outputPort { get; } + + internal VirtualFunctionStackView(VirtualFunctionStackData data) + { + capabilities &= ~(Capabilities.Deletable | Capabilities.Copiable); + var header = new Label(AbstractVirtualFunctionNode.ContextLabel(data.context)) { name = "headerLabel" }; + headerContainer.Add(header); + inputPort = AddPort(Direction.Input, inputContainer); + outputPort = AddPort(Direction.Output, outputContainer); + Bind(data); + + if (string.IsNullOrEmpty(data.context)) + { + var badge = InternalBridge.IconBadge.CreateComment("These virtual functions have no 'sg:Context' hint, so they are shown in this stack."); + hierarchy.Add(badge); + badge.AttachTo(header, SpriteAlignment.RightCenter); + } + } + + static Port AddPort(Direction direction, VisualElement container) + { + var port = Port.Create(Orientation.Vertical, direction, Port.Capacity.Single, null); + port.portName = string.Empty; + port.pickingMode = PickingMode.Ignore; + container.Add(port); + return port; + } + + internal void Bind(VirtualFunctionStackData data) + { + stackData = data; + if (data.isPlaced && GetPosition().position != data.position) + SetPosition(new Rect(data.position, Vector2.zero)); + } + + protected override bool AcceptsElement(GraphElement element, ref int proposedIndex, int maxIndex) + => element.userData is VirtualFunctionOutputNode output && stackData.Holds(output.providerKey); + + public override void BuildContextualMenu(ContextualMenuPopulateEvent evt) + { + } + + protected override void OnSeparatorContextualMenuEvent(ContextualMenuPopulateEvent evt, int separatorIndex) + { + } + } +} diff --git a/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/VirtualFunctionStackView.cs.meta b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/VirtualFunctionStackView.cs.meta new file mode 100644 index 00000000000..5e668079071 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/ProviderSystem/Views/VirtualFunctionStackView.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 4e905859b8c174cff965deb210a0f159 \ No newline at end of file diff --git a/Packages/com.unity.shadergraph/Editor/ShaderGraphProjectSettings.cs b/Packages/com.unity.shadergraph/Editor/ShaderGraphProjectSettings.cs index 1443990ee69..6fbe77cb2b4 100644 --- a/Packages/com.unity.shadergraph/Editor/ShaderGraphProjectSettings.cs +++ b/Packages/com.unity.shadergraph/Editor/ShaderGraphProjectSettings.cs @@ -141,7 +141,7 @@ void OnGUIHandler(string searchContext) GUILayout.FlexibleSpace(); if (GUILayout.Button(Styles.kLearnMore, Styles.learnMoreStyle)) { - System.Diagnostics.Process.Start(kCustomInterpolatorDocumentationURL); + Application.OpenURL(kCustomInterpolatorDocumentationURL); } EditorGUIUtility.AddCursorRect(GUILayoutUtility.GetLastRect(), MouseCursor.Link); GUILayout.EndHorizontal(); diff --git a/Packages/com.unity.shadergraph/Editor/ShaderGraphShortcuts.cs b/Packages/com.unity.shadergraph/Editor/ShaderGraphShortcuts.cs index 786037f228f..bfb54b82964 100644 --- a/Packages/com.unity.shadergraph/Editor/ShaderGraphShortcuts.cs +++ b/Packages/com.unity.shadergraph/Editor/ShaderGraphShortcuts.cs @@ -192,7 +192,7 @@ static void Documentation(ShortcutArguments args) foreach (var selected in GetGraphView().selection) if (selected is IShaderNodeView nodeView && nodeView.node.documentationURL != null) { - System.Diagnostics.Process.Start(nodeView.node.documentationURL); + Application.OpenURL(nodeView.node.documentationURL); break; } } diff --git a/Packages/com.unity.shadergraph/Samples~/Common/Meshes/Billboard/NegativeX.FBX.meta b/Packages/com.unity.shadergraph/Samples~/Common/Meshes/Billboard/NegativeX.fbx.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/Common/Meshes/Billboard/NegativeX.FBX.meta rename to Packages/com.unity.shadergraph/Samples~/Common/Meshes/Billboard/NegativeX.fbx.meta diff --git a/Packages/com.unity.shadergraph/Samples~/Common/Meshes/Billboard/NegativeY.FBX.meta b/Packages/com.unity.shadergraph/Samples~/Common/Meshes/Billboard/NegativeY.fbx.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/Common/Meshes/Billboard/NegativeY.FBX.meta rename to Packages/com.unity.shadergraph/Samples~/Common/Meshes/Billboard/NegativeY.fbx.meta diff --git a/Packages/com.unity.shadergraph/Samples~/Common/Meshes/Billboard/NegativeZ.FBX.meta b/Packages/com.unity.shadergraph/Samples~/Common/Meshes/Billboard/NegativeZ.fbx.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/Common/Meshes/Billboard/NegativeZ.FBX.meta rename to Packages/com.unity.shadergraph/Samples~/Common/Meshes/Billboard/NegativeZ.fbx.meta diff --git a/Packages/com.unity.shadergraph/Samples~/Common/Meshes/Billboard/PositiveX.FBX.meta b/Packages/com.unity.shadergraph/Samples~/Common/Meshes/Billboard/PositiveX.fbx.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/Common/Meshes/Billboard/PositiveX.FBX.meta rename to Packages/com.unity.shadergraph/Samples~/Common/Meshes/Billboard/PositiveX.fbx.meta diff --git a/Packages/com.unity.shadergraph/Samples~/Common/Meshes/Billboard/PositiveY.FBX.meta b/Packages/com.unity.shadergraph/Samples~/Common/Meshes/Billboard/PositiveY.fbx.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/Common/Meshes/Billboard/PositiveY.FBX.meta rename to Packages/com.unity.shadergraph/Samples~/Common/Meshes/Billboard/PositiveY.fbx.meta diff --git a/Packages/com.unity.shadergraph/Samples~/Common/Meshes/Billboard/PositiveZ.FBX.meta b/Packages/com.unity.shadergraph/Samples~/Common/Meshes/Billboard/PositiveZ.fbx.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/Common/Meshes/Billboard/PositiveZ.FBX.meta rename to Packages/com.unity.shadergraph/Samples~/Common/Meshes/Billboard/PositiveZ.fbx.meta diff --git a/Packages/com.unity.shadergraph/Samples~/Common/Meshes/Particles/ParticleStack100.FBX.meta b/Packages/com.unity.shadergraph/Samples~/Common/Meshes/Particles/ParticleStack100.fbx.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/Common/Meshes/Particles/ParticleStack100.FBX.meta rename to Packages/com.unity.shadergraph/Samples~/Common/Meshes/Particles/ParticleStack100.fbx.meta diff --git a/Packages/com.unity.shadergraph/Samples~/Common/Meshes/Particles/ParticleStack25.FBX.meta b/Packages/com.unity.shadergraph/Samples~/Common/Meshes/Particles/ParticleStack25.fbx.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/Common/Meshes/Particles/ParticleStack25.FBX.meta rename to Packages/com.unity.shadergraph/Samples~/Common/Meshes/Particles/ParticleStack25.fbx.meta diff --git a/Packages/com.unity.shadergraph/Samples~/Common/Meshes/Particles/ParticleStack50.FBX.meta b/Packages/com.unity.shadergraph/Samples~/Common/Meshes/Particles/ParticleStack50.fbx.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/Common/Meshes/Particles/ParticleStack50.FBX.meta rename to Packages/com.unity.shadergraph/Samples~/Common/Meshes/Particles/ParticleStack50.fbx.meta diff --git a/Packages/com.unity.shadergraph/Samples~/Common/Meshes/grass_bladeNoLOD10.FBX.meta b/Packages/com.unity.shadergraph/Samples~/Common/Meshes/grass_bladeNoLOD10.fbx.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/Common/Meshes/grass_bladeNoLOD10.FBX.meta rename to Packages/com.unity.shadergraph/Samples~/Common/Meshes/grass_bladeNoLOD10.fbx.meta diff --git a/Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Bacteria.ShaderSubGraph.meta b/Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Bacteria.shadersubgraph.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Bacteria.ShaderSubGraph.meta rename to Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Bacteria.shadersubgraph.meta diff --git a/Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Brick.ShaderSubGraph.meta b/Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Brick.shadersubgraph.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Brick.ShaderSubGraph.meta rename to Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Brick.shadersubgraph.meta diff --git a/Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Dots.ShaderSubGraph.meta b/Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Dots.shadersubgraph.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Dots.ShaderSubGraph.meta rename to Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Dots.shadersubgraph.meta diff --git a/Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Grid.ShaderSubGraph.meta b/Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Grid.shadersubgraph.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Grid.ShaderSubGraph.meta rename to Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Grid.shadersubgraph.meta diff --git a/Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Herringbone.ShaderSubGraph.meta b/Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Herringbone.shadersubgraph.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Herringbone.ShaderSubGraph.meta rename to Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Herringbone.shadersubgraph.meta diff --git a/Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Hex Lattice.ShaderSubGraph.meta b/Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Hex Lattice.shadersubgraph.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Hex Lattice.ShaderSubGraph.meta rename to Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Hex Lattice.shadersubgraph.meta diff --git a/Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Houndstooth.ShaderSubGraph.meta b/Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Houndstooth.shadersubgraph.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Houndstooth.ShaderSubGraph.meta rename to Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Houndstooth.shadersubgraph.meta diff --git a/Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Smooth Wave.ShaderSubGraph.meta b/Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Smooth Wave.shadersubgraph.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Smooth Wave.ShaderSubGraph.meta rename to Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Smooth Wave.shadersubgraph.meta diff --git a/Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Spiral.ShaderSubGraph.meta b/Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Spiral.shadersubgraph.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Spiral.ShaderSubGraph.meta rename to Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Spiral.shadersubgraph.meta diff --git a/Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Stripes.ShaderSubGraph.meta b/Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Stripes.shadersubgraph.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Stripes.ShaderSubGraph.meta rename to Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Stripes.shadersubgraph.meta diff --git a/Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Truchet.ShaderSubGraph.meta b/Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Truchet.shadersubgraph.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Truchet.ShaderSubGraph.meta rename to Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Truchet.shadersubgraph.meta diff --git a/Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Whirl.ShaderSubGraph.meta b/Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Whirl.shadersubgraph.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Whirl.ShaderSubGraph.meta rename to Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Whirl.shadersubgraph.meta diff --git a/Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Zig Zag.ShaderSubGraph.meta b/Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Zig Zag.shadersubgraph.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Zig Zag.ShaderSubGraph.meta rename to Packages/com.unity.shadergraph/Samples~/ProceduralPatterns/Zig Zag.shadersubgraph.meta diff --git a/Packages/com.unity.shadergraph/Samples~/ProductionReady/Environment/Details/Grass/grass_bladeNoLOD10.FBX.meta b/Packages/com.unity.shadergraph/Samples~/ProductionReady/Environment/Details/Grass/grass_bladeNoLOD10.fbx.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/ProductionReady/Environment/Details/Grass/grass_bladeNoLOD10.FBX.meta rename to Packages/com.unity.shadergraph/Samples~/ProductionReady/Environment/Details/Grass/grass_bladeNoLOD10.fbx.meta diff --git a/Packages/com.unity.shadergraph/Samples~/ProductionReady/Environment/Details/Grass/grass_bladeNoLOD15.FBX.meta b/Packages/com.unity.shadergraph/Samples~/ProductionReady/Environment/Details/Grass/grass_bladeNoLOD15.fbx.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/ProductionReady/Environment/Details/Grass/grass_bladeNoLOD15.FBX.meta rename to Packages/com.unity.shadergraph/Samples~/ProductionReady/Environment/Details/Grass/grass_bladeNoLOD15.fbx.meta diff --git a/Packages/com.unity.shadergraph/Samples~/ProductionReady/Environment/Details/Grass/grass_bladeNoLOD30.FBX.meta b/Packages/com.unity.shadergraph/Samples~/ProductionReady/Environment/Details/Grass/grass_bladeNoLOD30.fbx.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/ProductionReady/Environment/Details/Grass/grass_bladeNoLOD30.FBX.meta rename to Packages/com.unity.shadergraph/Samples~/ProductionReady/Environment/Details/Grass/grass_bladeNoLOD30.fbx.meta diff --git a/Packages/com.unity.shadergraph/Samples~/ProductionReady/Environment/Details/Pebbles/pebbles.FBX.meta b/Packages/com.unity.shadergraph/Samples~/ProductionReady/Environment/Details/Pebbles/pebbles.fbx.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/ProductionReady/Environment/Details/Pebbles/pebbles.FBX.meta rename to Packages/com.unity.shadergraph/Samples~/ProductionReady/Environment/Details/Pebbles/pebbles.fbx.meta diff --git a/Packages/com.unity.shadergraph/Samples~/ProductionReady/Environment/Details/clover/clover.FBX.meta b/Packages/com.unity.shadergraph/Samples~/ProductionReady/Environment/Details/clover/clover.fbx.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/ProductionReady/Environment/Details/clover/clover.FBX.meta rename to Packages/com.unity.shadergraph/Samples~/ProductionReady/Environment/Details/clover/clover.fbx.meta diff --git a/Packages/com.unity.shadergraph/Samples~/ProductionReady/Environment/Water/WaterFall.FBX.meta b/Packages/com.unity.shadergraph/Samples~/ProductionReady/Environment/Water/WaterFall.fbx.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/ProductionReady/Environment/Water/WaterFall.FBX.meta rename to Packages/com.unity.shadergraph/Samples~/ProductionReady/Environment/Water/WaterFall.fbx.meta diff --git a/Packages/com.unity.shadergraph/Samples~/ProductionReady/Environment/Water/WaterPlane.FBX.meta b/Packages/com.unity.shadergraph/Samples~/ProductionReady/Environment/Water/WaterPlane.fbx.meta similarity index 100% rename from Packages/com.unity.shadergraph/Samples~/ProductionReady/Environment/Water/WaterPlane.FBX.meta rename to Packages/com.unity.shadergraph/Samples~/ProductionReady/Environment/Water/WaterPlane.fbx.meta diff --git a/Packages/com.unity.shadergraph/Samples~/UGUIShaders/Scripts/BlurredHexagonController.cs b/Packages/com.unity.shadergraph/Samples~/UGUIShaders/Scripts/BlurredHexagonController.cs index a49bbe9e10b..1cc24394c3b 100644 --- a/Packages/com.unity.shadergraph/Samples~/UGUIShaders/Scripts/BlurredHexagonController.cs +++ b/Packages/com.unity.shadergraph/Samples~/UGUIShaders/Scripts/BlurredHexagonController.cs @@ -16,7 +16,13 @@ public class BlurredHexagonController : UIBehaviour, IMaterialModifier [SerializeField] Slider _saturationSlider, _tintRedSlider, _tintGreenSlider, _tintBlueSlider, _hexagonDissolveSlider, _hexagonTilesSlider, _blurSlider, _blurCyclesSlider, _blurSamplesPerCycleSlider; - static int _saturationId, _tintId, _hexagonDissolveId, _hexagonTilesId, _blurId, _blurCyclesId, _blurSamplesPerCycleId; + static readonly int _saturationId = Shader.PropertyToID(_saturationRef), + _tintId = Shader.PropertyToID(_tintRef), + _hexagonDissolveId = Shader.PropertyToID(_hexagonDissolveRef), + _hexagonTilesId = Shader.PropertyToID(_hexagonTilesRef), + _blurId = Shader.PropertyToID(_blurRef), + _blurCyclesId = Shader.PropertyToID(_blurCyclesRef), + _blurSamplesPerCycleId = Shader.PropertyToID(_blurSamplesPerCycleRef); private float _saturation, _hexagonDissolve, _hexagonTiles, _blur, _blurCycles, _blurSamplesPerCycle; private Color _tint = Color.gray; @@ -110,15 +116,6 @@ protected override void Awake() { base.Awake(); - // get ids from prop names - _saturationId = Shader.PropertyToID(_saturationRef); - _tintId = Shader.PropertyToID(_tintRef); - _hexagonDissolveId = Shader.PropertyToID(_hexagonDissolveRef); - _hexagonTilesId = Shader.PropertyToID(_hexagonTilesRef); - _blurId = Shader.PropertyToID(_blurRef); - _blurCyclesId = Shader.PropertyToID(_blurCyclesRef); - _blurSamplesPerCycleId = Shader.PropertyToID(_blurSamplesPerCycleRef); - // initialize values with the material's values var mat = Graphic.material; _saturation = mat.GetFloat(_saturationId); diff --git a/Packages/com.unity.shadergraph/Samples~/UITKShaders/Examples/Backgrounds/BlurredHexagon.shader b/Packages/com.unity.shadergraph/Samples~/UITKShaders/Examples/Backgrounds/BlurredHexagon.shader index 83d9fc1ee14..d644b38d330 100644 --- a/Packages/com.unity.shadergraph/Samples~/UITKShaders/Examples/Backgrounds/BlurredHexagon.shader +++ b/Packages/com.unity.shadergraph/Samples~/UITKShaders/Examples/Backgrounds/BlurredHexagon.shader @@ -33,7 +33,6 @@ Shader "Unlit/UITKShaders/BlurredHexagon" CGPROGRAM #pragma vertex vert #pragma fragment frag - #pragma multi_compile _ _UIE_OUTPUT_LINEAR #include "UnityCG.cginc" #include "UnityUIEFilter.cginc" @@ -180,9 +179,8 @@ Shader "Unlit/UITKShaders/BlurredHexagon" half4 sharp = tex2D(_MainTex, i.uv); col = lerp(col, sharp, border * saturate(_BorderOpacity)); - #if _UIE_OUTPUT_LINEAR - col.rgb = GammaToLinearSpace(col.rgb); - #endif + if (UIEFilterOutputsLinear()) + col.rgb = GammaToLinearSpace(col.rgb); return col; } diff --git a/Packages/com.unity.shadergraph/Samples~/UITKShaders/Examples/Backgrounds/Pixelation.shader b/Packages/com.unity.shadergraph/Samples~/UITKShaders/Examples/Backgrounds/Pixelation.shader index 8f209963bb7..de750391667 100644 --- a/Packages/com.unity.shadergraph/Samples~/UITKShaders/Examples/Backgrounds/Pixelation.shader +++ b/Packages/com.unity.shadergraph/Samples~/UITKShaders/Examples/Backgrounds/Pixelation.shader @@ -22,7 +22,6 @@ Shader "Unlit/UITKShaders/Pixelation" CGPROGRAM #pragma vertex vert #pragma fragment frag - #pragma multi_compile _ _UIE_OUTPUT_LINEAR #include "UnityCG.cginc" #include "UnityUIEFilter.cginc" @@ -81,9 +80,8 @@ Shader "Unlit/UITKShaders/Pixelation" half4 col = tex2D(_MainTex, uv); // Force-gamma workflow: the last filter pass must output linear. - #if _UIE_OUTPUT_LINEAR - col.rgb = GammaToLinearSpace(col.rgb); - #endif + if (UIEFilterOutputsLinear()) + col.rgb = GammaToLinearSpace(col.rgb); return col; } diff --git a/Packages/com.unity.shadergraph/Tests/Editor/ProviderTests/ProviderNodeCharacterizationTests.cs b/Packages/com.unity.shadergraph/Tests/Editor/ProviderTests/ProviderNodeCharacterizationTests.cs index 666a9a4cc2b..aa8fa9f654d 100644 --- a/Packages/com.unity.shadergraph/Tests/Editor/ProviderTests/ProviderNodeCharacterizationTests.cs +++ b/Packages/com.unity.shadergraph/Tests/Editor/ProviderTests/ProviderNodeCharacterizationTests.cs @@ -6,6 +6,7 @@ using System.Text.RegularExpressions; using NUnit.Framework; using Unity.GraphAuthoring.Editor.ProviderSystem; +using Unity.GraphAuthoring.Editor.ProviderSystem.Reflection; using UnityEditor.ShaderApiReflection; using UnityEngine; @@ -20,15 +21,15 @@ class ProviderNodeCharacterizationTests sealed class SourceProvider : IProvider { - public string ProviderKey { get; } + public ProviderInfo Info { get; } public IShaderFunction Definition { get; } public IReadOnlyList Messages { get; } internal SourceProvider(string providerKey, ReflectedFunction source) { - ProviderKey = providerKey; + Info = new ProviderInfo(providerKey); List messages = new(); - Definition = ShaderReflectionUtils.ToShaderFunction(source, default, null, messages, out _); + Definition = ShaderReflectionUtils.ToShaderFunction(source, default, messages, out _); Messages = messages; } @@ -210,8 +211,8 @@ static string Snapshot(string caseName) sb.Append("slot ").Append(SlotLine(slot)).Append('\n'); List messages = new(); - foreach (var (subject, message, severity) in node.Header.messages) - messages.Add($"{subject ?? "function"} {severity}: {message}"); + foreach (var message in node.messages) + messages.Add($"{message.subject ?? "function"} {message.severity}: {message.text}"); messages.Sort(StringComparer.Ordinal); foreach (var message in messages) sb.Append("message ").Append(message).Append('\n'); diff --git a/Packages/com.unity.shadergraph/Tests/Editor/ProviderTests/ProviderNodeGroupTests.cs b/Packages/com.unity.shadergraph/Tests/Editor/ProviderTests/ProviderNodeGroupTests.cs index 4609bf6ce32..9b75ef963e5 100644 --- a/Packages/com.unity.shadergraph/Tests/Editor/ProviderTests/ProviderNodeGroupTests.cs +++ b/Packages/com.unity.shadergraph/Tests/Editor/ProviderTests/ProviderNodeGroupTests.cs @@ -44,7 +44,7 @@ static ProviderNode NodeFor(string providerKey, string version = null) Assert.IsTrue(ProviderLibrary.TryGetInstance(out var lib), "Provider library must be available in the main editor."); foreach (var provider in lib.ProvidersByVersion(providerKey)) { - if (version != null && provider.Version != version) + if (version != null && provider.Info.Version != version) continue; var node = new ProviderNode(); new GraphData().AddNode(node); @@ -62,7 +62,7 @@ static string Snapshot(ProviderNode node) var header = node.Header; List candidates = new(); foreach (var (provider, label) in header.groupCandidates ?? new (IProvider, string)[0]) - candidates.Add($"{provider.ProviderKey}={label}"); + candidates.Add($"{provider.Info.ProviderKey}={label}"); List versions = new(); foreach (var (provider, version) in header.versionCandidates ?? new (IProvider, string)[0]) versions.Add($"{provider.Definition.Name}={version}"); diff --git a/Packages/com.unity.shadergraph/Tests/Editor/ProviderTests/ProviderNodeTests.cs b/Packages/com.unity.shadergraph/Tests/Editor/ProviderTests/ProviderNodeTests.cs new file mode 100644 index 00000000000..19531917898 --- /dev/null +++ b/Packages/com.unity.shadergraph/Tests/Editor/ProviderTests/ProviderNodeTests.cs @@ -0,0 +1,131 @@ +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework; +using Unity.GraphAuthoring.Editor.ProviderSystem; +using UnityEditor.Graphing; +using UnityEditor.Graphing.Util; +using UnityEditor.Rendering.BuiltIn.ShaderGraph; +using UnityEngine; + +namespace UnityEditor.ShaderGraph.ProviderSystem.Tests +{ + [TestFixture] + class ProviderNodeTests + { + sealed class ParameterMessageProvider : IProvider + { + public ProviderInfo Info => new("ParameterMessage"); + public IShaderFunction Definition { get; } = new ShaderFunction("Func", null, new IShaderField[] { new ShaderField("a", true, false, new ShaderType("float")) }, new ShaderType("float"), "return a;"); + public IReadOnlyList Messages { get; } = new[] { new Message("Is ignored.", MessageSeverity.Warning, "a") }; + public IProvider Clone() => this; + } + + static ProviderNode MissingNode() + { + var node = new ProviderNode(); + node.InitializeFromProvider(new ReflectedFunctionProvider(GUID.Generate(), "Missing")); + return node; + } + + static GraphData BuiltInGraph() + { + var graph = new GraphData { messageManager = new MessageManager() }; + graph.AddContexts(); + graph.InitializeOutputs(new Target[] { new BuiltInTarget() }, new[] { BlockFields.SurfaceDescription.BaseColor }); + return graph; + } + + // Keeps the output it had when its source last loaded. + static ProviderNode MissingNodeWithAnOutput(GraphData graph) + { + var node = MissingNode(); + node.AddSlot(new Vector3MaterialSlot(1, "Out", "Out", SlotType.Output, Vector3.zero)); + graph.AddNode(node); + return node; + } + + static bool ImportFails(GraphData graph) + { + new Generator(graph, null, GenerationMode.ForReals, "Test"); + return graph.messageManager.HasSeverity(id => graph.GetNodeFromId(id)?.wasUsedByGenerator ?? false, Rendering.ShaderCompilerMessageSeverity.Error); + } + + [Test] + public void ProviderNode_WhoseSourceIsMissing_IsAnOrphanLikeAnyProviderNode() + { + var graph = new GraphData { messageManager = new MessageManager() }; + var node = MissingNode(); + + graph.AddNode(node); + + Assert.IsTrue(node.isOrphaned); + StringAssert.Contains("'Missing'", node.messages.Single().text); + Assert.AreEqual(MessageType.Error, node.messages.Single().severity); + Assert.AreEqual("Setup: " + node.messages.Single().text, graph.messageManager.ErrorStrings(id => id == node.objectId).Single()); + } + + [Test] + public void ProviderNode_WhoseSourceIsMissing_StaysInactive_InAGraphWhoseTargetAllowsIt() + { + var graph = new GraphData(); + graph.AddContexts(); + graph.InitializeOutputs(new Target[] { new BuiltInTarget() }, null); + var node = MissingNode(); + + graph.AddNode(node); + + Assert.IsTrue(node.isOrphaned); + Assert.IsFalse(node.isActive); + } + + [Test] + public void ProviderNode_WhoseSourceIsMissing_FailsTheImport_WhenItFeedsTheOutput() + { + var graph = BuiltInGraph(); + var node = MissingNodeWithAnOutput(graph); + var baseColor = graph.GetNodes().Single(b => b.descriptor == BlockFields.SurfaceDescription.BaseColor); + graph.Connect(node.GetSlotReference(1), baseColor.GetSlotReference(0)); + + Assert.IsTrue(ImportFails(graph)); + Assert.IsTrue(node.wasUsedByGenerator); + } + + [Test] + public void ProviderNode_WhoseSourceIsMissing_DoesNotFailTheImport_WhenItFeedsNothing() + { + var graph = BuiltInGraph(); + var node = MissingNodeWithAnOutput(graph); + + Assert.IsFalse(ImportFails(graph)); + Assert.IsFalse(node.wasUsedByGenerator); + } + + [Test] + public void ProviderNodes_WhoseSourcesAreMissing_InALongChain_DoNotFailTheImport_WhenTheyFeedNothing() + { + var graph = BuiltInGraph(); + var previous = MissingNodeWithAnOutput(graph); + for (int i = 0; i < 40; ++i) + { + var node = MissingNodeWithAnOutput(graph); + node.AddSlot(new Vector3MaterialSlot(0, "In", "In", SlotType.Input, Vector3.zero)); + graph.Connect(previous.GetSlotReference(1), node.GetSlotReference(0)); + previous = node; + } + + Assert.IsFalse(ImportFails(graph)); + } + + [Test] + public void ProviderNode_ReportsAParametersMessage_WithTheParametersName() + { + var graph = new GraphData { messageManager = new MessageManager() }; + var node = new ProviderNode(); + node.InitializeFromProvider(new ParameterMessageProvider()); + + graph.AddNode(node); + + CollectionAssert.Contains(graph.messageManager.ErrorStrings(id => id == node.objectId, Rendering.ShaderCompilerMessageSeverity.Warning), "Validation: 'a': Is ignored."); + } + } +} diff --git a/Packages/com.unity.shadergraph/Tests/Editor/ProviderTests/ProviderNodeTests.cs.meta b/Packages/com.unity.shadergraph/Tests/Editor/ProviderTests/ProviderNodeTests.cs.meta new file mode 100644 index 00000000000..cf6104e6f9c --- /dev/null +++ b/Packages/com.unity.shadergraph/Tests/Editor/ProviderTests/ProviderNodeTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: d777ab1a930304f3791624442b6687b2 \ No newline at end of file diff --git a/Packages/com.unity.shadergraph/Tests/Editor/ProviderTests/ReflectedFunctionTests.cs b/Packages/com.unity.shadergraph/Tests/Editor/ProviderTests/ReflectedFunctionTests.cs index bbc6b2c6392..31cd65ff2b4 100644 --- a/Packages/com.unity.shadergraph/Tests/Editor/ProviderTests/ReflectedFunctionTests.cs +++ b/Packages/com.unity.shadergraph/Tests/Editor/ProviderTests/ReflectedFunctionTests.cs @@ -1,6 +1,9 @@ using System.Collections.Generic; +using System.Linq; using NUnit.Framework; using Unity.GraphAuthoring.Editor.ProviderSystem; +using UnityEditor.Graphing; +using UnityEditor.ShaderGraph.Serialization; namespace UnityEditor.ShaderGraph.ProviderSystem.Tests { @@ -69,6 +72,25 @@ public void ExternalParameter_KeepsItsProviderAcrossReload() Assert.AreEqual("ExternalNamespace::ExternalStruct", ShaderObjectUtils.QualifyName(new List(provider.Definition.Parameters)[0].ShaderType)); } + [Test] + public void ProviderNode_AfterLoading_ReadsItsDefinitionFromItsSource() + { + Assert.IsTrue(ProviderLibrary.TryGetInstance(out var lib), "Provider library must be available in the main editor."); + Assert.IsTrue(lib.TryGet("UniqueProviderName", out var provider)); + var graph = new GraphData(); + var node = new ProviderNode(); + node.InitializeFromProvider(provider); + graph.AddNode(node); + + var loaded = new GraphData(); + MultiJson.Deserialize(loaded, MultiJson.Serialize(graph)); + + var restored = loaded.GetNodes().Single(); + Assert.IsFalse(restored.isOrphaned); + Assert.AreEqual("ProviderName", restored.Provider.Definition.Name); + Assert.AreEqual(node.GetSlots().Count(), restored.GetSlots().Count()); + } + [Test] public void ReflectionTest() { diff --git a/Packages/com.unity.shadergraph/Tests/Editor/ProviderTests/ShaderInterfaceModeTests.cs b/Packages/com.unity.shadergraph/Tests/Editor/ProviderTests/ShaderInterfaceModeTests.cs index 8237e713716..9e4e8ac4d3b 100644 --- a/Packages/com.unity.shadergraph/Tests/Editor/ProviderTests/ShaderInterfaceModeTests.cs +++ b/Packages/com.unity.shadergraph/Tests/Editor/ProviderTests/ShaderInterfaceModeTests.cs @@ -13,7 +13,33 @@ namespace UnityEditor.ShaderGraph.ProviderSystem.Tests [TestFixture] class ShaderInterfaceModeTests { - static readonly GUID k_InterfaceAsset = new("0123456789abcdef0123456789abcdef"); + const string kInterfacePath = "Assets/ShaderInterfaceModeTests.shader"; + const string kInterfaceName = "Hidden/Tests/ShaderInterfaceModeTests"; + + const string kInterfaceSource = @" +ShaderInterface ""Hidden/Tests/ShaderInterfaceModeTests"" +{ + SubShader + { + Pass + { + Name ""Forward"" + Public + { + UNITY_VIRTUAL half3 GetColor() { return 1; } + } + Private + { + #pragma vertex Vert + #pragma fragment Frag + float4 Vert(float4 positionOS : POSITION0) : SV_POSITION0 { return positionOS; } + float4 Frag() : SV_TARGET0 { return float4(GetColor(), 1); } + } + } + } +}"; + + static GUID InterfaceAsset => AssetDatabase.GUIDFromAssetPath(kInterfacePath); System.Func m_PreviousInternalMode; @@ -28,13 +54,17 @@ public void EnableInternalMode() public void RestoreInternalMode() { GraphData.isInternalMode = m_PreviousInternalMode; + AssetDatabase.DeleteAsset(kInterfacePath); } static GraphData InterfaceGraph() { var graph = new GraphData { isShaderInterfaceMode = true }; - var definition = new ShaderInterface("Lit", default, null, null, null, null); - graph.SetShaderInterface(new ShaderInterfaceProvider(k_InterfaceAsset, definition)); + File.WriteAllText(kInterfacePath, kInterfaceSource); + AssetDatabase.ImportAsset(kInterfacePath, ImportAssetOptions.ForceSynchronousImport | ImportAssetOptions.ForceUpdate); + IProvider provider = new ShaderInterfaceProvider(InterfaceAsset, kInterfaceName); + Assume.That(provider.IsValid); + graph.SetShaderInterface(provider); return graph; } @@ -56,8 +86,23 @@ public void ModeAndInterface_SurviveSerialization() MultiJson.Deserialize(loaded, json); Assert.IsTrue(loaded.isShaderInterfaceMode); - Assert.AreEqual("Lit", loaded.shaderInterface.ProviderKey); - Assert.AreEqual(k_InterfaceAsset, loaded.shaderInterface.AssetID); + Assert.AreEqual(kInterfaceName, loaded.shaderInterface.Info.ProviderKey); + Assert.AreEqual(InterfaceAsset, loaded.shaderInterface.AssetID); + } + + [Test] + public void LocalProviderState_SurvivesSerialization() + { + var graph = InterfaceGraph(); + var function = (VirtualFunctionProvider)((ShaderInterfaceProvider)graph.shaderInterface).VirtualFunctionProviders.Single(p => p.Definition.Name == "GetColor"); + function.EnsureBaseCall = false; + + var loaded = new GraphData(); + MultiJson.Deserialize(loaded, MultiJson.Serialize(graph)); + + var restored = ((ShaderInterfaceProvider)loaded.shaderInterface).VirtualFunctionProviders.Single(p => p.Definition.Name == "GetColor"); + Assert.AreNotSame(function, restored); + Assert.IsFalse(restored.Definition.EnsureBaseCall); } [Test] @@ -70,7 +115,7 @@ public void SelectedInterface_IsADependencyOfTheGraph() var dependencies = new AssetCollection(); Assert.IsTrue(MinimalGraphData.GatherMinimalDependenciesFromFile(path, dependencies)); - Assert.IsTrue(dependencies.assets.TryGetValue(k_InterfaceAsset, out var flags)); + Assert.IsTrue(dependencies.assets.TryGetValue(InterfaceAsset, out var flags)); Assert.IsTrue(flags.HasFlag(AssetCollection.Flags.SourceDependency)); } finally @@ -134,7 +179,7 @@ public void ReplacingAGraph_CopiesTheModeAndTheInterface() live.ReplaceWith(source); Assert.IsTrue(live.isShaderInterfaceMode); - Assert.AreEqual(k_InterfaceAsset, live.shaderInterface.AssetID); + Assert.AreEqual(InterfaceAsset, live.shaderInterface.AssetID); } [Test] @@ -166,10 +211,12 @@ public void Settings_WithAMissingInterface_Warn() { // Loaded from disk, the interface has to be found again; this one's source doesn't exist. var loaded = new GraphData(); - MultiJson.Deserialize(loaded, MultiJson.Serialize(InterfaceGraph())); + var json = MultiJson.Serialize(InterfaceGraph()); + AssetDatabase.DeleteAsset(kInterfacePath); + MultiJson.Deserialize(loaded, json); var settings = new ShaderInterfaceSettings(loaded); - Assert.AreEqual("Lit", PickerText(settings)); + Assert.AreEqual(kInterfaceName, PickerText(settings), "Without its source, the interface is shown by its saved name."); Assert.IsNotNull(settings.Q()); Assert.AreEqual(1, settings.Query