This commit is contained in:
2026-11-24 15:51:02 +01:00
parent cca4d73e41
commit f4aa17114a
22092 changed files with 5042406 additions and 0 deletions
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: de07e00acee5049188d7f5c776e98c91
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 72ad64d64e3d29449bb230deb5349fb2
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,352 @@
using System;
using System.Collections.Generic;
using System.Text;
using UnityEditor.Rendering.Converter;
using UnityEngine;
using UnityEngine.Categorization;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
using static UnityEditor.Rendering.AnimationClipUpgrader;
using ClipPath = UnityEditor.Rendering.AnimationClipUpgrader.ClipPath;
namespace UnityEditor.Rendering.Universal
{
/// <summary>
/// Represents an animation clip asset that needs to be converted from Built-in RP to URP.
/// Tracks the animation clip and all its dependent assets (materials, prefabs, etc.).
/// </summary>
[Serializable]
internal class AnimationClipConverterItem : RenderPipelineConverterAssetItem
{
public AnimationClipConverterItem(GlobalObjectId gid, string assetPath)
: base(gid, assetPath)
{
info = assetPath;
}
/// <summary>
/// List of assets that reference this animation clip (e.g., prefabs, scene GameObjects).
/// Used to determine if the clip can be safely upgraded based on its usage context.
/// </summary>
[SerializeReference]
public List<RenderPipelineConverterAssetItem> dependencies = new();
}
/// <summary>
/// Converts animation clips that animate material properties from Built-in RP to URP.
/// Updates property paths in animation clips to match the new URP shader properties,
/// ensuring animations continue to work after material conversion.
/// </summary>
[Serializable]
[URPHelpURL("urp/features/rp-converter")]
[PipelineConverter("Built-in", "Universal Render Pipeline (Universal Renderer)")]
[BatchModeConverterClassInfo("BuiltInToURP", "AnimationClip")]
[ElementInfo(Name = "Animation Clip",
Order = 110,
Description = "Updates animation clips that reference material properties to work with URP shaders.\nEnsures material animations continue working after converting Materials from Built-in RP to URP.")]
internal sealed class AnimationClipConverter : IRenderPipelineConverter
{
public bool isEnabled
{
get
{
if (GraphicsSettings.currentRenderPipeline is not UniversalRenderPipelineAsset urpAsset)
return false;
return urpAsset.scriptableRenderer is UniversalRenderer;
}
}
public string isDisabledMessage => "Converter requires URP with an Universal Renderer. Convert your project to URP to use this converter.";
[SerializeField]
internal List<AnimationClipConverterItem> assets = new();
/// <summary>
/// Builds a list of animation clips that animate material properties and their search queries.
/// Each entry contains a search query to find assets referencing the clip, and the clip's path.
/// </summary>
/// <returns>List of tuples containing search queries and animation clip paths.</returns>
public static List<(string animationClip, string searchQuery)> GetAnimationClipsSearchList()
{
List<(string materialName, string searchQuery)> list = new();
// Find all animation clips in the project
foreach (var animationClip in AssetDatabaseHelper.FindAssets<AnimationClip>())
{
// Only include clips that animate material properties (e.g., color, float values)
if (!AnimationClipUpgrader.IsAnimatingMaterialProperties(animationClip))
continue;
// Create a search query using the GlobalObjectId to find all assets referencing this clip
string formattedId = $"<$object:{GlobalObjectId.GetGlobalObjectIdSlow(animationClip)},UnityEngine.Object$>";
list.Add(($"p: ref={formattedId}", AssetDatabase.GetAssetPath(animationClip)));
}
return list;
}
/// <summary>
/// Scans the project for animation clips that need conversion and identifies their dependencies.
/// </summary>
/// <param name="onScanFinish">Callback invoked with the list of items to convert when scanning completes.</param>
public void Scan(Action<List<IRenderPipelineConverterItem>> onScanFinish)
{
assets.Clear();
AnimationClipConverterItem currentAnimationClipItem = null;
void OnSearchFinish()
{
// Create a defensive copy to avoid exposing the internal mutable collection
var results = new List<IRenderPipelineConverterItem>(assets.Count);
foreach (var asset in assets)
{
if (asset.dependencies.Count == 0)
continue;
results.Add(asset);
}
onScanFinish?.Invoke(results);
}
using (UnityEngine.Pool.DictionaryPool<string, HashSet<AnimationClipConverterItem>>.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
);
}
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<AnimationClip>(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
);
}
}
/// <summary>
/// Cache of material upgrade paths from Built-in shaders to URP shaders.
/// Used to determine how animated material properties should be remapped.
/// </summary>
internal AnimationClipUpgradePathsCache m_UpgradePathsToNewShaders;
/// <summary>
/// Prepares the converter by loading all material upgrade paths.
/// Called once before converting any animation clips.
/// </summary>
public void BeforeConvert()
{
m_UpgradePathsToNewShaders = new (BuiltInToURP3DMaterialUpgrader.FetchMaterialUpgraders());
}
/// <summary>
/// Cleans up resources after conversion completes.
/// </summary>
public void AfterConvert()
{
m_UpgradePathsToNewShaders.Dispose();
m_UpgradePathsToNewShaders = null;
}
/// <summary>
/// Converts a single animation clip item by upgrading its material property paths.
/// </summary>
/// <param name="item">The animation clip item to convert.</param>
/// <param name="message">Output message describing the conversion result or any errors.</param>
/// <returns>Status indicating success or failure of the conversion.</returns>
public Status Convert(IRenderPipelineConverterItem item, out string message)
{
var assetItem = item as AnimationClipConverterItem;
var animationClip = assetItem.LoadObject() as AnimationClip;
if (animationClip == null)
{
message = $"Failed to load {assetItem.name} - Asset Path {assetItem.assetPath}";
return Status.Error;
}
var errorString = new StringBuilder();
var status = ConvertObject(animationClip, assetItem.dependencies, errorString);
message = errorString.ToString();
return status;
}
/// <summary>
/// Performs the actual conversion of an animation clip by analyzing its usage context
/// and upgrading material property paths where safe to do so.
/// </summary>
/// <param name="clip">The animation clip to convert.</param>
/// <param name="dependencies">List of assets that reference this clip (prefabs, GameObjects, etc.).</param>
/// <param name="message">Output message builder for logging results and errors.</param>
/// <returns>Status indicating success or failure of the conversion.</returns>
Status ConvertObject(AnimationClip clip, List<RenderPipelineConverterAssetItem> dependencies, StringBuilder message)
{
var status = Status.Success;
try
{
var clipPaths = new ClipPath[] { clip };
// Extract material property animation data from the clip
var clipData = AnimationClipUpgrader.GetAssetDataForClipsFiltered(clipPaths);
if (clipData.Count == 0)
{
message.AppendLine($"The given animation clip ({clip}) does not have material bindings");
return Status.Error;
}
using (UnityEngine.Pool.ListPool<GameObject>.Get(out var tmpGameObjects))
{
// Analyze how the clip is used across different GameObjects/prefabs to determine
// if it can be safely upgraded. A clip used with both upgraded and non-upgraded
// materials cannot be converted without breaking one of those use cases.
//
// Dependencies include:
// - Prefabs that use this animation clip
// - GameObjects in scenes that use this clip
// - Scene assets (skipped as GameObjects provide sufficient context)
foreach (var d in dependencies)
{
if (d.LoadObject() is GameObject go)
GatherClipsUsageForGameObject(go, clipData, m_UpgradePathsToNewShaders, default);
}
// Track which clips were successfully upgraded and which could not be converted
var upgraded = new HashSet<(IAnimationClip Clip, ClipPath Path, ShaderPropertyUsage Usage)>();
var notUpgraded = new HashSet<(IAnimationClip Clip, ClipPath Path, ShaderPropertyUsage Usage)>();
// Perform the upgrade, filtering out clips with ambiguous usage
UpgradeClips(clipData, upgraded, notUpgraded);
// Generate result message based on upgrade outcome
if (upgraded.Count == 1)
{
status = Status.Success;
bool setDirty = true;
foreach (var item in upgraded)
{
var (Clip, Path, Usage) = item;
if (Usage.HasFlag(ShaderPropertyUsage.InvalidShader))
{
message.Append("Unable to migrate Animation Clip");
message.AppendLine("- There is not converter defined for the target shader, or the target shader must be upgraded before.");
status = Status.Warning;
setDirty = false;
}
}
if (setDirty)
EditorUtility.SetDirty(clip);
}
else if (notUpgraded.Count == 1)
{
status = Status.Warning;
// Provide detailed information about why the clip couldn't be upgraded
foreach (var item in notUpgraded)
{
var (Clip, Path, Usage) = item;
message.AppendLine("Unable to migrate Animation Clip:");
if (Usage.HasFlag(ShaderPropertyUsage.InvalidShader))
{
message.AppendLine("- There is not converter defined for the target shader, or the target shader must be upgraded before.");
status = Status.Warning;
}
if (Usage.HasFlag(ShaderPropertyUsage.MultipleUpgradePaths))
{
message.Append("- The upgraders define multiple upgrade paths for one of the properties");
status = Status.Error;
}
}
}
}
}
catch (Exception ex)
{
message.AppendLine($"Error converting {clip}: {ex.Message}");
}
return status;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1f1277c79080f894d826683283a48ecf
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,167 @@
using System;
using System.Collections;
using System.Collections.Generic;
namespace UnityEditor.Rendering.Universal
{
[Flags]
enum ShaderPropertyUsage : byte
{
None = 0,
InvalidShader = 1 << 0,
NoMapping = 1 << 1,
ValidForUpgrade = 1 << 2,
MultipleUpgradePaths = 1 << 3,
AlreadyUpgraded = 1 << 4,
HasIssues = InvalidShader | NoMapping | MultipleUpgradePaths,
CanProcess = ValidForUpgrade | AlreadyUpgraded,
}
class AnimationClipUpgradePathsCache : IDisposable
{
class Cache : IDisposable
{
public class Entry
{
public List<MaterialUpgrader> upgraders = new();
public class Mapping
{
public Dictionary<string, string> mapping = new();
public HashSet<string> mappingsWithInvalidUpgradePaths = new();
public void Add(string from, string to)
{
if (mapping.TryGetValue(from, out var value))
{
if (value != to)
mappingsWithInvalidUpgradePaths.Add(from);
}
mapping[from] = to;
}
public ShaderPropertyUsage Get(string propertyName, out string newPropertyName)
{
if (!mapping.TryGetValue(propertyName, out newPropertyName))
{
newPropertyName = propertyName;
foreach (var kvp in mapping)
{
if (propertyName.Equals(kvp.Value))
return ShaderPropertyUsage.AlreadyUpgraded;
}
return ShaderPropertyUsage.NoMapping;
}
if (mappingsWithInvalidUpgradePaths.Contains(propertyName))
return ShaderPropertyUsage.MultipleUpgradePaths;
return ShaderPropertyUsage.ValidForUpgrade;
}
}
public List<Mapping> mappings = new List<Mapping>((int)MaterialUpgrader.MaterialPropertyType.Count);
Array m_EnumValues;
IEnumerator m_Enumerator;
public Entry()
{
m_EnumValues = Enum.GetValues(typeof(MaterialUpgrader.MaterialPropertyType));
m_Enumerator = m_EnumValues.GetEnumerator();
for (int m = 0; m < (int)MaterialUpgrader.MaterialPropertyType.Count; ++m)
{
mappings.Add(new Mapping());
}
}
public void Add(MaterialUpgrader upgrader)
{
upgraders.Add(upgrader);
m_Enumerator.Reset();
for (int m = 0; m < (int)MaterialUpgrader.MaterialPropertyType.Count; ++m)
{
m_Enumerator.MoveNext();
var mapping = mappings[(int)m];
foreach (var propertyRename in upgrader.GetPropertyRenameMap((MaterialUpgrader.MaterialPropertyType)m_Enumerator.Current))
{
mapping.Add(propertyRename.Key, propertyRename.Value);
}
}
}
public ShaderPropertyUsage Get(MaterialUpgrader.MaterialPropertyType type, string propertyName, out string newPropertyName)
{
var mapping = mappings[(int)type];
return mapping.Get(propertyName, out newPropertyName);
}
}
Dictionary<string, Entry> m_Dictionary = new();
public void Add(MaterialUpgrader upgrader)
{
if (!m_Dictionary.TryGetValue(upgrader.NewShaderPath, out var entry))
{
entry = new();
m_Dictionary[upgrader.NewShaderPath] = entry;
}
entry.Add(upgrader);
}
public bool TryGetEntry(string shaderName, out Entry entry)
{
entry = null;
if (string.IsNullOrEmpty(shaderName))
return false;
return m_Dictionary.TryGetValue(shaderName, out entry);
}
public void Dispose()
{
m_Dictionary.Clear();
}
}
Cache m_Cache = new ();
public AnimationClipUpgradePathsCache(List<MaterialUpgrader> upgraders)
{
BuildUpgradeCache(upgraders);
}
private void BuildUpgradeCache(List<MaterialUpgrader> upgraders)
{
foreach (var upgrader in upgraders)
{
m_Cache.Add(upgrader);
}
}
public ShaderPropertyUsage GetShaderPropertyUsage(string shaderName, MaterialUpgrader.MaterialPropertyType propertyType, string propertyName, out string newPropertyName)
{
newPropertyName = propertyName;
if (!m_Cache.TryGetEntry(shaderName, out var entry))
{
return ShaderPropertyUsage.InvalidShader;
}
return entry.Get(propertyType, propertyName, out newPropertyName);
}
public void Dispose()
{
m_Cache.Dispose();
}
}
}
@@ -0,0 +1,572 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEditor.Animations;
using UnityEditor.Rendering.Universal;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.Rendering;
using UnityEngine.UIElements;
using static UnityEditor.Rendering.AnimationClipUpgrader;
using static UnityEditor.Rendering.Universal.AnimationClipConverter;
using IMaterial = UnityEditor.Rendering.UpgradeUtility.IMaterial;
using UID = UnityEditor.Rendering.UpgradeUtility.UID;
namespace UnityEditor.Rendering
{
/// <summary>
/// A class containing static methods for updating <see cref="AnimationClip"/> assets with bindings for <see cref="Material"/> properties.
/// </summary>
/// <remarks>
/// Animation clips store bindings for material properties by path name, but don't know whether those properties exist on their dependents.
/// Because property names did not change uniformly in the material/shader upgrade process, it is not possible to patch path names indiscriminately.
/// This class provides utilities for discovering how clips are used, so users can make decisions about whether or not to then update them.
/// It has the limitation that it only knows about:
/// - Clips that are directly referenced by an <see cref="Animation"/> component
/// - Clips referenced by an <see cref="AnimatorController"/> used by an <see cref="Animator"/> component
/// - Clips that are sub-assets of a <see cref="PlayableAsset"/> used by a <see cref="PlayableDirector"/> component with a single <see cref="Animator"/> binding
/// It does not know about clips that might be referenced in other ways for run-time reassignment.
/// The utility can also provide faster, more reliable results if it knows what <see cref="MaterialUpgrader"/> was used to upgrade specific materials.
/// </remarks>
static partial class AnimationClipUpgrader
{
static readonly Regex k_MatchMaterialPropertyName = new Regex(@"material.(\w+)(\.\w+)?", RegexOptions.Compiled);
public static bool IsAnimatingMaterialProperties(AnimationClip animationClip)
{
var curveBindings = AnimationUtility.GetCurveBindings(animationClip);
if (curveBindings.Length == 0)
return false;
foreach (var curveBinding in curveBindings)
{
if (AnimationClipUpgrader.IsMaterialBinding(curveBinding))
return true;
}
return false;
}
/// <summary>
/// Determines whether the specified<see cref="EditorCurveBinding"/> is for a material property.
/// </summary>
/// <remarks>Internal only for testability.</remarks>
/// <param name="b">An <see cref="EditorCurveBinding"/>.</param>
/// <returns><c>true</c> if the binding is for a material property; <c>false</c> otherwise.</returns>
internal static bool IsMaterialBinding(EditorCurveBinding b)
{
if (b == null)
return false;
if (b.type == null || !b.type.IsSubclassOf(typeof(Renderer)))
return false;
if (string.IsNullOrEmpty(b.propertyName) || !k_MatchMaterialPropertyName.IsMatch(b.propertyName))
return false;
return true;
}
/// <summary>
/// Gets asset data for all clip assets at the specified paths, which contain bindings for material properties.
/// (See also <seealso cref="GatherClipsUsageInDependentPrefabs"/> and <seealso cref="GatherClipsUsageInDependentScenes"/>.)
/// </summary>
/// <param name="clipPaths">Paths to assets containing <see cref="AnimationClip"/>.</param>
/// <returns>
/// Lookup table mapping <see cref="AnimationClip"/> to its asset path, bindings, property rename table, and usage.
/// (Use <see cref="GatherClipsUsageInDependentPrefabs"/> to initialize rename table and usage.)
/// </returns>
internal static IDictionary<
IAnimationClip,
(ClipPath Path, EditorCurveBinding[] Bindings, ShaderPropertyUsage Usage, IDictionary<EditorCurveBinding, string> PropertyRenames)
> GetAssetDataForClipsFiltered(
IEnumerable<ClipPath> clipPaths
)
{
var result = new Dictionary<
IAnimationClip,
(ClipPath Path, EditorCurveBinding[] Bindings, ShaderPropertyUsage Usage, IDictionary<EditorCurveBinding, string> PropertyRenames)
>();
foreach (var clipPath in clipPaths)
{
foreach (var asset in AssetDatabase.LoadAllAssetsAtPath(clipPath))
{
if (!(asset is AnimationClip clip))
continue;
var bindings = AnimationUtility.GetCurveBindings(clip);
if (bindings.Length == 0)
continue;
using (UnityEngine.Pool.ListPool<EditorCurveBinding>.Get(out var tmp))
{
foreach (var b in bindings)
{
if (IsMaterialBinding(b))
tmp.Add(b);
}
if (tmp.Count != 0)
{
result[(AnimationClipProxy)clip] = (clipPath, tmp.ToArray(), ShaderPropertyUsage.None, new Dictionary<EditorCurveBinding, string>());
}
}
}
}
return result;
}
/// <summary>
/// Get dependency mappings between <see cref="AnimationClip"/> and their dependents.
/// </summary>
/// <param name="clips"> Paths to clips to consider. (See also <seealso cref="GetAssetDataForClipsFiltered"/>.)</param>
/// <param name="assets">Paths to assets to consider.</param>
/// <param name="clipToDependentAssets">Mapping of clip paths to paths of their dependents.</param>
/// <param name="assetToClipDependencies">Mapping of asset paths to their clip dependencies.</param>
/// <typeparam name="T">The type of asset path.</typeparam>
internal static void GetClipDependencyMappings<T>(
IEnumerable<ClipPath> clips,
IEnumerable<T> assets,
out IReadOnlyDictionary<ClipPath, IReadOnlyCollection<T>> clipToDependentAssets,
out IReadOnlyDictionary<T, IReadOnlyCollection<ClipPath>> assetToClipDependencies
) where T : struct, IAssetPath
{
// ensure there are no duplicate keys
clips = new HashSet<ClipPath>(clips);
assets = new HashSet<T>(assets);
// create mutable builders
var clipsDependentsBuilder = clips.ToDictionary(c => c, c => new HashSet<T>());
var assetsBuilder = new Dictionary<T, HashSet<ClipPath>>();
// build dependency tables
foreach (var asset in assets)
{
assetsBuilder[asset] = new HashSet<ClipPath>();
foreach (var dependencyPath in AssetDatabase.GetDependencies(asset.Path))
{
if (!clipsDependentsBuilder.TryGetValue(dependencyPath, out var dependents))
continue;
dependents.Add(asset);
assetsBuilder[asset].Add(dependencyPath);
}
}
// return readonly results
clipToDependentAssets =
clipsDependentsBuilder.ToDictionary(kv => kv.Key, kv => kv.Value as IReadOnlyCollection<T>);
assetToClipDependencies =
assetsBuilder.ToDictionary(kv => kv.Key, kv => kv.Value as IReadOnlyCollection<ClipPath>);
}
// reusable buffers
static readonly List<Animation> s_AnimationBuffer = new List<Animation>(8);
static readonly List<Animator> s_AnimatorBuffer = new List<Animator>(8);
static readonly List<IAnimationClipSource> s_CustomAnimationBuffer = new List<IAnimationClipSource>(8);
static readonly List<PlayableDirector> s_PlayableDirectorBuffer = new List<PlayableDirector>(8);
/// <summary>
/// Get information about a clip's usage among its dependent scenes to determine whether or not it should be upgraded.
/// </summary>
/// <param name="clipDependents">
/// A table mapping clip asset paths, to asset paths of their dependent prefabs.
/// (See <seealso cref="GetClipDependencyMappings{T}"/>.)
/// </param>
/// <param name="assetDependencies">
/// A table mapping prefab asset paths, to asset paths of their clip dependencies.
/// (See <seealso cref="GetClipDependencyMappings{T}"/>.)
/// </param>
/// <param name="clipData">
/// A table mapping clips to other data about them. (See also <seealso cref="GetAssetDataForClipsFiltered"/>.)
/// </param>
/// <param name="allUpgradePathsToNewShaders">
/// A table of new shader names and all known upgrade paths to them in the target pipeline.
/// (See also <seealso cref="UpgradeUtility.GetAllUpgradePathsToShaders"/>.)
/// </param>
/// <param name="upgradePathsUsedByMaterials">
/// Optional table of materials known to have gone through a specific upgrade path.
/// </param>
/// <param name="progressFunctor">
/// Optional functor to display a progress bar.
/// </param>
internal static void GatherClipsUsageInDependentPrefabs(
IReadOnlyDictionary<ClipPath, IReadOnlyCollection<PrefabPath>> clipDependents,
// TODO: right now, clip dependencies are gathered in Animation/Animator, so this may not be needed...
IReadOnlyDictionary<PrefabPath, IReadOnlyCollection<ClipPath>> assetDependencies,
IDictionary<
IAnimationClip,
(ClipPath Path, EditorCurveBinding[] Bindings, ShaderPropertyUsage Usage, IDictionary<EditorCurveBinding, string> PropertyRenames)
> clipData,
AnimationClipUpgradePathsCache allUpgradePathsToNewShaders,
IReadOnlyDictionary<UID, MaterialUpgrader> upgradePathsUsedByMaterials = default,
Func<string, float, bool> progressFunctor = null
)
{
int clipIndex = 0;
int totalNumberOfClips = clipDependents.Count;
// check all dependents for usage
foreach (var kv in clipDependents)
{
float currentProgress = (float)++clipIndex / totalNumberOfClips;
if (progressFunctor != null && progressFunctor($"({clipIndex} of {totalNumberOfClips}) {kv.Key.Path}", currentProgress))
break;
foreach (var prefabPath in kv.Value)
{
var go = AssetDatabase.LoadAssetAtPath<GameObject>(prefabPath);
GatherClipsUsageForGameObject(go, clipData, allUpgradePathsToNewShaders, upgradePathsUsedByMaterials);
}
}
}
/// <summary>
/// Get information about a clip's usage among its dependent scenes to determine whether or not it should be upgraded.
/// </summary>
/// <remarks>
/// Because this method will open scenes to search for usages, it is recommended you first prompt for user input.
/// It is also a good idea to first call <see cref="GatherClipsUsageInDependentPrefabs"/> to generate usage data.
/// Clips that are already known to be unsafe for upgrading based on their prefab usage can be skipped here.
/// </remarks>
/// <param name="clipDependents">
/// A table mapping clip asset paths, to asset paths of their dependent scenes.
/// (See <seealso cref="GetClipDependencyMappings{T}"/>.)
/// </param>
/// <param name="assetDependencies">
/// A table mapping scene asset paths, to asset paths of their clip dependencies.
/// (See <seealso cref="GetClipDependencyMappings{T}"/>.)
/// </param>
/// <param name="clipData">
/// A table mapping clips to other data about them. (See also <seealso cref="GetAssetDataForClipsFiltered"/>.)
/// </param>
/// <param name="allUpgradePathsToNewShaders">
/// A table of new shader names and all known upgrade paths to them in the target pipeline.
/// (See also <seealso cref="UpgradeUtility.GetAllUpgradePathsToShaders"/>.)
/// </param>
/// <param name="upgradePathsUsedByMaterials">
/// Optional table of materials known to have gone through a specific upgrade path.
/// </param>
/// <param name="progressFunctor">
/// Optional functor to display a progress bar.
/// </param>
internal static void GatherClipsUsageInDependentScenes(
IReadOnlyDictionary<ClipPath, IReadOnlyCollection<ScenePath>> clipDependents,
// TODO: right now, clip dependencies are gathered in Animation/Animator, so this may not be needed...
IReadOnlyDictionary<ScenePath, IReadOnlyCollection<ClipPath>> assetDependencies,
IDictionary<
IAnimationClip,
(ClipPath Path, EditorCurveBinding[] Bindings, ShaderPropertyUsage Usage, IDictionary<EditorCurveBinding, string>
PropertyRenames)
> clipData,
AnimationClipUpgradePathsCache allUpgradePathsToNewShaders,
IReadOnlyDictionary<UID, MaterialUpgrader> upgradePathsUsedByMaterials = default,
Func<string, float, bool> progressFunctor = null
)
{
int clipIndex = 0;
int totalNumberOfClips = clipDependents.Count;
// check all dependents for usage
foreach (var kv in clipDependents)
{
float currentProgress = (float)++clipIndex / totalNumberOfClips;
if (progressFunctor != null && progressFunctor($"({clipIndex} of {totalNumberOfClips}) {kv.Key.Path}", currentProgress))
break;
foreach (var scenePath in kv.Value)
{
var scene = EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Single);
foreach (var go in scene.GetRootGameObjects())
GatherClipsUsageForGameObject(go, clipData, allUpgradePathsToNewShaders, upgradePathsUsedByMaterials);
}
}
}
/// <summary>
/// Update usage information about the specified clips in the clip data table.
/// </summary>
/// <param name="go">A prefab, or a <see cref="GameObject"/> in a scene.</param>
/// <param name="clipData">
/// A table mapping clips to other data about them. (See also <seealso cref="GetAssetDataForClipsFiltered"/>.)
/// </param>
/// <param name="allUpgradePathsToNewShaders">
/// A table of new shader names and all known upgrade paths to them in the target pipeline.
/// (See also <seealso cref="UpgradeUtility.GetAllUpgradePathsToShaders"/>.)
/// </param>
/// <param name="upgradePathsUsedByMaterials">
/// Optional table of materials known to have gone through a specific upgrade path.
/// </param>
public static void GatherClipsUsageForGameObject(
GameObject go,
IDictionary<
IAnimationClip,
(ClipPath Path, EditorCurveBinding[] Bindings, ShaderPropertyUsage Usage, IDictionary<EditorCurveBinding, string> PropertyRenames)
> clipData,
AnimationClipUpgradePathsCache allUpgradePathsToNewShaders,
IReadOnlyDictionary<UID, MaterialUpgrader> upgradePathsUsedByMaterials = default
)
{
go.GetComponentsInChildren(true, s_AnimationBuffer);
go.GetComponentsInChildren(true, s_AnimatorBuffer);
go.GetComponentsInChildren(true, s_CustomAnimationBuffer);
// first check clip usage among GameObjects with legacy Animation
var gameObjects = new HashSet<GameObject>(s_AnimationBuffer.Select(a => a.gameObject)
.Union(s_AnimatorBuffer.Select(a => a.gameObject))
.Union(s_CustomAnimationBuffer.Where(a => a is Component).Select(a => ((Component)a).gameObject)));
foreach (var gameObject in gameObjects)
{
var clips = AnimationUtility.GetAnimationClips(gameObject).Select(clip => (IAnimationClip)(AnimationClipProxy)clip);
GatherClipsUsageForAnimatedHierarchy(
gameObject.transform, clips, clipData, allUpgradePathsToNewShaders, upgradePathsUsedByMaterials
);
}
// next check clip usage among GameObjects with PlayableDirector
go.GetComponentsInChildren(true, s_PlayableDirectorBuffer);
foreach (var playableDirector in s_PlayableDirectorBuffer)
{
var playableAsset = playableDirector.playableAsset;
if (playableAsset == null)
continue;
var assetPath = AssetDatabase.GetAssetPath(playableAsset);
// get all clip sub-assets
var clips = new HashSet<IAnimationClip>(
AssetDatabase.LoadAllAssetsAtPath(assetPath)
.Where(asset => asset is AnimationClip)
.Select(asset => (IAnimationClip)(AnimationClipProxy)(asset as AnimationClip))
);
// get all clip dependency-assets
// this will not handle nested clips in FBX like assets, but these are less likely to be editable
clips.UnionWith(AssetDatabase.GetDependencies(assetPath)
.Select(AssetDatabase.LoadAssetAtPath<AnimationClip>)
.Where(asset => asset is AnimationClip)
.Select(asset => (IAnimationClip)(AnimationClipProxy)asset));
// check if the value of a binding is an animator, and examines clip usage relative to it
// this is imprecise, but is suitable to catch the majority of cases (i.e., a single animator binding)
using (var so = new SerializedObject(playableDirector))
{
var clipsProp = so.FindProperty("m_SceneBindings");
for (int i = 0, count = clipsProp.arraySize; i < count; ++i)
{
var elementProp = clipsProp.GetArrayElementAtIndex(i);
var value = elementProp.FindPropertyRelative("value");
if (value.objectReferenceValue is Animator animator)
{
GatherClipsUsageForAnimatedHierarchy(
animator.transform, clips, clipData, allUpgradePathsToNewShaders, upgradePathsUsedByMaterials
);
}
}
}
}
// release UnityObject references
s_AnimationBuffer.Clear();
s_AnimatorBuffer.Clear();
s_CustomAnimationBuffer.Clear();
s_PlayableDirectorBuffer.Clear();
}
// reusable buffers
static readonly List<Renderer> s_RendererBuffer = new List<Renderer>(8);
static readonly Dictionary<string, (IRenderer Renderer, List<IMaterial> Materials)> s_RenderersByPath =
new Dictionary<string, (IRenderer Renderer, List<IMaterial> Materials)>();
/// <summary>
/// Update usage information about the specified clips in the clip data table.
/// </summary>
/// <param name="root">The root of the animated hierarchy (i.e., object with Animation or Animator).</param>
/// <param name="clips">Collection of animation clips</param>
/// <param name="clipData">
/// A table mapping clips to other data about them. (See also <seealso cref="GetAssetDataForClipsFiltered"/>.)
/// </param>
/// <param name="allUpgradePathsToNewShaders">
/// A table of new shader names and all known upgrade paths to them in the target pipeline.
/// (See also <seealso cref="UpgradeUtility.GetAllUpgradePathsToShaders"/>.)
/// </param>
/// <param name="upgradePathsUsedByMaterials">
/// Optional table of materials known to have gone through a specific upgrade path.
/// </param>
static void GatherClipsUsageForAnimatedHierarchy(
Transform root,
IEnumerable<IAnimationClip> clips,
IDictionary<
IAnimationClip,
(ClipPath Path, EditorCurveBinding[] Bindings, ShaderPropertyUsage Usage, IDictionary<EditorCurveBinding, string> PropertyRenames)
> clipData,
AnimationClipUpgradePathsCache allUpgradePathsToNewShaders,
IReadOnlyDictionary<UID, MaterialUpgrader> upgradePathsUsedByMaterials
)
{
// TODO: report paths of specific assets that contribute to problematic results?
// find all renderers in the animated hierarchy
root.GetComponentsInChildren(true, s_RendererBuffer);
foreach (var renderer in s_RendererBuffer)
{
var path = AnimationUtility.CalculateTransformPath(renderer.transform, root);
var m = ListPool<IMaterial>.Get();
var r = (RendererProxy)renderer;
r.GetSharedMaterials(m);
s_RenderersByPath[path] = (r, m);
}
// if there are any renderers, check all clips for usage
if (s_RendererBuffer.Count > 0)
{
foreach (var clip in clips)
GatherClipUsage(clip, clipData, s_RenderersByPath, allUpgradePathsToNewShaders, upgradePathsUsedByMaterials);
}
// release UnityObject references
s_RendererBuffer.Clear();
foreach (var (_, materials) in s_RenderersByPath.Values)
ListPool<IMaterial>.Release(materials);
s_RenderersByPath.Clear();
}
/// <summary>
/// Update usage information about the specified clip in the clip data table.
/// </summary>
/// <remarks>
/// This method works by looking at shaders used by materials assigned to the specified renderers.
/// Usage and property renames for the clip are updated, if a binding in the clip matches an upgrader.
/// Internal only for testability.
/// </remarks>
/// <param name="clip">An animation clip.</param>
/// <param name="clipData">
/// A table mapping clips to other data about them. (See also <seealso cref="GetAssetDataForClipsFiltered"/>.)
/// </param>
/// <param name="renderersByPath">
/// A table mapping transform paths of renderers to lists of the materials they use.
/// </param>
/// <param name="allUpgradePathsToNewShaders">
/// A table of new shader names and all known upgrade paths to them in the target pipeline.
/// (See also <seealso cref="UpgradeUtility.GetAllUpgradePathsToShaders"/>.)
/// </param>
/// <param name="upgradePathsUsedByMaterials">
/// Optional table of materials known to have gone through a specific upgrade path.
/// </param>
internal static void GatherClipUsage(
IAnimationClip clip,
IDictionary<
IAnimationClip,
(ClipPath Path, EditorCurveBinding[] Bindings, ShaderPropertyUsage Usage, IDictionary<EditorCurveBinding, string> PropertyRenames)
> clipData,
IReadOnlyDictionary<string, (IRenderer Renderer, List<IMaterial> Materials)> renderersByPath,
AnimationClipUpgradePathsCache allUpgradePathsToNewShaders,
IReadOnlyDictionary<UID, MaterialUpgrader> upgradePathsUsedByMaterials
)
{
// exit if clip is unknown; it may have been filtered at an earlier stage
if (!clipData.TryGetValue(clip, out var data))
return;
// see if any animated material bindings in the clip refer to renderers in animated hierarchy
foreach (var binding in data.Bindings)
{
// skip if binding is not for material, or refers to a nonexistent renderer
if (!IsMaterialBinding(binding) || !renderersByPath.TryGetValue(binding.path, out var rendererData))continue;
// determine the shader property name and type from the binding
(string shaderProperty, ShaderPropertyType type) = EditorCurveBindingUtils.InferShaderProperty(binding);
MaterialUpgrader.MaterialPropertyType materialPropertyType = MaterialUpgrader.MaterialPropertyType.Float;
if (type == ShaderPropertyType.Color)
materialPropertyType = MaterialUpgrader.MaterialPropertyType.Color;
else if (type == ShaderPropertyType.Texture)
materialPropertyType = MaterialUpgrader.MaterialPropertyType.Texture;
// material property animations apply to all materials, so check shader usage in all of them
foreach (var material in rendererData.Materials)
{
var usage = allUpgradePathsToNewShaders.GetShaderPropertyUsage(material.ShaderName, materialPropertyType, shaderProperty, out var newPropertyName);
// if the property has already been upgraded with a different name, mark the upgrade as ambiguous
if ( usage == ShaderPropertyUsage.ValidForUpgrade && data.PropertyRenames.TryGetValue(binding, out var propertyRename) && propertyRename != newPropertyName)
usage |= ShaderPropertyUsage.MultipleUpgradePaths;
data.Usage |= usage;
data.PropertyRenames[binding] = newPropertyName;
}
}
clipData[clip] = data;
}
/// <summary>
/// Upgrade the specified clips using the associated property rename table.
/// </summary>
/// <param name="clipsToUpgrade">
/// A table mapping clips to property renaming tables that can be safely applied to their bindings.
/// </param>
/// <param name="excludeFlags">Do not upgrade clips that have any of these flags set.</param>
/// <param name="upgraded">Collector for all clips that are upgraded.</param>
/// <param name="notUpgraded">Collector for all clips that are not upgraded.</param>
/// <param name="progressFunctor">Optional functor to display a progress bar.</param>
internal static void UpgradeClips(
IDictionary<IAnimationClip, (ClipPath Path, EditorCurveBinding[] Bindings, ShaderPropertyUsage Usage, IDictionary<EditorCurveBinding, string> PropertyRenames)> clipsToUpgrade,
HashSet<(IAnimationClip Clip, ClipPath Path, ShaderPropertyUsage Usage)> upgraded,
HashSet<(IAnimationClip Clip, ClipPath Path, ShaderPropertyUsage Usage)> notUpgraded,
Func<string, float, bool> progressFunctor = null
)
{
upgraded.Clear();
notUpgraded.Clear();
int clipIndex = 0;
int totalNumberOfClips = clipsToUpgrade.Count;
foreach (var kv in clipsToUpgrade)
{
float currentProgress = (float)++clipIndex / totalNumberOfClips;
if (progressFunctor != null && progressFunctor($"({clipIndex} of {totalNumberOfClips}) {kv.Value.Path.Path}", currentProgress))
break;
if (kv.Value.Usage == ShaderPropertyUsage.None || (kv.Value.Usage & ShaderPropertyUsage.HasIssues) != 0)
{
notUpgraded.Add((kv.Key, kv.Value.Path, kv.Value.Usage));
continue;
}
var renames = kv.Value.PropertyRenames;
using (UnityEngine.Pool.ListPool<EditorCurveBinding>.Get(out var oldBindingsTmp))
using (UnityEngine.Pool.ListPool<EditorCurveBinding>.Get(out var newBindingsTmp))
{
foreach (var binding in kv.Key.GetCurveBindings())
{
if (!IsMaterialBinding(binding))
continue;
if (renames.TryGetValue(binding, out var newName))
{
var (name, type) = EditorCurveBindingUtils.InferShaderProperty(binding);
oldBindingsTmp.Add(binding);
var newBinding = binding;
newBinding.propertyName = binding.propertyName.Replace(name, newName);
newBindingsTmp.Add(newBinding);
}
}
kv.Key.ReplaceBindings(oldBindingsTmp.ToArray(), newBindingsTmp.ToArray());
}
upgraded.Add((kv.Key, kv.Value.Path, kv.Value.Usage));
}
}
}
}
@@ -0,0 +1,108 @@
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Rendering;
using IMaterial = UnityEditor.Rendering.UpgradeUtility.IMaterial;
using MaterialProxy = UnityEditor.Rendering.UpgradeUtility.MaterialProxy;
namespace UnityEditor.Rendering
{
/// <summary>
/// Internal type definitions for <see cref="AnimationClipUpgrader"/>.
/// </summary>
/// <remarks>
/// This class contains two categories of internal types:
/// 1. Proxies for UnityObject assets (used for test mocking and facilitating usage without requiring loading all assets of the given type at once).
/// 2. Asset path wrappers (used for stronger typing and clarity in the API surface).
/// </remarks>
static partial class AnimationClipUpgrader
{
#region Proxies
internal interface IAnimationClip
{
AnimationClip Clip { get; }
EditorCurveBinding[] GetCurveBindings();
void ReplaceBindings(EditorCurveBinding[] oldBindings, EditorCurveBinding[] newBindings);
}
internal struct AnimationClipProxy : IAnimationClip
{
public AnimationClip Clip { get; set; }
public EditorCurveBinding[] GetCurveBindings() => AnimationUtility.GetCurveBindings(Clip);
public void ReplaceBindings(EditorCurveBinding[] oldBindings, EditorCurveBinding[] newBindings)
{
var curves = new AnimationCurve[oldBindings.Length];
for (int i = 0, count = oldBindings.Length; i < count; ++i)
curves[i] = AnimationUtility.GetEditorCurve(Clip, oldBindings[i]);
AnimationUtility.SetEditorCurves(Clip, oldBindings, new AnimationCurve[oldBindings.Length]);
AnimationUtility.SetEditorCurves(Clip, newBindings, curves);
}
public static implicit operator AnimationClip(AnimationClipProxy proxy) => proxy.Clip;
public static implicit operator AnimationClipProxy(AnimationClip clip) => new AnimationClipProxy { Clip = clip };
public override string ToString() => Clip.ToString();
}
internal interface IRenderer
{
}
internal struct RendererProxy : IRenderer
{
Renderer m_Renderer;
public void GetSharedMaterials(List<IMaterial> materials)
{
materials.Clear();
var m = ListPool<Material>.Get();
m_Renderer.GetSharedMaterials(m);
materials.AddRange(m.Select(mm => (MaterialProxy)mm).Cast<IMaterial>());
ListPool<Material>.Release(m);
}
public static implicit operator Renderer(RendererProxy proxy) => proxy.m_Renderer;
public static implicit operator RendererProxy(Renderer renderer) => new RendererProxy { m_Renderer = renderer };
public override string ToString() => m_Renderer.ToString();
}
#endregion
#region AssetPath Wrappers
internal interface IAssetPath
{
string Path { get; }
}
internal struct ClipPath : IAssetPath
{
public string Path { get; set; }
public static implicit operator string(ClipPath clip) => clip.Path;
public static implicit operator ClipPath(string path) => new ClipPath { Path = path };
public static implicit operator ClipPath(AnimationClip clip) => new ClipPath { Path = AssetDatabase.GetAssetPath(clip) };
public override string ToString() => Path;
}
internal struct PrefabPath : IAssetPath
{
public string Path { get; set; }
public static implicit operator string(PrefabPath prefab) => prefab.Path;
public static implicit operator PrefabPath(string path) => new PrefabPath { Path = path };
public static implicit operator PrefabPath(GameObject go) => new PrefabPath { Path = AssetDatabase.GetAssetPath(go) };
public override string ToString() => Path;
}
internal struct ScenePath : IAssetPath
{
public string Path { get; set; }
public static implicit operator string(ScenePath scene) => scene.Path;
public static implicit operator ScenePath(string path) => new ScenePath { Path = path };
public static implicit operator ScenePath(SceneAsset scene) => new ScenePath { Path = AssetDatabase.GetAssetPath(scene) };
public override string ToString() => Path;
}
#endregion
}
}
@@ -0,0 +1,83 @@
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine.Rendering;
namespace UnityEditor.Rendering.Universal
{
static class EditorCurveBindingUtils
{
private static readonly HashSet<string> k_ColorAttributeSuffixes = new HashSet<string>
{
"r", "g", "b", "a"
};
private static readonly HashSet<string> k_VectorAttributeSuffixes = new HashSet<string>
{
"x", "y", "z", "w"
};
// All known texture sub-property suffixes
private static readonly string[] k_TextureSubProperties = new[]
{
"_ST", // Scale and Tiling (Vector4: x=scaleX, y=scaleY, z=offsetX, w=offsetY)
"_TexelSize", // Texel size (Vector4: x=1/width, y=1/height, z=width, w=height)
"_HDR", // HDR decode values (Vector4)
"_Bump" // Bump map scale (usually Float, but can be part of texture property)
};
// Matches material property names in the format:
// "material._PropertyName" or "material._PropertyName.component"
// Examples: "material._Color.r", "material._MainTex_ST.x", "material._Metallic"
private static readonly Regex k_MatchMaterialPropertyName = new(@"^material\.([^.]+)(?:\.([rgba]|[xyzw]))?$", RegexOptions.Compiled);
internal static (string Name, ShaderPropertyType Type) InferShaderProperty(EditorCurveBinding binding)
{
var match = k_MatchMaterialPropertyName.Match(binding.propertyName);
if (!match.Success)
return (binding.propertyName, ShaderPropertyType.Float);
var propertyName = match.Groups[1].Value;
var componentSuffix = match.Groups[2].Value;
// Priority 1: Check for texture sub-properties
var (isTexture, textureName) = CheckForTextureProperty(propertyName, componentSuffix);
if (isTexture)
{
return (textureName, ShaderPropertyType.Texture);
}
// Priority 2: Check for color components (r, g, b, a)
if (k_ColorAttributeSuffixes.Contains(componentSuffix))
{
return (propertyName, ShaderPropertyType.Color);
}
// Priority 3: Default to float
return (propertyName, ShaderPropertyType.Float);
}
private static (bool isTexture, string baseName) CheckForTextureProperty(string propertyName, string componentSuffix)
{
// Check each texture sub-property suffix
foreach (var subProperty in k_TextureSubProperties)
{
// Case 1: Property name ends with the sub-property (e.g., "_MainTex_ST")
if (propertyName.EndsWith(subProperty))
{
var baseName = propertyName.Substring(0, propertyName.Length - subProperty.Length);
return (true, baseName);
}
// Case 2: Property contains sub-property and has vector component (e.g., "_MainTex_ST" with ".x")
int subPropertyIndex = propertyName.IndexOf(subProperty);
if (subPropertyIndex > 0 && k_VectorAttributeSuffixes.Contains(componentSuffix))
{
var baseName = propertyName.Substring(0, subPropertyIndex);
return (true, baseName);
}
}
return (false, propertyName);
}
}
}
@@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using UnityEditor.Rendering.Converter;
using UnityEngine.Categorization;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
[Serializable]
[PipelineConverter("Built-in", "Universal Render Pipeline (Universal Renderer)")]
[BatchModeConverterClassInfo("BuiltInToURP", "Material")]
[ElementInfo(Name = "Material Shader Converter",
Order = 100,
Description = "This converter scans all materials that reference Built-in shaders and upgrades them to use Universal Render Pipeline (URP) shaders.")]
internal sealed class BuiltInToURP3DMaterialUpgrader : RenderPipelineConverterMaterialUpgrader
{
public override bool isEnabled
{
get
{
if (GraphicsSettings.currentRenderPipeline is not UniversalRenderPipelineAsset urpAsset)
return false;
return urpAsset.scriptableRenderer is UniversalRenderer;
}
}
public override string isDisabledMessage => "Converter requires URP with a Universal Renderer. Convert your project to URP to use this converter.";
internal static List<MaterialUpgrader> FetchMaterialUpgraders()
{
var allURPUpgraders = MaterialUpgrader.FetchAllUpgradersForPipeline(typeof(UniversalRenderPipelineAsset));
var builtInToURPUpgraders = new List<MaterialUpgrader>();
foreach (var upgrader in allURPUpgraders)
{
if (upgrader is IBuiltInToURPMaterialUpgrader)
builtInToURPUpgraders.Add(upgrader);
}
return builtInToURPUpgraders;
}
protected override List<MaterialUpgrader> upgraders => FetchMaterialUpgraders();
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: b3c58a63bfb3ecb4d81289bf60b5b802
@@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
using UnityEditor.Rendering.Converter;
using UnityEngine;
using UnityEngine.Categorization;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
[Serializable]
[PipelineConverter("Built-in", "Universal Render Pipeline (Universal Renderer)")]
[BatchModeConverterClassInfo("BuiltInToURP", "ReadonlyMaterial")]
[ElementInfo(Name = "Material Reference Converter",
Order = 100,
Description = "Converts references to Built-In readonly materials to URP readonly materials.")]
internal class BuiltInToURP3DReadonlyMaterialConverter : ReadonlyMaterialConverter
{
public override bool isEnabled
{
get
{
if (GraphicsSettings.currentRenderPipeline is not UniversalRenderPipelineAsset urpAsset)
return false;
return urpAsset.scriptableRenderer is UniversalRenderer;
}
}
public override string isDisabledMessage => "Converter requires URP with an Universal Renderer. Convert your project to URP to use this converter.";
protected override Dictionary<string, Func<Material>> materialMappings
{
get
{
return new()
{
["Default-Diffuse"] = () => GraphicsSettings.GetRenderPipelineSettings<UniversalRenderPipelineEditorMaterials>().defaultMaterial,
["Default-Material"] = () => GraphicsSettings.GetRenderPipelineSettings<UniversalRenderPipelineEditorMaterials>().defaultMaterial,
["Default-ParticleSystem"] = () => GraphicsSettings.GetRenderPipelineSettings<UniversalRenderPipelineEditorMaterials>().defaultParticleUnlitMaterial,
["Default-Particle"] = () => GraphicsSettings.GetRenderPipelineSettings<UniversalRenderPipelineEditorMaterials>().defaultParticleUnlitMaterial,
["Default-Terrain-Diffuse"] = () => GraphicsSettings.GetRenderPipelineSettings<UniversalRenderPipelineEditorMaterials>().defaultTerrainLitMaterial,
["Default-Terrain-Specular"] = () => GraphicsSettings.GetRenderPipelineSettings<UniversalRenderPipelineEditorMaterials>().defaultTerrainLitMaterial,
["Default-Terrain-Standard"] = () => GraphicsSettings.GetRenderPipelineSettings<UniversalRenderPipelineEditorMaterials>().defaultTerrainLitMaterial,
["Sprites-Default"] = () => GraphicsSettings.GetRenderPipelineSettings<Renderer2DResources>().defaultLitMaterial,
["Sprites-Mask"] = () => GraphicsSettings.GetRenderPipelineSettings<Renderer2DResources>().defaultLitMaterial,
["SpatialMappingOcclusion"] = () => AssetDatabase.LoadAssetAtPath<Material>("Packages/com.unity.render-pipelines.universal/Runtime/Materials/SpatialMappingOcclusion.mat"),
["SpatialMappingWireframe"] = () => AssetDatabase.LoadAssetAtPath<Material>("Packages/com.unity.render-pipelines.universal/Runtime/Materials/SpatialMappingWireframe.mat"),
};
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 087c834eb72635d4f9bfedf7a58af4f6
@@ -0,0 +1,195 @@
using System;
using UnityEditor.Rendering.Converter;
using UnityEngine;
using UnityEngine.Categorization;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
using ShadowQuality = UnityEngine.ShadowQuality;
namespace UnityEditor.Rendering.Universal
{
[Serializable]
[URPHelpURL("urp/features/rp-converter")]
[PipelineConverter("Built-in", "Universal Render Pipeline (Universal Renderer)")]
[BatchModeConverterClassInfo("BuiltInToURP", "RenderSettings")]
[ElementInfo(Name = "Rendering Settings",
Order = int.MinValue,
Description = "This converter creates Universal Render Pipeline (URP) assets and corresponding Renderer assets, configuring their settings to match the equivalent settings from the Built-in Render Pipeline.")]
class BuiltInToURP3DRenderSettingsConverter : RenderSettingsConverter
{
public override bool isEnabled => true;
public override string isDisabledMessage => string.Empty;
protected override RenderPipelineAsset CreateAsset(string name)
{
string path = $"Assets/{UniversalProjectSettings.projectSettingsFolderPath}/{name}.asset";
if (AssetDatabase.AssetPathExists(path))
return AssetDatabase.LoadAssetAtPath<UniversalRenderPipelineAsset>(path);
try
{
CoreUtils.EnsureFolderTreeInAssetFilePath(path);
var asset = ScriptableObject.CreateInstance(typeof(UniversalRenderPipelineAsset)) as UniversalRenderPipelineAsset;
AssetDatabase.CreateAsset(asset, path);
AssetDatabase.SaveAssetIfDirty(asset);
return asset;
}
catch (Exception ex)
{
Debug.LogError($"Unable to create asset at path {path} with exception {ex.Message}");
return null;
}
}
UniversalRendererData CreateUniversalRendererDataAsset(RenderingPath renderingPath, RenderingMode renderingMode)
{
string path = $"Assets/{UniversalProjectSettings.projectSettingsFolderPath}/Default_{renderingMode}_Renderer.asset";
if (AssetDatabase.AssetPathExists(path))
return AssetDatabase.LoadAssetAtPath<UniversalRendererData>(path);
CoreUtils.EnsureFolderTreeInAssetFilePath(path);
var asset = UniversalRenderPipelineAsset.CreateRendererAsset(path, RendererType.UniversalRenderer, relativePath: false) as UniversalRendererData;
asset.renderingMode = renderingPath == RenderingPath.Forward ? RenderingMode.Forward : RenderingMode.Deferred;
EditorUtility.SetDirty(asset);
AssetDatabase.SaveAssetIfDirty(asset);
return asset;
}
void GetRenderers(out ScriptableRendererData[] renderers, out int defaultIndex)
{
defaultIndex = 0;
var targetGrp = BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget);
var tier = EditorGraphicsSettings.GetTierSettings(targetGrp, GraphicsTier.Tier3);
using (ListPool<ScriptableRendererData>.Get(out var tmp))
{
var renderingPath = tier.renderingPath;
var renderingMode = GetEquivalentRenderMode(renderingPath);
tmp.Add(CreateUniversalRendererDataAsset(renderingPath, renderingMode));
// In case we need multiple renderers modify the defaultIndex and add more renderers here
// ...
renderers = tmp.ToArray();
}
// Tell the asset database to regenerate the fileId, otherwise when adding the reference to the URP
// asset the fileId might not be computed and the reference might be lost.
AssetDatabase.Refresh();
}
protected override void SetPipelineSettings(RenderPipelineAsset asset)
{
if (asset is not UniversalRenderPipelineAsset urpAsset)
return;
GetRenderers(out var renderers, out var defaultIndex);
urpAsset.m_RendererDataList = renderers;
urpAsset.m_DefaultRendererIndex = defaultIndex;
var targetGrp = BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget);
var tier = EditorGraphicsSettings.GetTierSettings(targetGrp, GraphicsTier.Tier3);
var pixelLightCount = QualitySettings.pixelLightCount;
var shadows = QualitySettings.shadows;
var shadowResolution = QualitySettings.shadowResolution;
var shadowDistance = QualitySettings.shadowDistance;
var reflectionProbeBlending = tier.reflectionProbeBlending;
var reflectionProbeBoxProjection = tier.reflectionProbeBoxProjection;
bool cascadeShadows = tier.cascadedShadowMaps;
var shadowCascadeCount = QualitySettings.shadowCascades;
var cascadeSplit2 = QualitySettings.shadowCascade2Split;
var cascadeSplit4 = QualitySettings.shadowCascade4Split;
bool hdr = tier.hdr;
var msaa = QualitySettings.antiAliasing;
var softParticles = QualitySettings.softParticles;
// General
urpAsset.supportsCameraDepthTexture = softParticles;
// Quality
urpAsset.supportsHDR = hdr;
urpAsset.msaaSampleCount = msaa == 0 ? 1 : msaa;
// Main Light
urpAsset.mainLightRenderingMode = pixelLightCount == 0
? LightRenderingMode.Disabled
: LightRenderingMode.PerPixel;
urpAsset.supportsMainLightShadows = shadows != ShadowQuality.Disable;
urpAsset.mainLightShadowmapResolution =
GetEquivalentMainlightShadowResolution((int)shadowResolution);
// Additional Lights
urpAsset.additionalLightsRenderingMode = pixelLightCount == 0
? LightRenderingMode.PerVertex
: LightRenderingMode.PerPixel;
urpAsset.maxAdditionalLightsCount = pixelLightCount != 0 ? Mathf.Max(0, pixelLightCount) : 4;
urpAsset.supportsAdditionalLightShadows = shadows != ShadowQuality.Disable;
urpAsset.additionalLightsShadowmapResolution =
GetEquivalentAdditionalLightAtlasShadowResolution((int)shadowResolution);
// Reflection Probes
urpAsset.reflectionProbeBlending = reflectionProbeBlending;
urpAsset.reflectionProbeBoxProjection = reflectionProbeBoxProjection;
// Shadows
urpAsset.shadowDistance = shadowDistance;
urpAsset.shadowCascadeCount = cascadeShadows ? shadowCascadeCount : 1;
urpAsset.cascade2Split = cascadeSplit2;
urpAsset.cascade4Split = cascadeSplit4;
urpAsset.supportsSoftShadows = shadows == ShadowQuality.All;
}
#region HelperFunctions
internal static int GetEquivalentMainlightShadowResolution(int value)
{
return GetEquivalentShadowResolution(value);
}
internal static int GetEquivalentAdditionalLightAtlasShadowResolution(int value)
{
return GetEquivalentShadowResolution(value);
}
private static int GetEquivalentShadowResolution(int value)
{
switch (value)
{
case 0: // low
return 1024;
case 1: // med
return 2048;
case 2: // high
return 4096;
case 3: // very high
return 4096;
default: // backup
return 1024;
}
}
private RenderingMode GetEquivalentRenderMode(RenderingPath path)
{
switch (path)
{
case RenderingPath.VertexLit:
case RenderingPath.Forward:
return RenderingMode.Forward;
case RenderingPath.DeferredShading:
return RenderingMode.Deferred;
default:
return RenderingMode.Forward;
}
}
#endregion
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 932911033fe1e934bbc87b0e1d9dd74e
@@ -0,0 +1,348 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using UnityEditor.Rendering.Converter;
using UnityEngine;
using UnityEngine.Rendering;
namespace UnityEditor.Rendering.Universal
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
internal class BatchModeConverterClassInfo : Attribute
{
public string converterType { get; }
public string containerName { get; }
public BatchModeConverterClassInfo(string containerName, string converterType)
{
this.converterType = converterType;
this.containerName = containerName;
}
}
/// <summary>
/// Class for the converter framework.
/// </summary>
public static partial class Converters
{
// Commands
const string k_BatchmodeCommand = "-batchmode";
const string k_HelpCommand = "--help";
const string k_ListCommand = "--list";
const string k_ContainerCommand = "-container";
const string k_TypesFilterCommand = "-typesFilter";
const string k_InclusiveFlag = "--inclusive";
const string k_ExclusiveFlag = "--exclusive";
// List all available containers
static void ListAvailableConverters()
{
// Get all converters and group them by container
var containersDict = DictionaryPool<string,List<string>>.Get();
foreach (var container in TypeCache.GetTypesWithAttribute<BatchModeConverterClassInfo>())
{
if (container.IsAbstract || container.IsInterface)
continue;
var info = container.GetCustomAttribute<BatchModeConverterClassInfo>();
if (!containersDict.ContainsKey(info.containerName))
{
containersDict[info.containerName] = new List<string>();
}
containersDict[info.containerName].Add(info.converterType);
}
// Organize the information
StringBuilder convertersMessage = StringBuilderPool.Get();
foreach (var converter in containersDict)
{
convertersMessage.AppendLine($"Container: {converter.Key}");
convertersMessage.AppendLine("Available converter types:");
convertersMessage.AppendLine(String.Join($"\n\t- ", converter.Value));
convertersMessage.AppendLine("\n");
}
Debug.Log($"Available containers and their converter types\n{convertersMessage}");
}
static void LogHelp()
{
StringBuilder helpMessage = StringBuilderPool.Get();
// Description
helpMessage.AppendLine("\n");
helpMessage.AppendLine( "The batchmode converter is a tool to help you upgrade your projects from one scriptable render pipeline\n" +
"to another. Using this API can lead to incomplete or unpredictable conversion outcomes.\n" +
"For reliable results, please perform the conversion via the dedicated window: Window > Rendering > Render Pipeline Converter.");
helpMessage.AppendLine("\n");
// Usage
helpMessage.AppendLine($"usage: \t<path to Unity executable> -projectPath <project path> {k_BatchmodeCommand} -executeMethod UnityEditor.Rendering.Universal.Converters.RunInBatchModeCmdLine\n" +
$"\t \t[{k_HelpCommand}] [{k_ListCommand}]\n" +
$"\t \t[{k_ContainerCommand} <name of container>] [{k_TypesFilterCommand} <types to include or exclude>] [{k_InclusiveFlag}|{k_ExclusiveFlag}]");
helpMessage.AppendLine("\n");
// Commands
helpMessage.AppendLine("Commands");
helpMessage.AppendLine($"\t{k_HelpCommand} \t \t Show this help and exit.");
helpMessage.AppendLine($"\t{k_ListCommand} \t \t List all available converters and exit.");
helpMessage.AppendLine("\n");
// Options
helpMessage.AppendLine("Options");
helpMessage.AppendLine($"\t{k_ContainerCommand} <name of container> \t \t \t The name of the container which will be batched (required).");
helpMessage.AppendLine($"\t{k_TypesFilterCommand} <types to include or exclude> \t The list of converters types that will be either included or excluded from batching. These converters need to be part of the passed in container for them to run.");
helpMessage.AppendLine($"\t{k_InclusiveFlag}|{k_ExclusiveFlag} \t \t \t Whether the list of converters specified with {k_TypesFilterCommand} will be included or excluded when batching.");
helpMessage.AppendLine("\n");
helpMessage.AppendLine("Notes");
helpMessage.AppendLine($"\t Use either {k_InclusiveFlag} or {k_ExclusiveFlag}, not both.");
helpMessage.AppendLine($"\t When using {k_InclusiveFlag}, you must specify values for {k_TypesFilterCommand}.");
helpMessage.AppendLine($"\t Values for {k_TypesFilterCommand} must be provided as a space-separated list: {k_TypesFilterCommand} typeA typeB typeC");
helpMessage.AppendLine("\nOnline documentation: https://docs.unity3d.com/6000.5/Documentation/Manual/urp/convert-assets-to-urp.html\n");
Debug.Log(helpMessage);
}
internal static void SuggestUpdatedCommand(string container, List<string> converters, bool isInclusive)
{
var containerParameter = $" {k_ContainerCommand} {container}";
var converterParameter = converters.Count == 0 ? "" : $" {k_TypesFilterCommand} {string.Join(" ", converters)}";
var filterModeFlag = isInclusive ? $" {k_InclusiveFlag}" : $" {k_ExclusiveFlag}";
Debug.Log("The method you're trying to use is deprecated. Try running the following command in the command line:\n" +
$"<path to Unity> -projectPath <path to project> {k_BatchmodeCommand} -executeMethod UnityEditor.Rendering.Universal.Converters.RunInBatchModeCmdLine{filterModeFlag}{containerParameter}{converterParameter}");
}
// Return all converters we will be running
internal static List<Type> FilterConverters(string containerName, List<string> convertedTypesFilter, bool isInclusive = false)
{
var allConverters = TypeCache.GetTypesWithAttribute<BatchModeConverterClassInfo>();
var filteredList = new List<Type>(allConverters.Count);
// early return
if (isInclusive && convertedTypesFilter.Count == 0)
return filteredList; // nothing included in the list
foreach (var converterType in allConverters)
{
var converterInfo = converterType.GetCustomAttribute<BatchModeConverterClassInfo>();
if (containerName != converterInfo.containerName)
continue;
var isTypeInFilteredList = convertedTypesFilter.Contains(converterInfo.converterType);
// add if inclusive and in the included list, add if exclusive and not in the excluded list
if (isInclusive == isTypeInFilteredList)
filteredList.Add(converterType);
}
return filteredList;
}
internal static Dictionary<string, List<string>> ParseArgs(string[] rawArgs)
{
int batchmodeArgIndex = Array.FindIndex(rawArgs, arg => arg == k_BatchmodeCommand);
if (batchmodeArgIndex == -1)
throw new ArgumentException($"No {k_BatchmodeCommand} argument found. Exiting.");
var parsedArgs = DictionaryPool<string,List<string>>.Get();
parsedArgs["Flags"] = new List<string>();
string currentKey = null; // are we collecting values for a key?
for(int i = batchmodeArgIndex + 1; i < rawArgs.Length; i++)
{
if (rawArgs[i].StartsWith("--")) // new flag
{
parsedArgs["Flags"].Add(rawArgs[i]);
currentKey = "";
}
else if (rawArgs[i].StartsWith("-")) // new argument
{
parsedArgs.Add(rawArgs[i], new List<string>());
currentKey = rawArgs[i];
}
else // adding to the last argument
{
if (String.IsNullOrEmpty(currentKey))
{
throw new ArgumentException($"Unrecognized argument: {rawArgs[i]}");
}
parsedArgs[currentKey].Add(rawArgs[i]);
}
}
return parsedArgs;
}
/// <summary>
/// Call this method to run all the converters in a specific container in batch mode.
/// </summary>
/// <param name="containerName">The name of the container which will be batched. All Converters in this Container will run if prerequisites are met.</param>
public static void RunInBatchMode(string containerName)
{
RunInBatchMode(containerName, null, isInclusive: false);
}
/// <summary>
/// Call this method to run a specific list of converters in a specific container in batch mode.
/// </summary>
/// <param name="containerName">The name of the container which will be batched.</param>
/// <param name="convertedTypes">The list of converters that will be either included or excluded from batching. These converters need to be part of the passed in container for them to run.</param>
/// <param name="isInclusive">Whether the list of converters will be included or excluded when batching.</param>
public static void RunInBatchMode(string containerName, List<string> convertedTypes, bool isInclusive)
{
var types = FilterConverters(containerName, convertedTypes, isInclusive);
RunInBatchMode(types);
}
/// <summary>
/// Call this method to run a specific list of converters in a specific container in batch mode.
/// Entry point for: -executeMethod UnityEditor.Rendering.Universal.Converters.RunInBatchModeCmdLine
/// </summary>
public static void RunInBatchModeCmdLine()
{
Debug.Log("BATCH MODE COMMAND LINE\n");
var exitCode = 0;
try
{
var args = ParseArgs(Environment.GetCommandLineArgs());
// If help requested, print and exit
if (args["Flags"].Contains(k_HelpCommand))
{
LogHelp();
EditorApplication.Exit(0);
return;
}
if (args["Flags"].Contains(k_ListCommand))
{
ListAvailableConverters();
EditorApplication.Exit(0);
return;
}
// ContainerType -----
if (!args.TryGetValue(k_ContainerCommand, out var converter))
throw new ArgumentException($"Missing required {k_ContainerCommand} <name of container>. Use {k_ListCommand} to see available converter.");
if(converter.Count != 1)
throw new ArgumentException($"Please specify only one container. Use {k_ListCommand} to see available converters.");
// Filter + Include/Exclude ------
var hasInclusive = args["Flags"].Contains(k_InclusiveFlag);
var hasExclusive = args["Flags"].Contains(k_ExclusiveFlag);
var hasTypesFilter = args.TryGetValue(k_TypesFilterCommand, out var filteredTypes);
if (hasTypesFilter && hasExclusive == hasInclusive)
{
throw new ArgumentException($"When using {k_TypesFilterCommand}, please specify exactly one of {k_InclusiveFlag} or {k_ExclusiveFlag}. Use {k_HelpCommand} for usage.");
}
if (hasInclusive && !hasTypesFilter)
throw new ArgumentException($"When using {k_InclusiveFlag} mode, please specify types to include using {k_TypesFilterCommand} otherwise nothing will be converted. " +
$"Use {k_ListCommand} to see available types.");
RunInBatchMode(converter[0], filteredTypes, hasInclusive);
}
catch (Exception ex)
{
Debug.LogError($"ConverterCli failed: {ex.Message}\n{ex}");
exitCode = 1;
}
finally
{
EditorApplication.Exit(exitCode);
}
}
/// <summary>
/// Call this method to run a specific list of converters in batch mode.
/// </summary>
/// <param name="converterTypes">The list of converters to run</param>
/// <returns>False if there were errors.</returns>
internal static bool RunInBatchMode(List<Type> converterTypes)
{
Debug.LogWarning($"Using this API can lead to incomplete or unpredictable conversion outcomes. For reliable results, please perform the conversion via the dedicated window: Window > Rendering > Render Pipeline Converter.");
List<IRenderPipelineConverter> convertersToExecute = new();
bool errors = false;
foreach (var type in converterTypes)
{
try
{
var instance = Activator.CreateInstance(type) as IRenderPipelineConverter;
if (instance == null)
{
Debug.LogWarning($"{type} is not a converter type.");
errors = true;
}
else
convertersToExecute.Add(instance);
}
catch
{
Debug.LogWarning($"Unable to create instance of type {type}.");
errors = true;
}
}
if (errors)
{
Debug.LogWarning($"Please use any of the given Converter Types.");
ListAvailableConverters();
}
BatchConverters(convertersToExecute);
return !errors;
}
static void BatchConverters(List<IRenderPipelineConverter> converters)
{
foreach (var converter in converters)
{
var sb = StringBuilderPool.Get();
converter.Scan(OnConverterCompleteDataCollection);
void OnConverterCompleteDataCollection(List<IRenderPipelineConverterItem> items)
{
// Flatten folders to leaf items for batch conversion
var leafItems = new List<IRenderPipelineConverterItem>();
RenderPipelineConverterUtility.CollectLeafItems(items, leafItems);
converter.BeforeConvert();
foreach (var item in leafItems)
{
var status = converter.Convert(item, out var message);
switch (status)
{
case Status.Pending:
throw new InvalidOperationException("Converter returned a pending status when converting. This is not supported.");
case Status.Error:
case Status.Warning:
sb.AppendLine($"- {item.name} ({status}) ({message})");
break;
case Status.Success:
{
sb.AppendLine($"- {item.name} ({status})");
}
break;
}
}
converter.AfterConvert();
var conversionResult = sb.ToString();
if (!string.IsNullOrEmpty(conversionResult))
Debug.Log(sb.ToString());
}
}
AssetDatabase.SaveAssets();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 96e55a15cdc29c1439f077074b7d409d
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 3bea68cd70a3b17418ac142e2936b092
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 036db18d0922d53419a5d769fe345bec
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,42 @@
#if PPV2_EXISTS
using System;
using BIRPToURPConversionExtensions;
using UnityEditor;
using UnityEngine.Rendering;
using BIRPRendering = UnityEngine.Rendering.PostProcessing;
using URPRendering = UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
public class BloomConverter : PostProcessEffectSettingsConverter
{
#if PPV2_EXISTS
protected override Type OldSettingsType { get; } = typeof(BIRPRendering.Bloom);
protected override void ConvertToTarget(BIRPRendering.PostProcessEffectSettings oldSettings, VolumeProfile targetProfile)
{
var oldBloom = oldSettings as BIRPRendering.Bloom;
var newVolumeComponent = AddVolumeComponentToAsset<URPRendering.Bloom>(targetProfile);
newVolumeComponent.active = oldBloom.active;
oldBloom.clamp.Convert(newVolumeComponent.clamp);
oldBloom.diffusion.Convert(newVolumeComponent.scatter, scale: 0.05f);
oldBloom.intensity.Convert(newVolumeComponent.intensity, enabledState: oldBloom.enabled);
oldBloom.threshold.Convert(newVolumeComponent.threshold);
oldBloom.color.Convert(newVolumeComponent.tint);
oldBloom.dirtIntensity.Convert(newVolumeComponent.dirtIntensity);
oldBloom.dirtTexture.Convert(newVolumeComponent.dirtTexture);
oldBloom.fastMode.Convert(newVolumeComponent.highQualityFiltering, invertValue: true);
// TODO: No clear conversions for these?
// newVolumeComponent.skipIterations = oldBloom.???;
// newVolumeComponent.??? = oldBloom.anamorphicRatio;
// newVolumeComponent.??? = oldBloom.softKnee;
}
#endif
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 65de241854404d343a0937eb1adbb6f7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,34 @@
#if PPV2_EXISTS
using System;
using BIRPToURPConversionExtensions;
using UnityEditor;
using UnityEngine.Rendering;
using BIRPRendering = UnityEngine.Rendering.PostProcessing;
using URPRendering = UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
public class ChromaticAberrationConverter : PostProcessEffectSettingsConverter
{
protected override Type OldSettingsType { get; } = typeof(BIRPRendering.ChromaticAberration);
protected override void ConvertToTarget(BIRPRendering.PostProcessEffectSettings oldSettings,
VolumeProfile targetProfile)
{
var oldChromaticAberration = oldSettings as BIRPRendering.ChromaticAberration;
var newVolumeComponent = AddVolumeComponentToAsset<URPRendering.ChromaticAberration>(targetProfile);
newVolumeComponent.active = oldChromaticAberration.active;
// TODO: Verify that these are 1:1 conversions for visual parity
oldChromaticAberration.intensity.Convert(newVolumeComponent.intensity,
enabledState: oldChromaticAberration.enabled);
// TODO: No clear conversions for these?
// oldChromaticAberration.spectralLut
// oldChromaticAberration.fastMode
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ef31d99f657209a468edc1f49b350cb5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,130 @@
#if PPV2_EXISTS
using System;
using BIRPToURPConversionExtensions;
using UnityEngine;
using UnityEngine.Rendering;
using BIRPRendering = UnityEngine.Rendering.PostProcessing;
using URPRendering = UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
public class ColorGradingConverter : PostProcessEffectSettingsConverter
{
protected override Type OldSettingsType { get; } = typeof(BIRPRendering.ColorGrading);
protected override void ConvertToTarget(BIRPRendering.PostProcessEffectSettings oldSettings,
VolumeProfile targetProfile)
{
var oldColorGrading = oldSettings as BIRPRendering.ColorGrading;
var newTonemapping = AddVolumeComponentToAsset<URPRendering.Tonemapping>(targetProfile); // was: Tonemapping
var newWhiteBalance =
AddVolumeComponentToAsset<URPRendering.WhiteBalance>(targetProfile); // was: White Balance
var newColorAdjustments =
AddVolumeComponentToAsset<URPRendering.ColorAdjustments>(targetProfile); // was: Tone
var newTargetProfile =
AddVolumeComponentToAsset<URPRendering.ChannelMixer>(targetProfile); // was: Channel Mixer
var newLiftGammaGain =
AddVolumeComponentToAsset<URPRendering.LiftGammaGain>(targetProfile); // was: Trackballs
var newColorCurves =
AddVolumeComponentToAsset<URPRendering.ColorCurves>(targetProfile); // was: Grading Curves
// Tonemapping
newTonemapping.active = oldColorGrading.active;
ConvertTonemapper(oldColorGrading.tonemapper, newTonemapping.mode, oldColorGrading.enabled);
// White Balance
newWhiteBalance.active = oldColorGrading.active;
oldColorGrading.temperature.Convert(newWhiteBalance.temperature, enabledState: oldColorGrading.enabled);
oldColorGrading.tint.Convert(newWhiteBalance.tint, enabledState: oldColorGrading.enabled);
// Tone -> ColorAdjustments
newColorAdjustments.active = oldColorGrading.active;
oldColorGrading.postExposure.Convert(newColorAdjustments.postExposure,
enabledState: oldColorGrading.enabled);
oldColorGrading.colorFilter.Convert(newColorAdjustments.colorFilter, oldColorGrading.enabled,
disabledColor: Color.white);
oldColorGrading.hueShift.Convert(newColorAdjustments.hueShift, enabledState: oldColorGrading.enabled);
oldColorGrading.saturation.Convert(newColorAdjustments.saturation, enabledState: oldColorGrading.enabled);
oldColorGrading.contrast.Convert(newColorAdjustments.contrast, enabledState: oldColorGrading.enabled);
// Channel Mixer
newTargetProfile.active = oldColorGrading.active;
oldColorGrading.mixerRedOutRedIn.Convert(newTargetProfile.redOutRedIn,
enabledState: oldColorGrading.enabled);
oldColorGrading.mixerRedOutGreenIn.Convert(newTargetProfile.redOutGreenIn,
enabledState: oldColorGrading.enabled);
oldColorGrading.mixerRedOutBlueIn.Convert(newTargetProfile.redOutBlueIn,
enabledState: oldColorGrading.enabled);
oldColorGrading.mixerGreenOutRedIn.Convert(newTargetProfile.greenOutRedIn,
enabledState: oldColorGrading.enabled);
oldColorGrading.mixerGreenOutGreenIn.Convert(newTargetProfile.greenOutGreenIn,
enabledState: oldColorGrading.enabled);
oldColorGrading.mixerGreenOutBlueIn.Convert(newTargetProfile.greenOutBlueIn,
enabledState: oldColorGrading.enabled);
oldColorGrading.mixerBlueOutRedIn.Convert(newTargetProfile.blueOutRedIn,
enabledState: oldColorGrading.enabled);
oldColorGrading.mixerBlueOutGreenIn.Convert(newTargetProfile.blueOutGreenIn,
enabledState: oldColorGrading.enabled);
oldColorGrading.mixerBlueOutBlueIn.Convert(newTargetProfile.blueOutBlueIn,
enabledState: oldColorGrading.enabled);
// Trackballs -> LiftGammaGain
newLiftGammaGain.active = oldColorGrading.active;
// Note: URP always does color grading in HDR values (as it should),
// which means the non-HDR modes no longer have valid conversion targets.
// So, these values are left at defaults (neutral) when not previously using HDR.
if (oldColorGrading.gradingMode.value == BIRPRendering.GradingMode.HighDefinitionRange)
{
oldColorGrading.lift.Convert(newLiftGammaGain.lift, oldColorGrading.enabled);
oldColorGrading.gamma.Convert(newLiftGammaGain.gamma, oldColorGrading.enabled);
oldColorGrading.gain.Convert(newLiftGammaGain.gain, oldColorGrading.enabled);
}
// Grading Curves -> ColorCurves
newColorCurves.active = oldColorGrading.active;
oldColorGrading.masterCurve.Convert(newColorCurves.master, oldColorGrading.enabled);
oldColorGrading.redCurve.Convert(newColorCurves.red, oldColorGrading.enabled);
oldColorGrading.greenCurve.Convert(newColorCurves.green, oldColorGrading.enabled);
oldColorGrading.blueCurve.Convert(newColorCurves.blue, oldColorGrading.enabled);
oldColorGrading.hueVsHueCurve.Convert(newColorCurves.hueVsHue, oldColorGrading.enabled);
oldColorGrading.hueVsSatCurve.Convert(newColorCurves.hueVsSat, oldColorGrading.enabled);
oldColorGrading.satVsSatCurve.Convert(newColorCurves.satVsSat, oldColorGrading.enabled);
oldColorGrading.lumVsSatCurve.Convert(newColorCurves.lumVsSat, oldColorGrading.enabled);
}
private void ConvertTonemapper(BIRPRendering.TonemapperParameter birpSource,
URPRendering.TonemappingModeParameter target, bool enabledState)
{
if (target == null) return;
switch (birpSource.value)
{
case BIRPRendering.Tonemapper.Neutral:
target.value = URPRendering.TonemappingMode.Neutral;
break;
case BIRPRendering.Tonemapper.ACES:
target.value = URPRendering.TonemappingMode.ACES;
break;
default:
target.value = URPRendering.TonemappingMode.None;
break;
}
if (!enabledState)
{
target.value = URPRendering.TonemappingMode.None;
}
target.overrideState = birpSource.overrideState;
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c93687e52abd628448c8f7666b1dbd23
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,38 @@
#if PPV2_EXISTS
using System;
using BIRPToURPConversionExtensions;
using UnityEngine.Rendering;
using BIRPRendering = UnityEngine.Rendering.PostProcessing;
using URPRendering = UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
public class DepthOfFieldConverter : PostProcessEffectSettingsConverter
{
protected override Type OldSettingsType { get; } = typeof(BIRPRendering.DepthOfField);
protected override void ConvertToTarget(BIRPRendering.PostProcessEffectSettings oldSettings,
VolumeProfile targetProfile)
{
var oldDepthOfField = oldSettings as BIRPRendering.DepthOfField;
var newVolumeComponent = AddVolumeComponentToAsset<URPRendering.DepthOfField>(targetProfile);
newVolumeComponent.active = oldDepthOfField.active;
// Always use Bokeh mode, because it has parity with the PPv2 approach
newVolumeComponent.mode.value = oldDepthOfField.enabled
? URPRendering.DepthOfFieldMode.Bokeh
: URPRendering.DepthOfFieldMode.Off;
newVolumeComponent.mode.overrideState = true;
oldDepthOfField.focusDistance.Convert(newVolumeComponent.focusDistance, enabledState: oldSettings.enabled);
oldDepthOfField.focalLength.Convert(newVolumeComponent.focalLength, enabledState: oldSettings.enabled);
oldDepthOfField.aperture.Convert(newVolumeComponent.aperture, enabledState: oldSettings.enabled);
// TODO: No clear conversions for these?
// oldDepthOfField.kernelSize
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: aa79bbd82ff697846b2723bb624f5b5c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,42 @@
#if PPV2_EXISTS
using System;
using BIRPToURPConversionExtensions;
using UnityEditor;
using UnityEngine.Rendering;
using BIRPRendering = UnityEngine.Rendering.PostProcessing;
using URPRendering = UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
public class GrainConverter : PostProcessEffectSettingsConverter
{
protected override Type OldSettingsType { get; } = typeof(BIRPRendering.Grain);
protected override void ConvertToTarget(BIRPRendering.PostProcessEffectSettings oldSettings,
VolumeProfile targetProfile)
{
var oldGrain = oldSettings as BIRPRendering.Grain;
var newVolumeComponent = AddVolumeComponentToAsset<URPRendering.FilmGrain>(targetProfile);
newVolumeComponent.active = oldGrain.active;
oldGrain.intensity.Convert(newVolumeComponent.intensity, enabledState: oldGrain.enabled);
oldGrain.lumContrib.Convert(newVolumeComponent.response);
newVolumeComponent.type.overrideState = oldGrain.size.overrideState;
if (oldGrain.size.value > 1.5f)
newVolumeComponent.type.value = URPRendering.FilmGrainLookup.Medium3;
else if (oldGrain.size.value > 1.25f)
newVolumeComponent.type.value = URPRendering.FilmGrainLookup.Medium2;
else if (oldGrain.size.value > 0.7f)
newVolumeComponent.type.value = URPRendering.FilmGrainLookup.Thin2;
else
newVolumeComponent.type.value = URPRendering.FilmGrainLookup.Thin1;
// TODO: No clear conversions for these?
// oldGrain.colored
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: df39fb04691e914469d4b4ae2a027fb4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,39 @@
#if PPV2_EXISTS
using System;
using BIRPToURPConversionExtensions;
using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;
using BIRPRendering = UnityEngine.Rendering.PostProcessing;
using URPRendering = UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
public class LensDistortionConverter : PostProcessEffectSettingsConverter
{
protected override Type OldSettingsType { get; } = typeof(BIRPRendering.LensDistortion);
protected override void ConvertToTarget(BIRPRendering.PostProcessEffectSettings oldSettings,
VolumeProfile targetProfile)
{
var oldLensDistortion = oldSettings as BIRPRendering.LensDistortion;
var newVolumeComponent = AddVolumeComponentToAsset<URPRendering.LensDistortion>(targetProfile);
newVolumeComponent.active = oldLensDistortion.active;
oldLensDistortion.intensity.Convert(newVolumeComponent.intensity,
scale: 0.01f,
enabledState: oldLensDistortion.enabled);
oldLensDistortion.intensityX.Convert(newVolumeComponent.xMultiplier);
oldLensDistortion.intensityY.Convert(newVolumeComponent.yMultiplier);
oldLensDistortion.scale.Convert(newVolumeComponent.scale);
newVolumeComponent.center.overrideState =
oldLensDistortion.centerX.overrideState || oldLensDistortion.centerY.overrideState;
newVolumeComponent.center.value =
new Vector2(oldLensDistortion.centerX.value, oldLensDistortion.centerY.value);
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ef0ef98463379a649ba68d026c95ea4d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,37 @@
#if PPV2_EXISTS
using System;
using BIRPToURPConversionExtensions;
using UnityEditor;
using UnityEngine.Rendering;
using BIRPRendering = UnityEngine.Rendering.PostProcessing;
using URPRendering = UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
public class MotionBlurConverter : PostProcessEffectSettingsConverter
{
protected override Type OldSettingsType { get; } = typeof(BIRPRendering.MotionBlur);
protected override void ConvertToTarget(BIRPRendering.PostProcessEffectSettings oldSettings, VolumeProfile targetProfile)
{
var oldMotionBlur = oldSettings as BIRPRendering.MotionBlur;
var newVolumeComponent = AddVolumeComponentToAsset<URPRendering.MotionBlur>(targetProfile);
newVolumeComponent.active = oldMotionBlur.active;
// Note: These settings cannot provide visual parity,
// but this scale factor provides a good starting point.
oldMotionBlur.shutterAngle.Convert(newVolumeComponent.intensity, scale: 1f / 360f, oldMotionBlur.enabled);
newVolumeComponent.quality.overrideState = oldMotionBlur.sampleCount.overrideState;
if (oldMotionBlur.sampleCount >= 24)
newVolumeComponent.quality.value = URPRendering.MotionBlurQuality.High;
else if (oldMotionBlur.sampleCount > 12)
newVolumeComponent.quality.value = URPRendering.MotionBlurQuality.Medium;
else
newVolumeComponent.quality.value = URPRendering.MotionBlurQuality.Low;
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5d1c67b3de6d65a44b641566a9d529b4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,43 @@
#if PPV2_EXISTS
using System;
using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;
using BIRPRendering = UnityEngine.Rendering.PostProcessing;
using URPRendering = UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
public abstract class PostProcessEffectSettingsConverter : ScriptableObject
{
protected abstract Type OldSettingsType { get; }
public void AddConvertedProfileSettingsToProfile(
BIRPRendering.PostProcessEffectSettings oldSettings,
VolumeProfile targetProfile)
{
if (oldSettings == null || oldSettings.GetType() != OldSettingsType) return;
if (targetProfile == null || targetProfile.Has(OldSettingsType)) return;
ConvertToTarget(oldSettings, targetProfile);
}
protected abstract void ConvertToTarget(BIRPRendering.PostProcessEffectSettings oldBloom,
VolumeProfile targetProfile);
protected T AddVolumeComponentToAsset<T>(VolumeProfile targetProfileAsset) where T : VolumeComponent
{
if (!targetProfileAsset) return null;
var profilePath = AssetDatabase.GetAssetPath(targetProfileAsset);
if (string.IsNullOrEmpty(profilePath)) return null;
var newVolumeComponent = targetProfileAsset.Add<T>();
AssetDatabase.AddObjectToAsset(newVolumeComponent, targetProfileAsset);
return newVolumeComponent;
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: fce1ffd6e78acfd4aa944af71b8a07d9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,93 @@
#if PPV2_EXISTS
using System.Data;
using UnityEngine;
using UnityEngine.Rendering;
using BIRPRendering = UnityEngine.Rendering.PostProcessing;
namespace BIRPToURPConversionExtensions
{
public static class PropertyConversions
{
public static void Convert(this BIRPRendering.FloatParameter birpSource, FloatParameter target, float scale = 1f, bool enabledState = true)
{
if (target == null) return;
target.value = enabledState ? birpSource.value * scale : 0f;
target.overrideState = birpSource.overrideState;
}
public static void Convert(this BIRPRendering.FloatParameter birpSource, MinFloatParameter target, float scale = 1f, bool enabledState = true)
{
if (target == null) return;
target.value = enabledState ? birpSource.value * scale : 0f;
target.overrideState = birpSource.overrideState;
}
public static void Convert(this BIRPRendering.FloatParameter birpSource, ClampedFloatParameter target, float scale = 1f, bool enabledState = true)
{
if (target == null) return;
target.value = enabledState ? birpSource.value * scale : 0f;
target.overrideState = birpSource.overrideState;
}
public static void Convert(this BIRPRendering.Vector2Parameter birpSource, Vector2Parameter target)
{
if (target == null) return;
target.value = birpSource.value;
target.overrideState = birpSource.overrideState;
}
public static void Convert(this BIRPRendering.Vector4Parameter birpSource, Vector4Parameter target, bool enabledState = true)
{
if (target == null) return;
target.value = enabledState ? birpSource.value : new Vector4(1f, 1f, 1f, 0f);
target.overrideState = birpSource.overrideState;
}
public static void Convert(this BIRPRendering.ColorParameter birpSource, ColorParameter target, bool enabledState, Color disabledColor)
{
if (target == null) return;
target.value = enabledState ? birpSource.value : disabledColor;
target.overrideState = birpSource.overrideState;
}
public static void Convert(this BIRPRendering.ColorParameter birpSource, ColorParameter target)
{
if (target == null) return;
target.value = birpSource.value;
target.overrideState = birpSource.overrideState;
}
public static void Convert(this BIRPRendering.TextureParameter birpSource, TextureParameter target)
{
if (target == null) return;
target.value = birpSource.value;
target.overrideState = birpSource.overrideState;
}
public static void Convert(this BIRPRendering.BoolParameter birpSource, BoolParameter target, bool invertValue = false)
{
if (target == null) return;
target.value = invertValue ? !birpSource.value : birpSource.value;
target.overrideState = birpSource.overrideState;
}
public static void Convert(this BIRPRendering.SplineParameter birpSource, TextureCurveParameter target, bool enabledState = true)
{
if (target == null) return;
target.value = new TextureCurve(birpSource.value.curve, zeroValue: 0f, loop: false, Vector2.up);
target.overrideState = birpSource.overrideState;
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 55392cd2a34cb21499958e42eba26b2d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,47 @@
#if PPV2_EXISTS
using System;
using BIRPToURPConversionExtensions;
using UnityEngine.Rendering;
using BIRPRendering = UnityEngine.Rendering.PostProcessing;
using URPRendering = UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
public class VignetteConverter : PostProcessEffectSettingsConverter
{
protected override Type OldSettingsType { get; } = typeof(BIRPRendering.Vignette);
protected override void ConvertToTarget(BIRPRendering.PostProcessEffectSettings oldSettings,
VolumeProfile targetProfile)
{
var oldVignette = oldSettings as BIRPRendering.Vignette;
var newVolumeComponent = AddVolumeComponentToAsset<URPRendering.Vignette>(targetProfile);
newVolumeComponent.active = oldVignette.active;
oldVignette.color.Convert(newVolumeComponent.color);
if (oldVignette.mode.value == BIRPRendering.VignetteMode.Masked)
{
// There's not much we can do with the Masked mode at present,
// so we just assume the old opacity should be used as intensity,
// and leave all other settings at default values.
oldVignette.opacity.Convert(newVolumeComponent.intensity, enabledState: oldSettings.enabled);
}
else
{
oldVignette.intensity.Convert(newVolumeComponent.intensity, enabledState: oldSettings.enabled);
oldVignette.center.Convert(newVolumeComponent.center);
oldVignette.rounded.Convert(newVolumeComponent.rounded);
oldVignette.smoothness.Convert(newVolumeComponent.smoothness);
}
// TODO: No clear conversions for these?
// oldVignette.mask
// oldVignette.roundness
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: de573be7419f3b84295377f64cf664c7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,37 @@
#if PPV2_EXISTS
using UnityEditor.Search;
using UnityEngine;
using BIRPRendering = UnityEngine.Rendering.PostProcessing;
namespace UnityEditor.Rendering.Universal
{
static class PPv2ConversionIndexers
{
// Note: Iterating this version number does not force an index rebuild.
// If modifying this code, you will need to either delete the Library directory,
// or open "Window > Search > Index Manager" and right-click each indexer to do a Force Rebuild.
private const int Version = 10;
[CustomObjectIndexer(typeof(Object), version = Version)]
internal static void ConversionIndexer(CustomObjectIndexerTarget context, ObjectIndexer indexer)
{
// Note: Volumes and Layers on the same object would still produce only a
// single result in the "urp:convert-ppv2component" search, thus we only
// explicitly add one or the other here, instead of both.
if (context.targetType == typeof(BIRPRendering.PostProcessVolume))
{
indexer.AddProperty("urp", "convert-ppv2component", context.documentIndex);
}
else if (context.targetType == typeof(BIRPRendering.PostProcessLayer))
{
indexer.AddProperty("urp", "convert-ppv2component", context.documentIndex);
}
if (context.targetType == typeof(BIRPRendering.PostProcessProfile))
{
indexer.AddProperty("urp", "convert-ppv2scriptableobject", context.documentIndex);
}
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 89952a5e365cbf54699031f6ee002f48
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,498 @@
using System;
using System.Collections.Generic;
using System.Text;
using UnityEditor.Rendering.Converter;
using UnityEngine.Categorization;
using UnityEngine.Rendering.Universal;
#if PPV2_EXISTS
using UnityEngine;
using UnityEngine.Rendering;
using System.IO;
using System.Linq;
using System.Reflection;
using UnityEditor.SceneManagement;
using BIRPRendering = UnityEngine.Rendering.PostProcessing;
using UnityEngine.SceneManagement;
using Object = UnityEngine.Object;
using URPRendering = UnityEngine.Rendering.Universal;
#endif
namespace UnityEditor.Rendering.Universal
{
[URPHelpURL("urp/features/rp-converter")]
[Serializable]
[PipelineConverter("Built-in", "Universal Render Pipeline (Universal Renderer)")]
[BatchModeConverterClassInfo("BuiltInToURP", "PPv2")]
[ElementInfo(Name = "Post-Processing Stack v2",
Order = int.MaxValue,
Description = "This converter creates Universal Render Pipeline (URP) assets and corresponding Renderer assets, configuring their settings to match the equivalent settings from the Built-in Render Pipeline.")]
internal class PPv2Converter : AssetsConverter
{
#if PPV2_EXISTS
public override bool isEnabled => s_PostProcessTypesToSearch?.Count() > 0;
public override string isDisabledMessage => "Missing types to search";
private IEnumerable<PostProcessEffectSettingsConverter> effectConverters = null;
private List<Object> postConversionDestroyables = null;
protected override List<(string query, string description)> contextSearchQueriesAndIds
=> s_PostProcessTypesToSearch;
static List<(string, string)> s_PostProcessTypesToSearch = new()
{
("p: t:PostProcessVolume", "Contains Post Process Volume Component"),
("p: t:PostProcessLayer", "Contains Post Process Layer Component"),
("p: t:PostProcessProfile", "Contains Instance of Post Process Profile")
};
public override void BeforeConvert()
{
// Converters should already be set to null on domain reload,
// but we're doing it here just in case anything somehow lingers.
effectConverters = null;
postConversionDestroyables = new List<Object>();
}
protected override Status ConvertObject(UnityEngine.Object obj, StringBuilder message)
{
BIRPRendering.PostProcessVolume[] oldVolumes = null;
BIRPRendering.PostProcessLayer[] oldLayers = null;
// TODO: Upcoming changes to GlobalObjectIdentifierToObjectSlow will allow
// this to be inverted, and the else to be deleted.
#if false
if (obj is GameObject go)
{
oldVolumes = go.GetComponents<BIRPRendering.PostProcessVolume>();
oldLayers = go.GetComponents<BIRPRendering.PostProcessLayer>();
}
else if (obj is MonoBehaviour mb)
{
oldVolumes = mb.GetComponents<BIRPRendering.PostProcessVolume>();
oldLayers = mb.GetComponents<BIRPRendering.PostProcessLayer>();
}
#else
if (obj is GameObject go)
{
oldVolumes = go.GetComponentsInChildren<BIRPRendering.PostProcessVolume>();
oldLayers = go.GetComponentsInChildren<BIRPRendering.PostProcessLayer>();
}
else if (obj is MonoBehaviour mb)
{
oldVolumes = mb.GetComponentsInChildren<BIRPRendering.PostProcessVolume>();
oldLayers = mb.GetComponentsInChildren<BIRPRendering.PostProcessLayer>();
}
#endif
// Note: even if nothing needs to be converted, that should still count as success,
// though it shouldn't ever actually occur.
var succeeded = true;
if (effectConverters == null ||
effectConverters.Count() == 0 ||
effectConverters.Any(converter => converter == null))
{
effectConverters = GetAllBIRPConverters();
}
if (oldVolumes != null)
{
foreach (var oldVolume in oldVolumes)
{
ConvertVolume(oldVolume, ref succeeded, message);
}
}
if (oldLayers != null)
{
foreach (var oldLayer in oldLayers)
{
ConvertLayer(oldLayer, ref succeeded, message);
}
}
if (obj is BIRPRendering.PostProcessProfile oldProfile)
{
ConvertProfile(oldProfile, ref succeeded, message);
}
if (!succeeded)
{
return Status.Error;
}
else
{
var currentScene = SceneManager.GetActiveScene();
EditorSceneManager.SaveScene(currentScene);
return Status.Success;
}
}
public override void AfterConvert()
{
for (var i = 0; i < postConversionDestroyables.Count; i++)
{
Object.DestroyImmediate(postConversionDestroyables[i], allowDestroyingAssets: true);
}
postConversionDestroyables.Clear();
}
#region Conversion_Entry_Points
private void ConvertVolume(BIRPRendering.PostProcessVolume oldVolume, ref bool succeeded,
StringBuilder errorString)
{
if (!succeeded)
{
return;
}
if (!oldVolume)
{
// TODO: unless there's good way to tell the if the object is just missing because it was already
// converted as part of an earlier conversion object, then these two lines should be commented
// out or removed. It should still return though.
// succeeded = false;
// errorString.AppendLine("PPv2 PostProcessVolume failed to be converted because the original asset reference was lost during conversion.");
return;
}
if (PrefabUtility.IsPartOfPrefabInstance(oldVolume) &&
!PrefabUtility.IsAddedComponentOverride(oldVolume))
{
// This is a property override on an instance of the component,
// so override the component instance with the modifications.
succeeded = ConvertVolumeInstance(oldVolume, errorString);
}
else
{
// The entire component is unique, so just convert it
succeeded = ConvertVolumeComponent(oldVolume, errorString);
}
}
private void ConvertLayer(BIRPRendering.PostProcessLayer oldLayer, ref bool succeeded,
StringBuilder errorString)
{
if (!succeeded)
{
return;
}
if (!oldLayer)
{
// TODO: unless there's good way to tell the if the object is just missing because it was already
// converted as part of an earlier conversion object, then these two lines should be commented
// out or removed. It should still return though.
// succeeded = false;
// errorString.AppendLine("PPv2 PostProcessLayer failed to be converted because the original asset reference was lost during conversion.");
return;
}
if (PrefabUtility.IsPartOfPrefabInstance(oldLayer) &&
!PrefabUtility.IsAddedComponentOverride(oldLayer))
{
// This is a property override on an instance of the component,
// so override the component instance with the modifications.
succeeded = ConvertLayerInstance(oldLayer, errorString);
}
else
{
// The entire component is unique, so just convert it
succeeded = ConvertLayerComponent(oldLayer, errorString);
}
}
private void ConvertProfile(BIRPRendering.PostProcessProfile oldProfile, ref bool succeeded,
StringBuilder errorString)
{
if (!succeeded)
{
return;
}
if (!oldProfile)
{
errorString.AppendLine(
"PPv2 PostProcessProfile failed to be converted because the original asset reference was lost during conversion.");
return;
}
ConvertVolumeProfileAsset(oldProfile, errorString, ref succeeded);
// TODO:
// - Perhaps old Profiles should only be deleted if they actually no longer have references,
// just in case some some Volume conversions are skipped and still need references for future conversion.
// - Alternatively, leave deletion of Profiles entirely to the user. (I think this is preferred)
}
#endregion Conversion_Entry_Points
private bool ConvertVolumeComponent(BIRPRendering.PostProcessVolume oldVolume, StringBuilder errorString)
{
// Don't convert if it appears to already have been converted.
if (oldVolume.GetComponent<Volume>()) return true;
var gameObject = oldVolume.gameObject;
var newVolume = gameObject.AddComponent<Volume>();
newVolume.priority = oldVolume.priority;
newVolume.weight = oldVolume.weight;
newVolume.blendDistance = oldVolume.blendDistance;
newVolume.isGlobal = oldVolume.isGlobal;
newVolume.enabled = oldVolume.enabled;
var success = true;
newVolume.sharedProfile = ConvertVolumeProfileAsset(oldVolume.sharedProfile, errorString, ref success);
if (PrefabUtility.IsPartOfPrefabAsset(oldVolume))
{
postConversionDestroyables.Add(oldVolume);
}
else
{
Object.DestroyImmediate(oldVolume, allowDestroyingAssets: true);
}
EditorUtility.SetDirty(gameObject);
return success;
}
private bool ConvertVolumeInstance(BIRPRendering.PostProcessVolume oldVolume, StringBuilder errorString)
{
// First get a reference to the local instance of the converted component
// which may require immediately converting it at its origin location first.
var newVolumeInstance = oldVolume.GetComponent<Volume>();
if (!newVolumeInstance)
{
var oldVolumeOrigin = PrefabUtility.GetCorrespondingObjectFromSource(oldVolume);
if (!ConvertVolumeComponent(oldVolumeOrigin, errorString))
{
return false;
}
PrefabUtility.SavePrefabAsset(oldVolumeOrigin.gameObject);
newVolumeInstance = oldVolume.GetComponent<Volume>();
if (!newVolumeInstance)
{
errorString.AppendLine(
"PPv2 PostProcessVolume failed to be converted because the instance object did not inherit the converted Prefab source.");
return false;
}
}
bool success = true;
var oldModifications = PrefabUtility.GetPropertyModifications(oldVolume);
foreach (var oldModification in oldModifications)
{
if (oldModification.target is BIRPRendering.PostProcessVolume)
{
if (oldModification.propertyPath.EndsWith("priority", StringComparison.InvariantCultureIgnoreCase))
newVolumeInstance.priority = oldVolume.priority;
else if (oldModification.propertyPath.EndsWith("weight",
StringComparison.InvariantCultureIgnoreCase))
newVolumeInstance.weight = oldVolume.weight;
else if (oldModification.propertyPath.EndsWith("blendDistance",
StringComparison.InvariantCultureIgnoreCase))
newVolumeInstance.blendDistance = oldVolume.blendDistance;
else if (oldModification.propertyPath.EndsWith("isGlobal",
StringComparison.InvariantCultureIgnoreCase))
newVolumeInstance.isGlobal = oldVolume.isGlobal;
else if (oldModification.propertyPath.EndsWith("enabled",
StringComparison.InvariantCultureIgnoreCase))
newVolumeInstance.enabled = oldVolume.enabled;
else if (oldModification.propertyPath.EndsWith("sharedProfile",
StringComparison.InvariantCultureIgnoreCase))
newVolumeInstance.sharedProfile =
ConvertVolumeProfileAsset(oldVolume.sharedProfile, errorString, ref success);
EditorUtility.SetDirty(newVolumeInstance);
}
}
return success;
}
private bool ConvertLayerComponent(BIRPRendering.PostProcessLayer oldLayer, StringBuilder errorString)
{
var siblingCamera = oldLayer.GetComponent<Camera>().GetUniversalAdditionalCameraData();
// PostProcessLayer requires a sibling Camera component, but
// we check it here just in case something weird went happened.
if (!siblingCamera)
{
errorString.AppendLine(
"PPv2 PostProcessLayer failed to be converted because the instance object was missing a required sibling Camera component.");
return false;
}
// The presence of a PostProcessLayer implies the Camera should render post-processes
siblingCamera.renderPostProcessing = true;
siblingCamera.volumeLayerMask = oldLayer.volumeLayer;
siblingCamera.volumeTrigger = oldLayer.volumeTrigger;
siblingCamera.stopNaN = oldLayer.stopNaNPropagation;
siblingCamera.antialiasingQuality =
(URPRendering.AntialiasingQuality)oldLayer.subpixelMorphologicalAntialiasing.quality;
switch (oldLayer.antialiasingMode)
{
case BIRPRendering.PostProcessLayer.Antialiasing.None:
siblingCamera.antialiasing = URPRendering.AntialiasingMode.None;
break;
case BIRPRendering.PostProcessLayer.Antialiasing.FastApproximateAntialiasing:
siblingCamera.antialiasing = URPRendering.AntialiasingMode.FastApproximateAntialiasing;
break;
case BIRPRendering.PostProcessLayer.Antialiasing.SubpixelMorphologicalAntialiasing:
siblingCamera.antialiasing = URPRendering.AntialiasingMode.SubpixelMorphologicalAntiAliasing;
break;
default:
// Default to the the most performant mode, since "None" is an explicit option.
siblingCamera.antialiasing = URPRendering.AntialiasingMode.FastApproximateAntialiasing;
break;
}
if (PrefabUtility.IsPartOfPrefabAsset(oldLayer))
{
postConversionDestroyables.Add(oldLayer);
}
else
{
Object.DestroyImmediate(oldLayer, allowDestroyingAssets: true);
}
EditorUtility.SetDirty(siblingCamera.gameObject);
return true;
}
private bool ConvertLayerInstance(BIRPRendering.PostProcessLayer oldLayer, StringBuilder errorString)
{
// First get a reference to the local instance of the camera (which is required by PostProcessingLayer)
var siblingCamera = oldLayer.GetComponent<Camera>().GetUniversalAdditionalCameraData();
if (!siblingCamera)
{
errorString.AppendLine(
"PPv2 PostProcessLayer failed to be converted because the instance object was missing a required sibling Camera component.");
return false;
}
var oldModifications = PrefabUtility.GetPropertyModifications(oldLayer);
foreach (var oldModification in oldModifications)
{
if (oldModification.target is BIRPRendering.PostProcessLayer)
{
if (oldModification.propertyPath.EndsWith("volumeLayer",
StringComparison.InvariantCultureIgnoreCase))
siblingCamera.volumeLayerMask = oldLayer.volumeLayer;
else if (oldModification.propertyPath.EndsWith("volumeTrigger",
StringComparison.InvariantCultureIgnoreCase))
siblingCamera.volumeTrigger = oldLayer.volumeTrigger;
else if (oldModification.propertyPath.EndsWith("stopNaNPropagation",
StringComparison.InvariantCultureIgnoreCase))
siblingCamera.stopNaN = oldLayer.stopNaNPropagation;
else if (oldModification.propertyPath.EndsWith("quality",
StringComparison.InvariantCultureIgnoreCase))
siblingCamera.antialiasingQuality =
(URPRendering.AntialiasingQuality)oldLayer.subpixelMorphologicalAntialiasing.quality;
else if (oldModification.propertyPath.EndsWith("antialiasingMode",
StringComparison.InvariantCultureIgnoreCase))
{
switch (oldLayer.antialiasingMode)
{
case BIRPRendering.PostProcessLayer.Antialiasing.None:
siblingCamera.antialiasing = URPRendering.AntialiasingMode.None;
break;
case BIRPRendering.PostProcessLayer.Antialiasing.FastApproximateAntialiasing:
siblingCamera.antialiasing = URPRendering.AntialiasingMode.FastApproximateAntialiasing;
break;
case BIRPRendering.PostProcessLayer.Antialiasing.SubpixelMorphologicalAntialiasing:
siblingCamera.antialiasing =
URPRendering.AntialiasingMode.SubpixelMorphologicalAntiAliasing;
break;
default:
// Default to the the most performant mode, since "None" is an explicit option.
siblingCamera.antialiasing = URPRendering.AntialiasingMode.FastApproximateAntialiasing;
break;
}
}
EditorUtility.SetDirty(siblingCamera);
}
}
return true;
}
private VolumeProfile ConvertVolumeProfileAsset(BIRPRendering.PostProcessProfile oldProfile,
StringBuilder errorString, ref bool success)
{
// Don't convert if it appears to already have been converted.
if (!oldProfile) return null;
var oldPath = AssetDatabase.GetAssetPath(oldProfile);
var oldDirectory = Path.GetDirectoryName(oldPath);
var oldName = Path.GetFileNameWithoutExtension(oldPath);
var newPath = Path.Combine(oldDirectory, $"{oldName}(URP).asset");
if (File.Exists(newPath))
{
return AssetDatabase.LoadAssetAtPath<VolumeProfile>(newPath);
}
var newProfile = ScriptableObject.CreateInstance<VolumeProfile>();
try
{
AssetDatabase.CreateAsset(newProfile, newPath);
}
catch (Exception e)
{
errorString.AppendLine($"PPv2 PostProcessLayer failed to be converted with exception:\n{e}");
success = false;
if (!newProfile) return null;
}
foreach (var oldSettings in oldProfile.settings)
{
foreach (var effectConverter in effectConverters)
{
effectConverter.AddConvertedProfileSettingsToProfile(oldSettings, newProfile);
}
}
EditorUtility.SetDirty(newProfile);
return newProfile;
}
public IEnumerable<PostProcessEffectSettingsConverter> GetAllBIRPConverters()
{
var baseType = typeof(PostProcessEffectSettingsConverter);
var assembly = Assembly.GetAssembly(baseType);
var derivedTypes = assembly
.GetTypes()
.Where(t =>
t.BaseType != null &&
t.BaseType == baseType)
.Select(t => ScriptableObject.CreateInstance(t) as PostProcessEffectSettingsConverter);
return derivedTypes;
}
#else
public override bool isEnabled => false;
public override string isDisabledMessage => "Post Processing package is not installed. Please install the Post Processing package to enable this converter.";
protected override List<(string query, string description)> contextSearchQueriesAndIds
=> null;
protected override Status ConvertObject(UnityEngine.Object obj, StringBuilder message) { return Status.Error; }
#endif
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 54019ac30a4ca724eac51bad54f48aac
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d5fa30f043d2e274f9024230be655650
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,642 @@
using System;
using System.Runtime.CompilerServices;
using UnityEditor.Rendering.Universal.ShaderGUI;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
[assembly: InternalsVisibleTo("MaterialPostprocessor")]
namespace UnityEditor.Rendering.Universal
{
internal interface IBuiltInToURPMaterialUpgrader
{
}
internal sealed class MaterialUpgradeUtils
{
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");
}
}
/// <summary>
/// Upgrade parameters for the supported shaders.
/// </summary>
public static class SupportedUpgradeParams
{
/// <summary>
/// Upgrade parameters for diffuse Opaque.
/// </summary>
public static UpgradeParams diffuseOpaque = new UpgradeParams()
{
surfaceType = UpgradeSurfaceType.Opaque,
blendMode = UpgradeBlendMode.Alpha,
alphaClip = false,
specularSource = SpecularSource.NoSpecular,
smoothnessSource = SmoothnessSource.BaseAlpha,
};
/// <summary>
/// Upgrade parameters for specular opaque.
/// </summary>
public static UpgradeParams specularOpaque = new UpgradeParams()
{
surfaceType = UpgradeSurfaceType.Opaque,
blendMode = UpgradeBlendMode.Alpha,
alphaClip = false,
specularSource = SpecularSource.SpecularTextureAndColor,
smoothnessSource = SmoothnessSource.BaseAlpha,
};
/// <summary>
/// Upgrade parameters for diffuse alpha.
/// </summary>
public static UpgradeParams diffuseAlpha = new UpgradeParams()
{
surfaceType = UpgradeSurfaceType.Transparent,
blendMode = UpgradeBlendMode.Alpha,
alphaClip = false,
specularSource = SpecularSource.NoSpecular,
smoothnessSource = SmoothnessSource.SpecularAlpha,
};
/// <summary>
/// Upgrade parameters for specular alpha.
/// </summary>
public static UpgradeParams specularAlpha = new UpgradeParams()
{
surfaceType = UpgradeSurfaceType.Transparent,
blendMode = UpgradeBlendMode.Alpha,
alphaClip = false,
specularSource = SpecularSource.SpecularTextureAndColor,
smoothnessSource = SmoothnessSource.SpecularAlpha,
};
/// <summary>
/// Upgrade parameters for diffuse alpha cutout.
/// </summary>
public static UpgradeParams diffuseAlphaCutout = new UpgradeParams()
{
surfaceType = UpgradeSurfaceType.Opaque,
blendMode = UpgradeBlendMode.Alpha,
alphaClip = true,
specularSource = SpecularSource.NoSpecular,
smoothnessSource = SmoothnessSource.SpecularAlpha,
};
/// <summary>
/// Upgrade parameters for specular alpha cutout.
/// </summary>
public static UpgradeParams specularAlphaCutout = new UpgradeParams()
{
surfaceType = UpgradeSurfaceType.Opaque,
blendMode = UpgradeBlendMode.Alpha,
alphaClip = true,
specularSource = SpecularSource.SpecularTextureAndColor,
smoothnessSource = SmoothnessSource.SpecularAlpha,
};
/// <summary>
/// Upgrade parameters for diffuse cubemap.
/// </summary>
public static UpgradeParams diffuseCubemap = new UpgradeParams()
{
surfaceType = UpgradeSurfaceType.Opaque,
blendMode = UpgradeBlendMode.Alpha,
alphaClip = false,
specularSource = SpecularSource.NoSpecular,
smoothnessSource = SmoothnessSource.BaseAlpha,
};
/// <summary>
/// Upgrade parameters for specular cubemap.
/// </summary>
public static UpgradeParams specularCubemap = new UpgradeParams()
{
surfaceType = UpgradeSurfaceType.Opaque,
blendMode = UpgradeBlendMode.Alpha,
alphaClip = false,
specularSource = SpecularSource.SpecularTextureAndColor,
smoothnessSource = SmoothnessSource.BaseAlpha,
};
/// <summary>
/// Upgrade parameters for diffuse cubemap alpha.
/// </summary>
public static UpgradeParams diffuseCubemapAlpha = new UpgradeParams()
{
surfaceType = UpgradeSurfaceType.Transparent,
blendMode = UpgradeBlendMode.Alpha,
alphaClip = false,
specularSource = SpecularSource.NoSpecular,
smoothnessSource = SmoothnessSource.BaseAlpha,
};
/// <summary>
/// Upgrade parameters for specular cubemap alpha.
/// </summary>
public static UpgradeParams specularCubemapAlpha = new UpgradeParams()
{
surfaceType = UpgradeSurfaceType.Transparent,
blendMode = UpgradeBlendMode.Alpha,
alphaClip = false,
specularSource = SpecularSource.SpecularTextureAndColor,
smoothnessSource = SmoothnessSource.BaseAlpha,
};
}
/// <summary>
/// Upgrader for the standard and standard (specular setup) shaders.
/// </summary>
public class StandardUpgrader : MaterialUpgrader, IBuiltInToURPMaterialUpgrader
{
enum LegacyRenderingMode
{
Opaque,
Cutout,
Fade, // Old school alpha-blending mode, fresnel does not affect amount of transparency
Transparent // Physically plausible transparency mode, implemented as alpha pre-multiply
}
/// <summary>
/// Updates keywords for the standard shader.
/// </summary>
/// <param name="material">The material to update.</param>
/// <exception cref="ArgumentNullException"></exception>
public static void UpdateStandardMaterialKeywords(Material material)
{
if (material == null)
throw new ArgumentNullException("material");
if (material.GetTexture("_MetallicGlossMap"))
material.SetFloat("_Smoothness", material.GetFloat("_GlossMapScale"));
else
material.SetFloat("_Smoothness", material.GetFloat("_Glossiness"));
if (material.IsKeywordEnabled("_ALPHATEST_ON"))
{
material.SetFloat("_AlphaClip", 1.0f);
}
material.SetFloat("_WorkflowMode", 1.0f);
CoreUtils.SetKeyword(material, "_OCCLUSIONMAP", material.GetTexture("_OcclusionMap"));
CoreUtils.SetKeyword(material, "_METALLICSPECGLOSSMAP", material.GetTexture("_MetallicGlossMap"));
UpdateSurfaceTypeAndBlendMode(material);
UpdateDetailScaleOffset(material);
BaseShaderGUI.SetupMaterialBlendMode(material);
MaterialUpgradeUtils.DisableKeywords(material);
}
/// <summary>
/// Updates keywords for the standard specular shader.
/// </summary>
/// <param name="material">The material to update.</param>
/// <exception cref="ArgumentNullException"></exception>
public static void UpdateStandardSpecularMaterialKeywords(Material material)
{
if (material == null)
throw new ArgumentNullException("material");
if (material.GetTexture("_SpecGlossMap"))
material.SetFloat("_Smoothness", material.GetFloat("_GlossMapScale"));
else
material.SetFloat("_Smoothness", material.GetFloat("_Glossiness"));
material.SetFloat("_WorkflowMode", 0.0f);
CoreUtils.SetKeyword(material, "_OCCLUSIONMAP", material.GetTexture("_OcclusionMap"));
CoreUtils.SetKeyword(material, "_METALLICSPECGLOSSMAP", material.GetTexture("_SpecGlossMap"));
CoreUtils.SetKeyword(material, "_SPECULAR_SETUP", true);
UpdateSurfaceTypeAndBlendMode(material);
UpdateDetailScaleOffset(material);
BaseShaderGUI.SetupMaterialBlendMode(material);
MaterialUpgradeUtils.DisableKeywords(material);
}
static void UpdateDetailScaleOffset(Material material)
{
// In URP details tile/offset is multipied with base tile/offset, where in builtin is not
// Basically we setup new tile/offset values that in shader they would result in same values as in builtin
// This archieved with inverted calculation where scale=detailScale/baseScale and tile=detailOffset-baseOffset*scale
var baseScale = material.GetTextureScale("_BaseMap");
var baseOffset = material.GetTextureOffset("_BaseMap");
var detailScale = material.GetTextureScale("_DetailAlbedoMap");
var detailOffset = material.GetTextureOffset("_DetailAlbedoMap");
var scale = new Vector2(baseScale.x == 0 ? 0 : detailScale.x / baseScale.x, baseScale.y == 0 ? 0 : detailScale.y / baseScale.y);
material.SetTextureScale("_DetailAlbedoMap", scale);
material.SetTextureOffset("_DetailAlbedoMap", new Vector2((detailOffset.x - baseOffset.x * scale.x), (detailOffset.y - baseOffset.y * scale.y)));
}
// Converts from legacy RenderingMode to new SurfaceType and BlendMode
static void UpdateSurfaceTypeAndBlendMode(Material material)
{
// Property _Mode is already renamed to _Surface at this point
var legacyRenderingMode = (LegacyRenderingMode)material.GetFloat("_Surface");
if (legacyRenderingMode == LegacyRenderingMode.Transparent)
{
material.EnableKeyword("_SURFACE_TYPE_TRANSPARENT");
material.SetFloat("_Surface", (float)BaseShaderGUI.SurfaceType.Transparent);
material.SetFloat("_Blend", (float)BaseShaderGUI.BlendMode.Premultiply);
}
else if (legacyRenderingMode == LegacyRenderingMode.Fade)
{
material.EnableKeyword("_SURFACE_TYPE_TRANSPARENT");
material.SetFloat("_Surface", (float)BaseShaderGUI.SurfaceType.Transparent);
material.SetFloat("_Blend", (float)BaseShaderGUI.BlendMode.Alpha);
}
else
{
material.DisableKeyword("_SURFACE_TYPE_TRANSPARENT");
material.SetFloat("_Surface", (float)BaseShaderGUI.SurfaceType.Opaque);
}
}
/// <summary>
/// Constructor for the StandardUpgrader class.
/// </summary>
/// <param name="oldShaderName">The name of the old shader.</param>
/// <exception cref="ArgumentNullException"></exception>
public StandardUpgrader(string oldShaderName)
{
if (oldShaderName == null)
throw new ArgumentNullException("oldShaderName");
string standardShaderPath = ShaderUtils.GetShaderPath(ShaderPathID.Lit);
if (oldShaderName.Contains("Specular"))
{
RenameShader(oldShaderName, standardShaderPath, UpdateStandardSpecularMaterialKeywords);
}
else
{
RenameShader(oldShaderName, standardShaderPath, UpdateStandardMaterialKeywords);
}
RenameFloat("_Mode", "_Surface");
RenameFloat("_Mode", "_AlphaClip", renderingMode => renderingMode == 1.0f);
RenameTexture("_MainTex", "_BaseMap");
RenameColor("_Color", "_BaseColor");
RenameFloat("_GlossyReflections", "_EnvironmentReflections");
}
}
internal class StandardSimpleLightingUpgrader : MaterialUpgrader, IBuiltInToURPMaterialUpgrader
{
internal StandardSimpleLightingUpgrader(string oldShaderName, UpgradeParams upgradeParams)
{
if (oldShaderName == null)
throw new ArgumentNullException("oldShaderName");
RenameShader(oldShaderName, ShaderUtils.GetShaderPath(ShaderPathID.SimpleLit), UpdateMaterialKeywords);
SetFloat("_Surface", (float)upgradeParams.surfaceType);
SetFloat("_Blend", (float)upgradeParams.blendMode);
SetFloat("_AlphaClip", upgradeParams.alphaClip ? 1 : 0);
SetFloat("_SpecularHighlights", (float)upgradeParams.specularSource);
SetFloat("_SmoothnessSource", (float)upgradeParams.smoothnessSource);
RenameTexture("_MainTex", "_BaseMap");
RenameColor("_Color", "_BaseColor");
RenameFloat("_Shininess", "_Smoothness");
if (oldShaderName.Contains("Legacy Shaders/Self-Illumin"))
{
RenameTexture("_Illum", "_EmissionMap");
RemoveTexture("_Illum");
SetColor("_EmissionColor", Color.white);
}
}
internal static void UpdateMaterialKeywords(Material material)
{
if (material == null)
throw new ArgumentNullException("material");
material.shaderKeywords = null;
BaseShaderGUI.SetupMaterialBlendMode(material);
UpdateMaterialSpecularSource(material);
CoreUtils.SetKeyword(material, "_NORMALMAP", material.GetTexture("_BumpMap"));
// A material's GI flag internally keeps track of whether emission is enabled at all, it's enabled but has no effect
// or is enabled and may be modified at runtime. This state depends on the values of the current flag and emissive color.
// The fixup routine makes sure that the material is in the correct state if/when changes are made to the mode or color.
MaterialEditor.FixupEmissiveFlag(material);
bool shouldEmissionBeEnabled = (material.globalIlluminationFlags & MaterialGlobalIlluminationFlags.AnyEmissive) != 0;
CoreUtils.SetKeyword(material, "_EMISSION", shouldEmissionBeEnabled);
MaterialUpgradeUtils.DisableKeywords(material);
}
private static void UpdateMaterialSpecularSource(Material material)
{
SpecularSource specSource = (SpecularSource)material.GetFloat("_SpecSource");
if (specSource == SpecularSource.NoSpecular)
{
CoreUtils.SetKeyword(material, "_SPECGLOSSMAP", false);
CoreUtils.SetKeyword(material, "_SPECULAR_COLOR", false);
CoreUtils.SetKeyword(material, "_GLOSSINESS_FROM_BASE_ALPHA", false);
}
else
{
SmoothnessSource glossSource = (SmoothnessSource)material.GetFloat("_SmoothnessSource");
bool hasGlossMap = material.GetTexture("_SpecGlossMap");
CoreUtils.SetKeyword(material, "_SPECGLOSSMAP", hasGlossMap);
CoreUtils.SetKeyword(material, "_SPECULAR_COLOR", !hasGlossMap);
CoreUtils.SetKeyword(material, "_GLOSSINESS_FROM_BASE_ALPHA", glossSource == SmoothnessSource.BaseAlpha);
}
}
}
/// <summary>
/// Upgrader for terrain materials.
/// </summary>
public class TerrainUpgrader : MaterialUpgrader, IBuiltInToURPMaterialUpgrader
{
/// <summary>
/// Constructor for the terrain upgrader.
/// </summary>
/// <param name="oldShaderName">The name of the old shader.</param>
public TerrainUpgrader(string oldShaderName)
{
RenameShader(oldShaderName, ShaderUtils.GetShaderPath(ShaderPathID.TerrainLit), MaterialUpgradeUtils.DisableKeywords);
}
}
internal class SpeedTreeUpgrader : MaterialUpgrader, IBuiltInToURPMaterialUpgrader
{
internal SpeedTreeUpgrader(string oldShaderName)
{
RenameShader(oldShaderName, ShaderUtils.GetShaderPath(ShaderPathID.SpeedTree7), MaterialUpgradeUtils.DisableKeywords);
}
}
internal class SpeedTreeBillboardUpgrader : MaterialUpgrader, IBuiltInToURPMaterialUpgrader
{
internal SpeedTreeBillboardUpgrader(string oldShaderName)
{
RenameShader(oldShaderName, ShaderUtils.GetShaderPath(ShaderPathID.SpeedTree7Billboard), MaterialUpgradeUtils.DisableKeywords);
}
}
/// <summary>
/// Upgrader for particle materials.
/// </summary>
public class ParticleUpgrader : MaterialUpgrader, IBuiltInToURPMaterialUpgrader
{
/// <summary>
/// Constructor for the particle upgrader.
/// </summary>
/// <param name="oldShaderName">The name of the old shader.</param>
/// <exception cref="ArgumentNullException"></exception>
public ParticleUpgrader(string oldShaderName)
{
if (oldShaderName == null)
throw new ArgumentNullException("oldShaderName");
RenameFloat("_Mode", "_Surface");
if (oldShaderName.Contains("Unlit"))
{
RenameShader(oldShaderName, ShaderUtils.GetShaderPath(ShaderPathID.ParticlesUnlit), UpdateUnlit);
}
else
{
RenameShader(oldShaderName, ShaderUtils.GetShaderPath(ShaderPathID.ParticlesLit), UpdateStandardSurface);
RenameFloat("_Glossiness", "_Smoothness");
}
RenameTexture("_MainTex", "_BaseMap");
RenameColor("_Color", "_BaseColor");
RenameFloat("_FlipbookMode", "_FlipbookBlending");
// Forward the _EMISSION keyword state from old shader to new shader
TransferKeyword("_EMISSION");
}
/// <summary>
/// Updates the standard shader surface properties.
/// </summary>
/// <param name="material"></param>
public static void UpdateStandardSurface(Material material)
{
UpdateSurfaceBlendModes(material);
ParticleGUI.SetupMaterialWithColorMode(material);
MaterialUpgradeUtils.DisableKeywords(material);
FixEmissiveFlags(material);
}
/// <summary>
/// Updates the unlit shader properties.
/// </summary>
/// <param name="material"></param>
public static void UpdateUnlit(Material material)
{
UpdateSurfaceBlendModes(material);
ParticleGUI.SetupMaterialWithColorMode(material);
MaterialUpgradeUtils.DisableKeywords(material);
FixEmissiveFlags(material);
}
/// <summary>
/// Fixes emission keyword and global illumination flags on the upgraded material.
/// Call this in the finalizer after the _EMISSION keyword has been forwarded.
/// </summary>
/// <param name="material">The upgraded material with the new shader.</param>
static void FixEmissiveFlags(Material material)
{
if (material == null)
return;
// If _EMISSION keyword is enabled, ensure globalIlluminationFlags are set correctly
if (material.IsKeywordEnabled("_EMISSION"))
{
LightingSettings lightingSettingsOrDefaultsFallback = Lightmapping.GetLightingSettingsOrDefaultsFallback();
MaterialGlobalIlluminationFlags materialGlobalIlluminationFlags =
(lightingSettingsOrDefaultsFallback.realtimeGI ? MaterialGlobalIlluminationFlags.RealtimeEmissive :
(lightingSettingsOrDefaultsFallback.bakedGI ? MaterialGlobalIlluminationFlags.BakedEmissive :
MaterialGlobalIlluminationFlags.None));
material.globalIlluminationFlags = materialGlobalIlluminationFlags;
}
// Fix emission checkbox appearing enabled after conversion when it was disabled in BiRP.
// BiRP Particles that never had emission toggled in inspector have None flags by default,
// but the emission checkbox checks if flags != EmissiveIsBlack (see MaterialEditor.EmissionEnabledProperty).
// Set EmissiveIsBlack to match what BiRP Standard does when emission is unchecked.
else if (material.globalIlluminationFlags == MaterialGlobalIlluminationFlags.None)
{
material.globalIlluminationFlags = MaterialGlobalIlluminationFlags.EmissiveIsBlack;
}
}
/// <summary>
/// Updates the blending mode properties.
/// </summary>
/// <param name="material"></param>
public static void UpdateSurfaceBlendModes(Material material)
{
switch (material.GetFloat("_Mode"))
{
case 0: // opaque
material.DisableKeyword("_SURFACE_TYPE_TRANSPARENT");
material.SetFloat("_Surface", (int)UpgradeSurfaceType.Opaque);
break;
case 1: // cutout > alphatest
material.DisableKeyword("_SURFACE_TYPE_TRANSPARENT");
material.SetFloat("_Surface", (int)UpgradeSurfaceType.Opaque);
material.SetFloat("_AlphaClip", 1);
break;
case 2: // fade > alpha
material.EnableKeyword("_SURFACE_TYPE_TRANSPARENT");
material.SetFloat("_Surface", (int)UpgradeSurfaceType.Transparent);
material.SetFloat("_Blend", (int)UpgradeBlendMode.Alpha);
break;
case 3: // transparent > premul
material.EnableKeyword("_SURFACE_TYPE_TRANSPARENT");
material.SetFloat("_Surface", (int)UpgradeSurfaceType.Transparent);
material.SetFloat("_Blend", (int)UpgradeBlendMode.Premultiply);
break;
case 4: // add
material.EnableKeyword("_SURFACE_TYPE_TRANSPARENT");
material.SetFloat("_Surface", (int)UpgradeSurfaceType.Transparent);
material.SetFloat("_Blend", (int)UpgradeBlendMode.Additive);
break;
case 5: // sub > transparent with Subtractive color mode
material.EnableKeyword("_SURFACE_TYPE_TRANSPARENT");
material.SetFloat("_Surface", (int)UpgradeSurfaceType.Transparent);
material.SetFloat("_Blend", (int)UpgradeBlendMode.Alpha);
material.SetFloat("_ColorMode", 2f); // ParticleGUI.ColorMode.Subtractive
break;
case 6: // mod > multiply
material.EnableKeyword("_SURFACE_TYPE_TRANSPARENT");
material.SetFloat("_Surface", (int)UpgradeSurfaceType.Transparent);
material.SetFloat("_Blend", (int)UpgradeBlendMode.Multiply);
break;
}
}
}
/// <summary>
/// Upgrader for the autodesk interactive shaders.
/// </summary>
public class AutodeskInteractiveUpgrader : MaterialUpgrader, IBuiltInToURPMaterialUpgrader
{
enum LegacyRenderingMode
{
Opaque,
Cutout,
Fade, // Old school alpha-blending mode, fresnel does not affect amount of transparency
Transparent // Physically plausible transparency mode, implemented as alpha pre-multiply
}
/// <summary>
/// Constructor for the autodesk interactive upgrader.
/// </summary>
/// <param name="oldShaderName">The name of the old shader.</param>
public AutodeskInteractiveUpgrader(string oldShaderName)
{
RenameShader(oldShaderName, "Universal Render Pipeline/Autodesk Interactive/AutodeskInteractive", MaterialUpgradeUtils.DisableKeywords);
}
private bool TryGetShaderUpgrade(Material material, out Shader shader)
{
if (material == null)
{
shader = null;
return false;
}
if (!GraphicsSettings.TryGetRenderPipelineSettings<UniversalRenderPipelineEditorShaders>(out var settings))
{
shader = null;
return false;
}
shader = null;
var legacyRenderingMode = (LegacyRenderingMode)material.GetFloat("_Mode");
switch (legacyRenderingMode)
{
case LegacyRenderingMode.Opaque:
shader = settings.autodeskInteractiveShader;
break;
case LegacyRenderingMode.Cutout:
shader = settings.autodeskInteractiveMaskedShader;
break;
case LegacyRenderingMode.Fade:
shader = settings.autodeskInteractiveTransparentShader;
break;
case LegacyRenderingMode.Transparent:
shader = settings.autodeskInteractiveTransparentShader;
break;
}
return true;
}
/// <inheritdoc/>
public override void Upgrade(Material material, UpgradeFlags flags)
{
if (material == null)
throw new ArgumentNullException(nameof(material));
if (!TryGetShaderUpgrade(material, out var shader))
{
Debug.LogError($"Unable to find destination shader {NewShaderPath} when trying to upgrade {material.name}");
return;
}
Material newMaterial;
if ((flags & UpgradeFlags.CleanupNonUpgradedProperties) != 0)
{
newMaterial = new Material(shader);
}
else
{
newMaterial = UnityEngine.Object.Instantiate(material) as Material;
newMaterial.shader = shader;
}
Convert(material, newMaterial);
// Material Variants will not change the shader as is a parent only thing
if (material.parent == null)
material.shader = shader;
material.CopyPropertiesFromMaterial(newMaterial);
UnityEngine.Object.DestroyImmediate(newMaterial);
Finalizer?.Invoke(material);
}
/// <inheritdoc/>
public override void Convert(Material srcMaterial, Material dstMaterial)
{
base.Convert(srcMaterial, dstMaterial);
dstMaterial.SetFloat("_UseColorMap", srcMaterial.GetTexture("_MainTex") ? 1.0f : .0f);
dstMaterial.SetFloat("_UseMetallicMap", srcMaterial.GetTexture("_MetallicGlossMap") ? 1.0f : .0f);
dstMaterial.SetFloat("_UseNormalMap", srcMaterial.GetTexture("_BumpMap") ? 1.0f : .0f);
dstMaterial.SetFloat("_UseRoughnessMap", srcMaterial.GetTexture("_SpecGlossMap") ? 1.0f : .0f);
dstMaterial.SetFloat("_UseEmissiveMap", srcMaterial.GetTexture("_EmissionMap") ? 1.0f : .0f);
dstMaterial.SetFloat("_UseAoMap", srcMaterial.GetTexture("_OcclusionMap") ? 1.0f : .0f);
dstMaterial.SetVector("_UvOffset", srcMaterial.GetTextureOffset("_MainTex"));
dstMaterial.SetVector("_UvTiling", srcMaterial.GetTextureScale("_MainTex"));
if (!TryGetShaderUpgrade(srcMaterial, out var shader))
{
return;
}
var legacyRenderingMode = (LegacyRenderingMode)srcMaterial.GetFloat("_Mode");
switch (legacyRenderingMode)
{
case LegacyRenderingMode.Opaque:
break;
case LegacyRenderingMode.Cutout:
dstMaterial.SetFloat("_UseOpacityMap", .0f);
dstMaterial.SetFloat("_OpacityThreshold", srcMaterial.GetFloat("_Cutoff"));
break;
case LegacyRenderingMode.Fade:
dstMaterial.SetFloat("_UseOpacityMap", .0f);
dstMaterial.SetFloat("_Opacity", srcMaterial.GetColor("_Color").a);
break;
case LegacyRenderingMode.Transparent:
dstMaterial.SetFloat("_UseOpacityMap", .0f);
dstMaterial.SetFloat("_Opacity", srcMaterial.GetColor("_Color").a);
break;
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 12779f6eb83918741bac0370abcf0df9
@@ -0,0 +1,147 @@
using System.Collections.Generic;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
[SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))]
class StandardMaterialUpgraderProvider : IMaterialUpgradersProvider
{
public IEnumerable<MaterialUpgrader> GetUpgraders()
{
yield return new StandardUpgrader("Standard");
yield return new StandardUpgrader("Standard (Specular setup)");
}
}
[SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))]
class StandardSimpleLightingUpgraderProvider : IMaterialUpgradersProvider
{
public IEnumerable<MaterialUpgrader> GetUpgraders()
{
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Diffuse", SupportedUpgradeParams.diffuseOpaque);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Diffuse Detail", SupportedUpgradeParams.diffuseOpaque);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Diffuse Fast", SupportedUpgradeParams.diffuseOpaque);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Specular", SupportedUpgradeParams.specularOpaque);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Bumped Diffuse", SupportedUpgradeParams.diffuseOpaque);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Bumped Specular", SupportedUpgradeParams.specularOpaque);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Parallax Diffuse", SupportedUpgradeParams.diffuseOpaque);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Parallax Specular", SupportedUpgradeParams.specularOpaque);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/VertexLit", SupportedUpgradeParams.specularOpaque);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Cutout/VertexLit", SupportedUpgradeParams.specularAlphaCutout);
// Reflective
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Bumped Diffuse", SupportedUpgradeParams.diffuseCubemap);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Bumped Specular", SupportedUpgradeParams.specularCubemap);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Bumped Unlit", SupportedUpgradeParams.diffuseCubemap);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Bumped VertexLit", SupportedUpgradeParams.diffuseCubemap);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Diffuse", SupportedUpgradeParams.diffuseCubemap);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Specular", SupportedUpgradeParams.specularCubemap);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/VertexLit", SupportedUpgradeParams.diffuseCubemap);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Parallax Diffuse", SupportedUpgradeParams.diffuseCubemap);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Parallax Specular", SupportedUpgradeParams.specularCubemap);
// Self-Illum
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Self-Illumin/Diffuse", SupportedUpgradeParams.diffuseOpaque);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Self-Illumin/Bumped Diffuse", SupportedUpgradeParams.diffuseOpaque);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Self-Illumin/Parallax Diffuse", SupportedUpgradeParams.diffuseOpaque);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Self-Illumin/Specular", SupportedUpgradeParams.specularOpaque);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Self-Illumin/Bumped Specular", SupportedUpgradeParams.specularOpaque);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Self-Illumin/Parallax Specular", SupportedUpgradeParams.specularOpaque);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Self-Illumin/VertexLit", SupportedUpgradeParams.specularOpaque);
// Alpha Blended
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Diffuse", SupportedUpgradeParams.diffuseAlpha);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Specular", SupportedUpgradeParams.specularAlpha);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Bumped Diffuse", SupportedUpgradeParams.diffuseAlpha);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Bumped Specular", SupportedUpgradeParams.specularAlpha);
// Cutout
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Cutout/Diffuse", SupportedUpgradeParams.diffuseAlphaCutout);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Cutout/Specular", SupportedUpgradeParams.specularAlphaCutout);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Cutout/Bumped Diffuse", SupportedUpgradeParams.diffuseAlphaCutout);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Cutout/Bumped Specular", SupportedUpgradeParams.specularAlphaCutout);
// Lightmapped
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Lightmapped/Diffuse", SupportedUpgradeParams.diffuseOpaque);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Lightmapped/Specular", SupportedUpgradeParams.specularOpaque);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Lightmapped/VertexLit", SupportedUpgradeParams.specularOpaque);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Lightmapped/Bumped Diffuse", SupportedUpgradeParams.diffuseOpaque);
yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Lightmapped/Bumped Specular", SupportedUpgradeParams.specularOpaque);
}
}
[SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))]
class SpriteMaterialUpgraderProviders : IMaterialUpgradersProvider
{
public IEnumerable<MaterialUpgrader> GetUpgraders()
{
yield return new StandardSimpleLightingUpgrader("Sprites/Diffuse", SupportedUpgradeParams.diffuseAlpha);
}
}
[SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))]
class UIMaterialUpgraderProviders : IMaterialUpgradersProvider
{
public IEnumerable<MaterialUpgrader> 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
{
public IEnumerable<MaterialUpgrader> GetUpgraders()
{
yield return new StandardSimpleLightingUpgrader("Mobile/Diffuse", SupportedUpgradeParams.diffuseOpaque);
yield return new StandardSimpleLightingUpgrader("Mobile/Bumped Specular", SupportedUpgradeParams.specularOpaque);
yield return new StandardSimpleLightingUpgrader("Mobile/Bumped Specular (1 Directional Realtime Light)", SupportedUpgradeParams.specularOpaque);
yield return new StandardSimpleLightingUpgrader("Mobile/Bumped Diffuse", SupportedUpgradeParams.diffuseOpaque);
yield return new StandardSimpleLightingUpgrader("Mobile/Unlit (Supports Lightmap)", SupportedUpgradeParams.diffuseOpaque);
yield return new StandardSimpleLightingUpgrader("Mobile/VertexLit", SupportedUpgradeParams.specularOpaque);
yield return new StandardSimpleLightingUpgrader("Mobile/VertexLit (Only Directional Lights)", SupportedUpgradeParams.specularOpaque);
yield return new StandardSimpleLightingUpgrader("Mobile/Particles/VertexLit Blended", SupportedUpgradeParams.specularOpaque);
}
}
[SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))]
class TerrainMaterialUpgraderProvider : IMaterialUpgradersProvider
{
public IEnumerable<MaterialUpgrader> GetUpgraders()
{
yield return new TerrainUpgrader("Nature/Terrain/Diffuse");
yield return new TerrainUpgrader("Nature/Terrain/Standard");
yield return new SpeedTreeUpgrader("Nature/SpeedTree");
yield return new SpeedTreeBillboardUpgrader("Nature/SpeedTree Billboard");
yield return new UniversalSpeedTree8Upgrader("Nature/SpeedTree8");
yield return new UniversalSpeedTree9Upgrader("Nature/SpeedTree9");
}
}
[SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))]
class ParticleMaterialUpgraderProvider : IMaterialUpgradersProvider
{
public IEnumerable<MaterialUpgrader> GetUpgraders()
{
// Standard particle shaders
yield return new ParticleUpgrader("Particles/Standard Surface");
yield return new ParticleUpgrader("Particles/Standard Unlit");
yield return new ParticleUpgrader("Legacy Shaders/Particles/VertexLit Blended");
}
}
[SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))]
class AutodeskMaterialUpgraderProvider : IMaterialUpgradersProvider
{
public IEnumerable<MaterialUpgrader> GetUpgraders()
{
yield return new AutodeskInteractiveUpgrader("Autodesk Interactive");
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 2f37f38354ae11b4ba31a324dbabef7d
@@ -0,0 +1,43 @@
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
class UniversalSpeedTree8Upgrader : SpeedTree8MaterialUpgrader, IBuiltInToURPMaterialUpgrader
{
internal UniversalSpeedTree8Upgrader(string oldShaderName)
: base(oldShaderName, ShaderUtils.GetShaderPath(ShaderPathID.SpeedTree8), UniversalSpeedTree8MaterialFinalizer)
{
RenameFloat("_TwoSided", Property.CullMode);
}
static public void UniversalSpeedTree8MaterialFinalizer(Material mat)
{
SpeedTree8MaterialFinalizer(mat);
if (mat.HasFloat("_TwoSided"))
mat.SetFloat(Property.CullMode, mat.GetFloat("_TwoSided"));
Unity.Rendering.Universal.ShaderUtils.UpdateMaterial(mat,
Unity.Rendering.Universal.ShaderUtils.MaterialUpdateType.CreatedNewMaterial,
Unity.Rendering.Universal.ShaderUtils.ShaderID.SpeedTree8);
}
}
class UniversalSpeedTree8PostProcessor : AssetPostprocessor
{
void OnPostprocessSpeedTree(GameObject speedTree)
{
context.DependsOnCustomDependency("srp/default-pipeline");
if (RenderPipelineManager.currentPipeline is UniversalRenderPipeline)
{
SpeedTreeImporter stImporter = assetImporter as SpeedTreeImporter;
if(stImporter.isV8)
{
SpeedTree8MaterialUpgrader.PostprocessSpeedTree8Materials(speedTree, stImporter, UniversalSpeedTree8Upgrader.UniversalSpeedTree8MaterialFinalizer);
}
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a699ef0a455ff0440a0fe9b1689ec566
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,48 @@
using UnityEngine;
using UnityEngine.Rendering;
using UnityEditor.SpeedTree.Importer;
using UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
class UniversalSpeedTree9Upgrader : SpeedTree9MaterialUpgrader, IBuiltInToURPMaterialUpgrader
{
internal UniversalSpeedTree9Upgrader(string oldShaderName)
{
RenameShader(oldShaderName, "Universal Render Pipeline/Nature/SpeedTree9_URP", UniversalSpeedTree9MaterialFinalizer);
RenameFloat("_TwoSided", Property.CullMode);
RenameColor("_ColorTint", "_Color");
RenameKeywordToFloat("EFFECT_HUE_VARIATION", "_HueVariationKwToggle", 1, 0);
RenameKeywordToFloat("EFFECT_SUBSURFACE", "_SubsurfaceKwToggle", 1, 0);
RenameKeywordToFloat("EFFECT_BUMP", "_NormalMapKwToggle", 1, 0);
RenameKeywordToFloat("EFFECT_BILLBOARD", "_BillboardKwToggle", 1, 0);
RenameKeywordToFloat("EFFECT_EXTRA_TEX", "EFFECT_EXTRA_TEX", 1, 0);
}
const int kMaterialUpgraderVersion = 1;
[MaterialSettingsCallbackAttribute(kMaterialUpgraderVersion)]
private static void OnAssetPostProcessDelegate(GameObject mainObject)
{
if (IsCurrentPipelineURP())
{
SpeedTree9MaterialUpgrader.PostprocessSpeedTree9Materials(mainObject, UniversalSpeedTree9MaterialFinalizer);
}
}
static private bool IsCurrentPipelineURP()
{
return GraphicsSettings.currentRenderPipeline is UniversalRenderPipelineAsset;
}
static public void UniversalSpeedTree9MaterialFinalizer(Material mat)
{
if (mat.HasFloat("_TwoSided"))
mat.SetFloat(Property.CullMode, mat.GetFloat("_TwoSided"));
Unity.Rendering.Universal.ShaderUtils.UpdateMaterial(mat,
Unity.Rendering.Universal.ShaderUtils.MaterialUpdateType.CreatedNewMaterial,
Unity.Rendering.Universal.ShaderUtils.ShaderID.SpeedTree9);
}
}
}
@@ -0,0 +1,128 @@
namespace UnityEditor.Rendering.Universal
{
/// <summary>
/// The surface type for your material.
/// </summary>
public enum UpgradeSurfaceType
{
/// <summary>
/// Use this for opaque surfaces.
/// </summary>
Opaque,
/// <summary>
/// Use this for transparent surfaces.
/// </summary>
Transparent
}
/// <summary>
/// The blend mode for your material.
/// </summary>
public enum UpgradeBlendMode
{
/// <summary>
/// Use this for alpha blend mode.
/// </summary>
Alpha,
/// <summary>
/// Use this for premultiply blend mode.
/// </summary>
Premultiply,
/// <summary>
/// Use this for additive blend mode.
/// </summary>
Additive,
/// <summary>
/// Use this for multiply blend mode.
/// </summary>
Multiply
}
/// <summary>
/// Options for Specular source.
/// </summary>
public enum SpecularSource
{
/// <summary>
/// Use this to use specular texture and color.
/// </summary>
SpecularTextureAndColor,
/// <summary>
/// Use this when not using specular.
/// </summary>
NoSpecular
}
/// <summary>
/// Options to select the texture channel where the smoothness value is stored.
/// </summary>
public enum SmoothnessSource
{
/// <summary>
/// Use this when smoothness is stored in the alpha channel of the Specular Map.
/// </summary>
SpecularAlpha,
/// <summary>
/// Use this when smoothness is stored in the alpha channel of the base Map.
/// </summary>
BaseAlpha,
}
/// <summary>
/// Options to select the source for reflections.
/// </summary>
public enum ReflectionSource
{
/// <summary>
/// Use this when there are no reflections.
/// </summary>
NoReflection,
/// <summary>
/// Use this when the source comes from a cubemap.
/// </summary>
Cubemap,
/// <summary>
/// Use this when the source comes from a reflection probe.
/// </summary>
ReflectionProbe
}
/// <summary>
/// Container for the upgrade parameters.
/// </summary>
public struct UpgradeParams
{
/// <summary>
/// Surface type upgrade parameters.
/// </summary>
public UpgradeSurfaceType surfaceType { get; set; }
/// <summary>
/// Blend mode upgrade parameters.
/// </summary>
public UpgradeBlendMode blendMode { get; set; }
/// <summary>
/// Alpha clip upgrade parameters.
/// </summary>
public bool alphaClip { get; set; }
/// <summary>
/// Specular source upgrade parameters.
/// </summary>
public SpecularSource specularSource { get; set; }
/// <summary>
/// Smoothness source upgrade parameters.
/// </summary>
public SmoothnessSource smoothnessSource { get; set; }
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 8fe5351dffe46e648adb2abd7a167ce7
timeCreated: 1490691870
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor.Rendering.Universal;
using UnityEngine;
using UnityObject = UnityEngine.Object;
namespace UnityEditor.Rendering
{
/// <summary>
/// Class containing utility methods for upgrading assets affected by render pipeline migration.
/// </summary>
static class UpgradeUtility
{
/// <summary>
/// Stable, unique identifier for some asset.
/// </summary>
internal struct UID
{
public string Value;
public static implicit operator string(UID uid) => uid.Value;
public static implicit operator UID(string id) => new UID { Value = id };
}
internal interface IMaterial
{
UID ID { get; }
string ShaderName { get; }
}
internal struct MaterialProxy : IMaterial
{
public MaterialProxy(Material material, UnityObject[] allAssetsAtPath)
{
m_ID = $"{allAssetsAtPath}{Array.IndexOf(allAssetsAtPath, material)}";
m_Material = material;
}
UID m_ID;
Material m_Material;
public UID ID => m_ID;
public string ShaderName => m_Material.shader.name;
public static implicit operator Material(MaterialProxy proxy) => proxy.m_Material;
public static implicit operator MaterialProxy(Material material) =>
new MaterialProxy(material, AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(material)));
public override string ToString() => m_Material.ToString();
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 88cd98f0807c4d0ea90990b27cc42068
timeCreated: 1616489074
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ac2f288d1072e2947a1704bffbd5cdee
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,31 @@
using System.Collections.Generic;
using System.ComponentModel;
using Unity.ProjectAuditor.Editor;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal.ProjectAuditor
{
[Category("Global Settings")]
class DefaultVolumeProfileAnalyzer : IRenderingSettingsAnalyzer
{
internal const string URP0202 = nameof(URP0202);
public Descriptor Descriptor { get; } = new Descriptor(
URP0202,
"URP: Default Volume Profile is not assigned",
Areas.Quality,
"The default Volume Profile is not assigned in Graphics Settings. Without a default volume profile, post-processing and other volume-based effects may not work correctly. This setting is configured in Project Settings > Graphics > URP.",
"Assign a default Volume Profile in Project Settings > Graphics > URP section"
);
public IEnumerable<RenderingSettingsIssue> EnumerateIssues()
{
var settings = GraphicsSettings.GetRenderPipelineSettings<URPDefaultVolumeProfileSettings>();
// If settings is null, we're not in URP or settings haven't been initialized
if (settings != null && settings.volumeProfile == null)
yield return new RenderingSettingsIssue(URP0202);
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 9c1c7f7878446834aab8c4fd0a79397e
@@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using Unity.ProjectAuditor.Editor;
using UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal.ProjectAuditor
{
[Category("Renderer")]
class DuplicateRendererFeaturesAnalyzer : IRenderingSettingsAnalyzer
{
internal const string URP0103 = nameof(URP0103);
public Descriptor Descriptor { get; } = new Descriptor(
URP0103,
"URP: Duplicate features with DisallowMultipleRendererFeature",
Areas.Quality,
"Some Renderer Features are marked with [DisallowMultipleRendererFeature] attribute but appear multiple times in a renderer. This can cause unexpected behavior or rendering issues.",
"Remove duplicate renderer features that are marked with DisallowMultipleRendererFeature attribute"
)
{
DefaultSeverity = Severity.Major,
};
public IEnumerable<RenderingSettingsIssue> EnumerateIssues()
{
var rendererDataAssets = URPProjectAuditorUtilities.GetAllRendererDataAssets();
foreach (var rendererData in rendererDataAssets)
{
if (rendererData == null || rendererData.rendererFeatures == null)
continue;
var featureTypeCounts = new Dictionary<Type, int>();
foreach (var feature in rendererData.rendererFeatures)
{
if (feature == null)
continue;
var featureType = feature.GetType();
var attribute = featureType.GetCustomAttribute<DisallowMultipleRendererFeature>();
if (attribute != null)
{
if (!featureTypeCounts.ContainsKey(featureType))
featureTypeCounts[featureType] = 0;
featureTypeCounts[featureType]++;
if (featureTypeCounts[featureType] > 1)
yield return new RenderingSettingsIssue(URP0103); // Found duplicate
}
}
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: c2f338207dfcc51409b62af3ad45954d
@@ -0,0 +1,41 @@
using System.Collections.Generic;
using System.ComponentModel;
using Unity.ProjectAuditor.Editor;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal.ProjectAuditor
{
[Category("Global Settings")]
class GlobalSettingsAssetAnalyzer : IRenderingSettingsAnalyzer
{
internal const string URP0201 = nameof(URP0201);
public Descriptor Descriptor { get; } = new Descriptor(
URP0201,
"URP: URP Global Settings Asset is not assigned",
Areas.Quality,
"The Universal Render Pipeline Global Settings asset is not assigned or is invalid. Global Settings contains important configuration such as rendering layer names and shader stripping settings. Without it, some URP features may not work correctly.",
"Ensure URP Global Settings asset"
)
{
DefaultSeverity = Severity.Major,
Fixer = FixGlobalSettings,
};
public IEnumerable<RenderingSettingsIssue> EnumerateIssues()
{
var settings = GraphicsSettings.GetRenderPipelineSettings<URPDefaultVolumeProfileSettings>();
// If settings is null, we're not in URP or settings haven't been initialized
if (UniversalRenderPipelineGlobalSettings.instance == null)
yield return new RenderingSettingsIssue(URP0201);
}
public static bool FixGlobalSettings(ReportItem issue, AnalysisParams context)
{
UniversalRenderPipelineGlobalSettings.Ensure();
return true;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: b9a1cfdb2f471544d93cc82d90cd225e
@@ -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 HDREnabledValidation : IRenderingSettingsAnalyzer
{
internal const string URP0004 = nameof(URP0004);
public Descriptor Descriptor { get; } = new Descriptor(
URP0004,
"URP: HDR is enabled",
Areas.GPU | Areas.Quality,
"<b>HDR</b> (High Dynamic Range) is enabled in a URP Asset for mobile platforms. HDR rendering can be very intensive on low-end mobile GPUs.",
"Disable <b>HDR</b> in the URP Asset."
)
{
Platforms = new SerializableEnum<BuildTarget>[] {
new(BuildTarget.Android),
new(BuildTarget.iOS),
new(BuildTarget.Switch)
},
MessageFormat = "URP: HDR is enabled in {0}.asset in {1}",
Fixer = FixHDR
};
public IEnumerable<RenderingSettingsIssue> EnumerateIssues()
{
// Check default render pipeline
if (GraphicsSettings.defaultRenderPipeline is UniversalRenderPipelineAsset urpAsset && urpAsset.supportsHDR)
{
yield return new RenderingSettingsIssue(URP0004, assetName: urpAsset.name);
}
using (UnityEngine.Pool.ListPool<(int level, string name)>.Get(out var tmp))
{
QualitySettings.ForEach((level, name) =>
{
if (QualitySettings.renderPipeline is UniversalRenderPipelineAsset qualityUrpAsset && qualityUrpAsset.supportsHDR)
{
tmp.Add((level, name));
}
});
foreach (var (level, name) in tmp)
yield return new RenderingSettingsIssue(URP0004, level, name);
}
}
public static bool FixHDR(ReportItem issue, AnalysisParams context)
{
bool fixedAny = false;
var configuredAssets = GraphicsSettings.allConfiguredRenderPipelines;
foreach (var asset in configuredAssets)
{
if (asset is UniversalRenderPipelineAsset urpAsset && urpAsset.supportsHDR)
{
urpAsset.supportsHDR = false;
EditorUtility.SetDirty(urpAsset);
fixedAny = true;
}
}
return fixedAny;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: eeea0853b4ef4054ea6842de40031a6d
@@ -0,0 +1,37 @@
using System.Collections.Generic;
using System.ComponentModel;
using Unity.ProjectAuditor.Editor;
namespace UnityEditor.Rendering.Universal.ProjectAuditor
{
[Category("Renderer")]
class InactiveRendererFeaturesAnalyzer : IRenderingSettingsAnalyzer
{
internal const string URP0104 = nameof(URP0104);
public Descriptor Descriptor { get; } = new Descriptor(
URP0104,
"URP: Inactive renderer features detected",
Areas.Quality | Areas.Memory,
"One or more renderer data assets contain inactive renderer features. Consider removing them if they are not needed.",
"Remove inactive renderer features or activate them if they should be used"
);
public IEnumerable<RenderingSettingsIssue> EnumerateIssues()
{
var rendererDataAssets = URPProjectAuditorUtilities.GetAllRendererDataAssets();
foreach (var rendererData in rendererDataAssets)
{
if (rendererData == null || rendererData.rendererFeatures == null)
continue;
foreach (var feature in rendererData.rendererFeatures)
{
if (feature != null && !feature.isActive)
yield return new RenderingSettingsIssue(URP0104);
}
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 1088471fc1e09ab4cba93811ddb5300c
@@ -0,0 +1,82 @@
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("Renderer")]
class InvalidRendererIndexAnalyzer : IRenderingSettingsAnalyzer
{
internal const string URP0101 = nameof(URP0101);
public Descriptor Descriptor { get; } = new Descriptor(
URP0101,
"URP: Invalid renderer index assigned",
Areas.Quality,
"One or more URP assets have a default renderer index that is out of bounds for their renderer list. This will cause rendering failures as the pipeline cannot find a valid renderer to use.",
"Check the default renderer index in each URP asset and ensure it's within the valid range of available renderers"
)
{
DefaultSeverity = Severity.Major,
MessageFormat = "URP: Invalid renderer index assigned in {0}.asset in {1}",
};
public IEnumerable<RenderingSettingsIssue> EnumerateIssues()
{
// Check default render pipeline
if (GraphicsSettings.defaultRenderPipeline is UniversalRenderPipelineAsset urpAsset && !IsRendererIndexValid(urpAsset))
{
if (!IsRendererIndexValid(urpAsset))
yield return new RenderingSettingsIssue(URP0101, assetName:urpAsset.name);
}
using (UnityEngine.Pool.ListPool<(int level, string name)>.Get(out var tmp))
{
QualitySettings.ForEach((level, name) =>
{
if (QualitySettings.renderPipeline is UniversalRenderPipelineAsset qualityUrpAsset && !IsRendererIndexValid(qualityUrpAsset))
{
tmp.Add((level, name));
}
});
foreach (var (level, name) in tmp)
yield return new RenderingSettingsIssue(URP0101, level, name);
}
}
static bool IsRendererIndexValid(UniversalRenderPipelineAsset urpAsset)
{
if (urpAsset == null)
return true; // Nothing to check
// Get the renderer data list
var rendererDataList = urpAsset.m_RendererDataList;
if (rendererDataList == null || rendererDataList.Length == 0)
{
// If there are no renderers, any index is invalid
return false;
}
// Get the default renderer index
int defaultRendererIndex = urpAsset.m_DefaultRendererIndex;
// Check if the index is out of bounds
if (defaultRendererIndex < 0 || defaultRendererIndex >= rendererDataList.Length)
{
return false;
}
// Check if the renderer at that index is null
if (rendererDataList[defaultRendererIndex] == null)
{
return false;
}
return true;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 087033380c2ca7e40b7290d8b763bab7
@@ -0,0 +1,37 @@
using System.Collections.Generic;
using System.ComponentModel;
using Unity.ProjectAuditor.Editor;
using UnityEngine;
namespace UnityEditor.Rendering.Universal.ProjectAuditor
{
[Category("Other")]
class LinearColorSpaceAnalyzer : IRenderingSettingsAnalyzer
{
internal const string URP0401 = nameof(URP0401);
public Descriptor Descriptor { get; } = new Descriptor(
URP0401,
"URP: Linear Color Space should be used",
Areas.Quality,
"The project is using Gamma color space. Linear color space is required for physically accurate rendering in URP. Gamma color space can cause incorrect lighting calculations and color artifacts.",
"Change Color Space to Linear in Project Settings > Player > Other Settings > Color Space"
)
{
Fixer = FixColorSpace,
DefaultSeverity = Severity.Major,
};
public IEnumerable<RenderingSettingsIssue> EnumerateIssues()
{
if (PlayerSettings.colorSpace != ColorSpace.Linear)
yield return new RenderingSettingsIssue(URP0401);
}
public static bool FixColorSpace(ReportItem issue, AnalysisParams context)
{
PlayerSettings.colorSpace = ColorSpace.Linear;
return true;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 9e086170170d88246a57c1d20b829abb
@@ -0,0 +1,85 @@
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 MSAAValidation : IRenderingSettingsAnalyzer
{
internal const string URP0005 = nameof(URP0005);
public Descriptor Descriptor { get; } = new Descriptor(
URP0005,
"URP: MSAA is set to 4x or 8x",
Areas.GPU | Areas.Quality,
"<b>Anti Aliasing (MSAA)</b> is set to <b>4x</b> or <b>8x</b> in a URP Asset for mobile platforms. MSAA 4x/8x rendering can be intensive on low-end mobile GPUs.",
"Decrease <b>Anti Aliasing (MSAA)</b> value to <b>2x</b> in the URP Asset."
)
{
Platforms = new SerializableEnum<BuildTarget>[] {
new(BuildTarget.Android),
new(BuildTarget.iOS),
new(BuildTarget.Switch)
},
MessageFormat = "URP: MSAA is set to 4x or 8x in {0}.asset in {1}",
Fixer = FixMSAA
};
internal static int GetMsaaSampleCountSetting(RenderPipelineAsset renderPipeline)
{
return renderPipeline is UniversalRenderPipelineAsset urpAsset ? urpAsset.msaaSampleCount : -1;
}
public IEnumerable<RenderingSettingsIssue> EnumerateIssues()
{
// Check default render pipeline
if (GetMsaaSampleCountSetting(GraphicsSettings.defaultRenderPipeline) >= 4)
{
yield return new RenderingSettingsIssue(URP0005);
}
using (UnityEngine.Pool.ListPool<(int level, string name)>.Get(out var tmp))
{
QualitySettings.ForEach((level, name) =>
{
if (GetMsaaSampleCountSetting(QualitySettings.renderPipeline) >= 4)
{
tmp.Add((level, name));
}
});
foreach (var (level, name) in tmp)
yield return new RenderingSettingsIssue(URP0005, level, name);
}
}
public static bool FixMSAA(ReportItem issue, AnalysisParams context)
{
bool fixedAny = false;
if (GetMsaaSampleCountSetting(GraphicsSettings.defaultRenderPipeline) >= 4)
{
(GraphicsSettings.defaultRenderPipeline as UniversalRenderPipelineAsset).msaaSampleCount = 2;
EditorUtility.SetDirty(GraphicsSettings.defaultRenderPipeline);
fixedAny = true;
}
QualitySettings.ForEach(() =>
{
if (GetMsaaSampleCountSetting(QualitySettings.renderPipeline) >= 4)
{
(QualitySettings.renderPipeline as UniversalRenderPipelineAsset).msaaSampleCount = 2;
EditorUtility.SetDirty(QualitySettings.renderPipeline);
fixedAny = true;
}
});
return fixedAny;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 0a19c63278396994eb3b7ae5114089d2
@@ -0,0 +1,66 @@
using System.Collections.Generic;
using System.ComponentModel;
using Unity.ProjectAuditor.Editor;
using UnityEngine;
namespace UnityEditor.Rendering.Universal.ProjectAuditor
{
[Category("Other")]
class UnmigratedMaterialsAnalyzer : IRenderingSettingsAnalyzer
{
internal const string URP0402 = nameof(URP0402);
public Descriptor Descriptor { get; } = new Descriptor(
URP0402,
"URP: Materials: Materials using Built-in shaders detected",
Areas.Quality | Areas.GPU,
"One or more materials in the project are still using Built-in render pipeline shaders. These materials should be converted to use URP-optimized shaders for better performance and compatibility. Use the Render Pipeline Converter (Window > Rendering > Render Pipeline Converter) to upgrade materials.",
"Convert materials to URP using Window > Rendering > Render Pipeline Converter"
);
public IEnumerable<RenderingSettingsIssue> EnumerateIssues()
{
if (!CheckForUnmigratedMaterials())
yield return new RenderingSettingsIssue(URP0402);
}
static bool CheckForUnmigratedMaterials()
{
// Get all built-in to URP upgraders
var upgraders = BuiltInToURP3DMaterialUpgrader.FetchMaterialUpgraders();
if (upgraders == null || upgraders.Count == 0)
return true; // No upgraders defined, consider valid
// Build a set of old shader paths that should be upgraded
var builtInShaderPaths = new HashSet<string>();
foreach (var upgrader in upgraders)
{
if (!string.IsNullOrEmpty(upgrader.OldShaderPath))
{
builtInShaderPaths.Add(upgrader.OldShaderPath);
}
}
if (builtInShaderPaths.Count == 0)
return true; // No old shaders to check
// Find all materials in the project
var materials = AssetDatabaseHelper.FindAssets<Material>();
foreach (var material in materials)
{
if (material != null && material.shader != null)
{
var shaderName = material.shader.name;
// Check if this material is using a built-in shader that should be upgraded
if (builtInShaderPaths.Contains(shaderName))
{
return false; // Found an unmigrated material
}
}
}
return true; // All materials are using URP shaders
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 11d0515733dd0344aa0a2e9979b11fd6
@@ -0,0 +1,49 @@
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 MissingAssignedRenderPipeline : IRenderingSettingsAnalyzer
{
internal const string URP0001 = nameof(URP0001);
public Descriptor Descriptor { get; } = new Descriptor(
URP0001,
"URP: Missing URP asset assigned",
Areas.Quality,
"Missing URP asset assigned. When a quality level has no render pipeline asset set, it will fall back to the default Graphics Settings asset. This can cause inconsistent rendering behavior across quality levels or fallback to Built-in Render Pipeline",
"Assign a URP asset to all quality levels in Project Settings > Quality and a Default Render Pipeline in Project Settings > Graphics."
)
{
MessageFormat = "URP: Missing URP asset assigned {0} in {1}"
};
public IEnumerable<RenderingSettingsIssue> EnumerateIssues()
{
// Check default render pipeline
if (GraphicsSettings.defaultRenderPipeline is not UniversalRenderPipelineAsset urpAsset)
{
yield return new RenderingSettingsIssue(URP0001);
}
using (UnityEngine.Pool.ListPool<(int level, string name)>.Get(out var tmp))
{
QualitySettings.ForEach((level, name) =>
{
if (QualitySettings.renderPipeline is not UniversalRenderPipelineAsset qualityUrpAsset)
{
tmp.Add((level, name));
}
});
foreach (var (level, name) in tmp)
yield return new RenderingSettingsIssue(URP0001, level, name);
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 038072bcd540e8d4b8712ce4a32dafbb
@@ -0,0 +1,45 @@
using System.Collections.Generic;
using System.ComponentModel;
using Unity.ProjectAuditor.Editor;
namespace UnityEditor.Rendering.Universal.ProjectAuditor
{
[Category("Renderer")]
class MissingRendererFeaturesAnalyzer : IRenderingSettingsAnalyzer
{
internal const string URP0102 = nameof(URP0102);
public Descriptor Descriptor { get; } = new Descriptor(
URP0102,
"URP: Missing or null renderer features",
Areas.Quality,
"One or more renderer data assets contain null or missing renderer features. This typically happens when scripts are deleted or there are compilation errors. This can cause rendering issues.",
"Open the renderer data asset and remove the missing features, or restore the missing scripts"
)
{
DefaultSeverity = Severity.Major,
};
public IEnumerable<RenderingSettingsIssue> EnumerateIssues()
{
if (!CheckForMissingFeatures())
yield return new RenderingSettingsIssue(URP0102);
}
static bool CheckForMissingFeatures()
{
var rendererDataAssets = URPProjectAuditorUtilities.GetAllRendererDataAssets();
foreach (var rendererData in rendererDataAssets)
{
if (rendererData == null)
continue;
if (rendererData.rendererFeatures != null && rendererData.rendererFeatures.Contains(null))
return false; // Found missing features
}
return true; // No missing features
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 1cca62a04dbbcc4428357d5bd3335140
@@ -0,0 +1,87 @@
using System;
using System.Collections.Generic;
using Unity.ProjectAuditor.Editor;
using Unity.ProjectAuditor.Editor.Core;
using UnityEngine;
namespace UnityEditor.Rendering.Universal.ProjectAuditor
{
internal struct RenderingSettingsIssue
{
public string id { get; set; }
public int? qualityLevel { get; set; }
public string assetName { get; set; }
public RenderingSettingsIssue(string id, int? qualityLevel = null, string assetName = null)
{
this.id = id;
this.qualityLevel = qualityLevel;
this.assetName = assetName;
}
}
internal interface IRenderingSettingsAnalyzer
{
public Descriptor Descriptor { get; }
public IEnumerable<RenderingSettingsIssue> EnumerateIssues();
}
partial class SettingsAnalyzer : SettingsModuleAnalyzer
{
List<IRenderingSettingsAnalyzer> m_Entries = new List<IRenderingSettingsAnalyzer>();
public SettingsAnalyzer()
{
foreach (var types in TypeCache.GetTypesDerivedFrom<IRenderingSettingsAnalyzer>())
{
m_Entries.Add(Activator.CreateInstance(types) as IRenderingSettingsAnalyzer);
}
// Sort by Descriptor.Id (alphabetically)
m_Entries.Sort((a, b) => string.Compare(a.Descriptor.Id, b.Descriptor.Id, StringComparison.Ordinal));
}
public override void Initialize(Action<Descriptor> registerDescriptor)
{
foreach (var entry in m_Entries)
{
registerDescriptor(entry.Descriptor);
}
}
static ReportItem CreateAssetSettingIssue(AnalysisContext context, int? qualityLevel, string name, string id)
{
string assetLocation = qualityLevel == null ? "Default Rendering Pipeline Asset" :
$"Rendering Pipeline Asset on Quality Level: '{QualitySettings.names[qualityLevel.Value]}'";
return context.CreateIssue(IssueCategory.ProjectSetting, id, name, assetLocation)
.WithCustomProperties(new object[] { qualityLevel })
.WithLocation(qualityLevel == null ? "Project/Graphics" : "Project/Quality");
}
static ReportItem CreateIssue(AnalysisContext context, string id)
{
return context.CreateIssue(IssueCategory.ProjectSetting, id)
.WithLocation("Project/Graphics");
}
public override IEnumerable<ReportItem> Analyze(SettingsAnalysisContext context)
{
foreach (var entry in m_Entries)
{
if (!context.IsDescriptorEnabled(entry.Descriptor))
continue;
foreach (var issue in entry.EnumerateIssues())
{
if (string.IsNullOrEmpty(issue.id))
throw new InvalidOperationException($"Issue id cannot be null or empty for {entry.Descriptor.Id}");
if (issue.qualityLevel == null && string.IsNullOrEmpty(issue.assetName))
yield return CreateIssue(context, issue.id);
else
yield return CreateAssetSettingIssue(context, issue.qualityLevel, issue.assetName, issue.id);
}
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 381d0513472fded4ead64160058a7490
@@ -0,0 +1,76 @@
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 NoRendererAssignedAnalyzer : IRenderingSettingsAnalyzer
{
internal const string URP0002 = nameof(URP0002);
public Descriptor Descriptor { get; } = new Descriptor(
URP0002,
"URP: URP Asset has no renderer assigned",
Areas.Quality,
"One or more Universal Render Pipeline assets have no renderers assigned. Without a renderer, the pipeline cannot render anything and will result in a blank screen or errors.",
"Assign at least one renderer to each URP asset in Graphics and Quality Settings"
)
{
DefaultSeverity = Severity.Major,
};
private bool CheckRenderers(UniversalRenderPipelineAsset urpAsset)
{
bool allHaveRenderers = true;
if (urpAsset.m_RendererDataList == null || urpAsset.m_RendererDataList.Length == 0)
{
allHaveRenderers = false;
}
else
{
// Check if all entries are null
bool hasValidRenderer = false;
foreach (var renderer in urpAsset.m_RendererDataList)
{
if (renderer != null)
{
hasValidRenderer = true;
break;
}
}
if (!hasValidRenderer)
allHaveRenderers = false;
}
return allHaveRenderers;
}
public IEnumerable<RenderingSettingsIssue> EnumerateIssues()
{
if (GraphicsSettings.defaultRenderPipeline is UniversalRenderPipelineAsset urpAsset)
{
if (!CheckRenderers(urpAsset))
yield return new RenderingSettingsIssue(URP0002);
}
using (UnityEngine.Pool.ListPool<(int level, string name)>.Get(out var tmp))
{
QualitySettings.ForEach((level, name) =>
{
if (QualitySettings.renderPipeline is UniversalRenderPipelineAsset qualityUrpAsset)
{
if (!CheckRenderers(qualityUrpAsset))
tmp.Add((level, name));
}
});
foreach (var (level, name) in tmp)
yield return new RenderingSettingsIssue(URP0002, level, name);
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a6902e65c09c05348be988c7c41ec33e
@@ -0,0 +1,76 @@
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("SRP and Static Batching")]
class SRPBatcherAnalyzer : IRenderingSettingsAnalyzer
{
internal const string URP0301 = nameof(URP0301);
public Descriptor Descriptor { get; } = new Descriptor(
URP0301,
"URP: SRP Batcher should be enabled",
Areas.GPU | Areas.Quality,
"Ensures that the Scriptable Render Pipeline Batcher is enabled on the URP Assets configured on Graphics and Quality Settings. This improves rendering performance significantly in many projects.",
"Enable the SRP Batcher on the used URP assets on Graphics and Quality Settings"
)
{
Fixer = FixSRPBatcher,
MessageFormat = "URP: SRPBatcher disabled in {0}.asset in {1}",
};
public IEnumerable<RenderingSettingsIssue> EnumerateIssues()
{
// Check default render pipeline
if (GraphicsSettings.defaultRenderPipeline is UniversalRenderPipelineAsset urpAsset && !urpAsset.useSRPBatcher)
{
yield return new RenderingSettingsIssue(URP0301, assetName: urpAsset.name);
}
using (UnityEngine.Pool.ListPool<(int level, string name)>.Get(out var tmp))
{
QualitySettings.ForEach((level, name) =>
{
if (QualitySettings.renderPipeline is UniversalRenderPipelineAsset urpAsset && !urpAsset.useSRPBatcher)
{
tmp.Add((level, name));
}
});
foreach (var (level, name) in tmp)
yield return new RenderingSettingsIssue(URP0301, level, name);
}
}
public static bool FixSRPBatcher(ReportItem issue, AnalysisParams context)
{
bool fixedAny = false;
// Fix default render pipeline in Graphics Settings
if (GraphicsSettings.defaultRenderPipeline is UniversalRenderPipelineAsset defaultUrpAsset)
{
defaultUrpAsset.useSRPBatcher = true;
EditorUtility.SetDirty(defaultUrpAsset);
fixedAny = true;
}
// Fix all quality level render pipelines
QualitySettings.ForEach(() =>
{
if (QualitySettings.renderPipeline is UniversalRenderPipelineAsset urpAsset)
{
urpAsset.useSRPBatcher = true;
EditorUtility.SetDirty(urpAsset);
fixedAny = true;
}
});
return fixedAny;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: d1707b3fb9f15f24fa86f2640a14e64f
@@ -0,0 +1,61 @@
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("SRP and Static Batching")]
class StaticBatchingWithSRPBatcherAnalyzer : IRenderingSettingsAnalyzer
{
internal const string URP0302 = nameof(URP0302);
public Descriptor Descriptor { get; } = new Descriptor(
URP0302,
"URP: Static Batching conflicts with SRP Batcher",
Areas.GPU | Areas.Quality,
"Static Batching is enabled while SRP Batcher is also enabled. Static Batching prevents the SRP Batcher from working efficiently, reducing performance. When using SRP Batcher, Static Batching should be disabled.",
"Disable Static Batching in Project Settings > Player > Other Settings > Static Batching"
)
{
Fixer = FixStaticBatching,
MessageFormat = "URP: Static Batching conflicts with SRP Batcher enabled in {0}.asset in {1}",
};
public IEnumerable<RenderingSettingsIssue> EnumerateIssues()
{
bool staticBatchingEnabled = PlayerSettings.GetStaticBatchingForPlatform(EditorUserBuildSettings.activeBuildTarget);
if (!staticBatchingEnabled)
yield break; // Static Batching is disabled, no issue
// Check default render pipeline
if (GraphicsSettings.defaultRenderPipeline is UniversalRenderPipelineAsset urpAsset && urpAsset.useSRPBatcher)
{
yield return new RenderingSettingsIssue(URP0302, assetName: urpAsset.name);
}
using (UnityEngine.Pool.ListPool<(int level, string name)>.Get(out var tmp))
{
QualitySettings.ForEach((level, name) =>
{
if (QualitySettings.renderPipeline is UniversalRenderPipelineAsset urpAsset && urpAsset.useSRPBatcher)
{
tmp.Add((level, name));
}
});
foreach (var (level, name) in tmp)
yield return new RenderingSettingsIssue(URP0302, level, name);
}
}
public static bool FixStaticBatching(ReportItem issue, AnalysisParams context)
{
PlayerSettings.SetStaticBatchingForPlatform(EditorUserBuildSettings.activeBuildTarget, false);
return true;
}
}
}
@@ -0,0 +1,50 @@
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 URPAssetLastVersionValidation : IRenderingSettingsAnalyzer
{
internal const string URP0003 = nameof(URP0003);
public Descriptor Descriptor { get; } = new Descriptor(
URP0003,
"URP: URP Asset are not at latest version",
Areas.Quality,
"One or more Universal Render Pipeline assets have no been upgraded to latest version.",
"Open the asset in the inspector to upgrade them to latest version."
)
{
DefaultSeverity = Severity.Major,
MessageFormat = "URP: URP Asset is not at latest version in {0}.asset in {1}",
};
public IEnumerable<RenderingSettingsIssue> EnumerateIssues()
{
// Check default render pipeline
if (GraphicsSettings.defaultRenderPipeline is UniversalRenderPipelineAsset urpAsset && !urpAsset.IsAtLastVersion())
{
yield return new RenderingSettingsIssue(URP0003);
}
using (UnityEngine.Pool.ListPool<(int level, string name)>.Get(out var tmp))
{
QualitySettings.ForEach((level, name) =>
{
if (QualitySettings.renderPipeline is UniversalRenderPipelineAsset urpAsset && !urpAsset.IsAtLastVersion())
{
tmp.Add((level, name));
}
});
foreach (var (level, name) in tmp)
yield return new RenderingSettingsIssue(URP0003, level, name);
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 0c9e13beeab0e3c4db1b5bd931db203a
@@ -0,0 +1,44 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal.ProjectAuditor
{
internal static class URPProjectAuditorUtilities
{
public static List<ScriptableRendererData> GetAllRendererDataAssets()
{
var assets = new List<ScriptableRendererData>();
// Get from Graphics Settings
if (GraphicsSettings.defaultRenderPipeline is UniversalRenderPipelineAsset urpAsset)
{
var rendererDataList = urpAsset.m_RendererDataList;
if (rendererDataList != null)
{
assets.AddRange(rendererDataList);
}
}
// Get from Quality Settings
QualitySettings.ForEach(() =>
{
if (QualitySettings.renderPipeline is UniversalRenderPipelineAsset qualityUrpAsset)
{
var rendererDataList = qualityUrpAsset.m_RendererDataList;
if (rendererDataList != null)
{
foreach (var data in rendererDataList)
{
if (data != null && !assets.Contains(data))
assets.Add(data);
}
}
}
});
return assets;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 37783e313f8379f4eb88183bbd9d2404