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,972 @@
using System;
using System.Collections.Generic;
using Codice.Client.Common.Threading;
using Codice.CM.Client.Differences;
using Codice.CM.Client.Differences.Graphic;
using MergetoolGui;
using PlasticGui;
using Unity.PlasticSCM.Editor.Diff.Asset.Diff.Meta;
using Unity.PlasticSCM.Editor.Diff.Asset.Common.Property;
using Unity.PlasticSCM.Editor.Diff.Asset.Diff.Property;
using Unity.PlasticSCM.Editor.Diff.Asset.Diff.UnityObject;
using Unity.PlasticSCM.Editor.Diff.Asset.Diff.Filtering;
using Unity.PlasticSCM.Editor.Diff.Asset.Diff.Search;
using Unity.PlasticSCM.Editor.Diff.Purged;
using Unity.PlasticSCM.Editor.Diff.Text;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
using XDiffGui;
using Unity.PlasticSCM.Editor.Diff.Asset.Common;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff
{
internal class AssetDiffControl : VisualElement, IBigFilePanelListener
{
internal AssetDiffControl(
IBigFileDownloader bigFileDownloader,
IBigFileChecker bigFileChecker,
Action onViewAsTextDiff)
{
mBigFileDownloader = bigFileDownloader;
mBigFileChecker = bigFileChecker;
mOnViewAsTextDiff = onViewAsTextDiff;
CreateGUI();
RegisterCallback<AttachToPanelEvent>(_ =>
{
AssetReloadNotifier.AssetsChanged += OnAssetsChanged;
EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
});
RegisterCallback<DetachFromPanelEvent>(_ =>
{
AssetReloadNotifier.AssetsChanged -= OnAssetsChanged;
EditorApplication.playModeStateChanged -= OnPlayModeStateChanged;
});
}
internal void ShowData(DiffViewerData diffData)
{
if (diffData == null)
return;
mDiffViewerData = diffData;
DisplayCurrentData(isReload: false);
}
void DisplayCurrentData(bool isReload)
{
DiffViewerData diffData = mDiffViewerData;
string leftContributor;
string rightContributor;
SymbolicNameParser.GetContributorSpecs(diffData.Left.SymbolicName,
diffData.Right.SymbolicName, out leftContributor, out rightContributor);
mContributorsHeaderPanel.SetNames(leftContributor, rightContributor);
mMessagePanel.Hide();
ReplaceMainView(mContentPanel);
if (BigFileDiffCalculator.IsBigFileDiff(diffData, mBigFileDownloader, mBigFileChecker))
{
ShowBigFileMessage();
return;
}
if (diffData.Left?.IsPurged == true || diffData.Right?.IsPurged == true)
{
ShowPurgedRevision(diffData);
return;
}
ShowAssetDiff(diffData.Left.File, diffData.Right.File, isReload);
}
void OnAssetsChanged(HashSet<string> changedFullPaths)
{
if (mDiffViewerData == null)
return;
if (!AssetReloadNotifier.IsWatchedPath(
mDiffViewerData.Left?.File, changedFullPaths)
&& !AssetReloadNotifier.IsWatchedPath(
mDiffViewerData.Right?.File, changedFullPaths))
return;
DisplayCurrentData(isReload: true);
}
// Entering or exiting play mode causes Unity to drop the objects we
// loaded into mObjectDiffs via LoadSerializedFileAndForget. Without
// a fresh load the next re-bind would render every header as a
// fallback ("Unknown" / generic file icon), since the underlying
// native objects are gone even though the C# refs remain.
void OnPlayModeStateChanged(PlayModeStateChange state)
{
if (mDiffViewerData == null)
return;
if (state != PlayModeStateChange.EnteredEditMode
&& state != PlayModeStateChange.EnteredPlayMode)
return;
DisplayCurrentData(isReload: true);
}
void ShowAssetDiff(string leftFile, string rightFile, bool isReload)
{
ReplaceView(mListView);
mVisibleRows.Clear();
ExpansionSnapshot previousCache = isReload
? SnapshotExpansionState()
: null;
bool isMetaDiff = MetaPath.IsMetaPath(leftFile);
mObjectDiffs = isMetaDiff ?
MetaFileDiffs.BuildDiffData(leftFile, rightFile) :
UnityObjectDiffs.BuildDiffData(leftFile, rightFile);
UpdateDataLossBanner(mObjectDiffs);
ApplyExpansionState(previousCache);
UpdateAvailableFilters(isMetaDiff);
RebuildVisibleRows();
}
void UpdateAvailableFilters(bool isMetaDiff)
{
if (isMetaDiff)
{
mDiffToolbarPanel.UpdateAvailableFilters(null, null, show: false);
return;
}
mDiffToolbarPanel.UpdateAvailableFilters(
ObjectDiffOptions.ExtractGameObjects(mObjectDiffs, GetGameObjectIcon),
ObjectDiffOptions.ExtractTypes(mObjectDiffs, GetIconForObject),
show: true);
}
static UnityEngine.Texture GetGameObjectIcon(ObjectDiff diff)
{
GameObject go = diff.GetGameObject();
if (go != null)
return EditorGUIUtility.ObjectContent(go, typeof(GameObject)).image;
return GetIconForObject(diff);
}
static UnityEngine.Texture GetIconForObject(ObjectDiff diff)
{
UnityEngine.Object obj = diff.SrcObject ?? diff.DstObject;
if (obj == null)
return null;
return EditorGUIUtility.ObjectContent(obj, obj.GetType()).image;
}
ExpansionSnapshot SnapshotExpansionState()
{
ExpansionSnapshot snapshot = new ExpansionSnapshot();
foreach (ObjectDiff obj in mObjectDiffs)
{
AddIfDeviatesFromDefault(snapshot.Objects, BuildObjectKey(obj), obj);
if (obj.ComponentDiffs == null)
continue;
for (int i = 0; i < obj.ComponentDiffs.Count; i++)
{
ObjectDiff comp = obj.ComponentDiffs[i];
AddIfDeviatesFromDefault(
snapshot.Objects, BuildComponentKey(obj, comp, i), comp);
}
}
foreach (string fullKey in mCollapsedGroups)
snapshot.CollapsedGroups.Add(fullKey);
return snapshot;
}
void AddIfDeviatesFromDefault(
Dictionary<string, bool> snapshot, string key, ObjectDiff obj)
{
bool isExpanded = mExpandedObjects.Contains(obj.GetObjectId());
if (isExpanded == DefaultExpand(obj))
return;
snapshot[key] = isExpanded;
}
void ApplyExpansionState(ExpansionSnapshot previousCache)
{
mExpandedObjects.Clear();
mCollapsedGroups.Clear();
foreach (ObjectDiff obj in mObjectDiffs)
{
if (ShouldExpand(previousCache?.Objects, BuildObjectKey(obj), DefaultExpand(obj)))
mExpandedObjects.Add(obj.GetObjectId());
if (obj.ComponentDiffs == null)
continue;
for (int i = 0; i < obj.ComponentDiffs.Count; i++)
{
ObjectDiff comp = obj.ComponentDiffs[i];
if (ShouldExpand(previousCache?.Objects, BuildComponentKey(obj, comp, i), DefaultExpand(comp)))
mExpandedObjects.Add(comp.GetObjectId());
}
}
if (previousCache == null)
return;
foreach (string fullKey in previousCache.CollapsedGroups)
mCollapsedGroups.Add(fullKey);
}
static bool ShouldExpand(
Dictionary<string, bool> previousCache, string key, bool defaultExpand)
{
if (previousCache != null && previousCache.TryGetValue(key, out bool wasExpanded))
return wasExpanded;
return defaultExpand;
}
static bool DefaultExpand(ObjectDiff obj)
{
bool hasComponents = obj.ComponentDiffs != null && obj.ComponentDiffs.Count > 0;
if (hasComponents)
return true;
if (obj.DiffType != DiffType.Modified)
return false;
return obj.PropertyDiffTree != null && obj.PropertyDiffTree.Children.Count > 0;
}
static string BuildObjectKey(ObjectDiff obj)
{
return "o:" + obj.GetSrcDisplayName();
}
static string BuildComponentKey(
ObjectDiff parent, ObjectDiff comp, int index)
{
return "c:" + parent.GetSrcDisplayName() + "/" + index + ":" + comp.GetSrcDisplayName();
}
static string BuildGroupFullKey(ObjectDiff owner, string groupKey)
{
return owner.GetObjectId() + ":" + groupKey;
}
void IBigFilePanelListener.OnCalculateDifferencesButtonClick()
{
mBigFileMessagePanel.Disable();
IThreadWaiter waiter = ThreadWaiter.GetWaiter(10);
waiter.Execute(
/*threadOperationDelegate*/ delegate
{
mBigFileDownloader.DownloadFiles(mDiffViewerData, null);
},
/*afterOperationDelegate*/ delegate
{
mBigFileMessagePanel.Enable();
if (waiter.Exception != null)
{
MergetoolExceptionsHandler.DisplayException(
waiter.Exception);
return;
}
DisplayCurrentData(isReload: false);
});
}
void ShowBigFileMessage()
{
if (mBigFileMessagePanel == null)
mBigFileMessagePanel = new BigFileMessagePanel(this, false);
mBigFileMessagePanel.UpdateDisplayData(
BigFileDisplayData.Build(
mDiffViewerData, mBigFileDownloader));
mContributorsHeaderPanel.SetSeparatorsVisible(true);
ReplaceView(mBigFileMessagePanel);
}
void ShowPurgedRevision(DiffViewerData data)
{
if (mPurgedRevisionControl == null)
mPurgedRevisionControl = new PurgedRevisionControl();
mPurgedRevisionControl.ShowData(data);
ReplaceMainView(mPurgedRevisionControl);
}
void ReplaceMainView(VisualElement panel)
{
if (hierarchy.childCount == 1 && hierarchy[0] == panel)
return;
Clear();
Add(panel);
}
void ReplaceView(VisualElement view)
{
if (mCurrentView == view)
return;
if (mCurrentView != null)
mContainerPanel.Remove(mCurrentView);
mContainerPanel.Add(view);
mCurrentView = view;
}
internal void Dispose()
{
mDiffToolbarPanel.Dispose();
if (mBigFileMessagePanel != null)
mBigFileMessagePanel.Dispose();
if (mPurgedRevisionControl != null)
mPurgedRevisionControl.Dispose();
}
void RebuildVisibleRows()
{
mVisibleRows.Clear();
mKnownGroups.Clear();
mSearchIndex = PropertyDiffSearchIndex.Build(mObjectDiffs, mSearchFilter);
CollectAllGroupKeys();
int modified = 0, added = 0, removed = 0;
foreach (ObjectDiff objDiff in mObjectDiffs)
{
CountByDiffType(objDiff.DiffType, ref modified, ref added, ref removed);
if (objDiff.ComponentDiffs == null)
continue;
foreach (ObjectDiff comp in objDiff.ComponentDiffs)
CountByDiffType(comp.DiffType, ref modified, ref added, ref removed);
}
foreach (ObjectDiff objDiff in mObjectDiffs)
{
if (!PassesGameObjectFilter(objDiff))
continue;
if (mSearchIndex.IsActive)
AddObjectRowsWithSearch(objDiff);
else
AddObjectRows(objDiff);
}
mDiffToolbarPanel.UpdateFilterButtons(modified, added, removed, mDiffFilter);
mContributorsHeaderPanel.SetSeparatorsVisible(mVisibleRows.Count == 0);
if (mVisibleRows.Count == 0)
{
ShowEmptyState();
return;
}
ReplaceView(mListView);
mListView.RefreshItems();
}
void ShowEmptyState()
{
if (mEmptyStatePanel == null)
mEmptyStatePanel = new DiffMessagePanel();
mEmptyStatePanel.ShowMessage(GetEmptyStateMessage());
ReplaceView(mEmptyStatePanel);
}
string GetEmptyStateMessage()
{
bool hasSearch = !string.IsNullOrEmpty(mSearchFilter);
bool hasFilter = mDiffFilter != DiffFilter.All
|| mSelectedGameObjects != null
|| mSelectedTypes != null;
if (hasSearch || hasFilter)
return PlasticLocalization.Name.NoDiffsMatchingFilters.GetString();
return PlasticLocalization.Name.NoSerializedAssetDifferencesFound.GetString();
}
void AddObjectRows(ObjectDiff objDiff)
{
bool selfPasses = PassesDiffFilter(objDiff.DiffType)
&& PassesTypeFilter(objDiff);
bool anyChildPasses = HasVisibleChildComponent(objDiff);
if (!selfPasses && !anyChildPasses)
return;
mVisibleRows.Add(new DiffRow(
DiffRowKind.ObjectHeader, objDiff, null));
if (!mExpandedObjects.Contains(objDiff.GetObjectId()))
return;
if (selfPasses)
AddPropertyRows(objDiff, 0);
AddComponentRows(objDiff);
}
bool HasVisibleChildComponent(ObjectDiff parent)
{
if (parent.ComponentDiffs == null)
return false;
foreach (ObjectDiff comp in parent.ComponentDiffs)
{
if (!PassesDiffFilter(comp.DiffType))
continue;
if (!PassesTypeFilter(comp))
continue;
return true;
}
return false;
}
void AddComponentRows(ObjectDiff parentDiff)
{
if (parentDiff.ComponentDiffs == null)
return;
foreach (ObjectDiff compDiff in parentDiff.ComponentDiffs)
{
if (!PassesDiffFilter(compDiff.DiffType))
continue;
if (!PassesTypeFilter(compDiff))
continue;
mVisibleRows.Add(new DiffRow(
DiffRowKind.ComponentHeader, compDiff, null, 1));
if (!mExpandedObjects.Contains(compDiff.GetObjectId()))
continue;
AddPropertyRows(compDiff, 1);
}
}
void AddPropertyRows(ObjectDiff objDiff, int indentLevel)
{
PropertyDiffNode root = objDiff.PropertyDiffTree;
if (root == null)
return;
mWalker.Walk(
root.Children,
indentLevel,
IsNodeVisible,
node => BuildGroupFullKey(objDiff, node.Path),
IsGroupExpanded,
(node, indent) => AddPropertyRow(
objDiff, ToFlatDiff(node), indent),
(node, indent, fullKey) => mVisibleRows.Add(new DiffRow(
DiffRowKind.ContainerHeader, objDiff, fullKey,
node.DisplayName, node.DiffType, indent)));
}
void CollectAllGroupKeys()
{
foreach (ObjectDiff objDiff in mObjectDiffs)
{
CollectGroupKeysForOwner(objDiff);
if (objDiff.ComponentDiffs == null)
continue;
foreach (ObjectDiff comp in objDiff.ComponentDiffs)
CollectGroupKeysForOwner(comp);
}
}
void CollectGroupKeysForOwner(ObjectDiff owner)
{
if (owner.PropertyDiffTree == null)
return;
mWalker.CollectGroupKeys(
owner.PropertyDiffTree.Children,
node => BuildGroupFullKey(owner, node.Path),
key => mKnownGroups.Add(key));
}
bool IsNodeVisible(PropertyDiffNode node)
{
if (!HasFilterMatchInSubtree(node))
return false;
return mSearchIndex.IsNodeVisible(node);
}
bool HasFilterMatchInSubtree(PropertyDiffNode node)
{
switch (mDiffFilter)
{
case DiffFilter.All:
return node.DescendantDiffTypes != DiffTypeFlags.None;
case DiffFilter.Modified:
return node.HasDescendantOfType(DiffType.Modified);
case DiffFilter.Added:
return node.HasDescendantOfType(DiffType.Added);
case DiffFilter.Removed:
return node.HasDescendantOfType(DiffType.Removed);
default:
return true;
}
}
bool IsGroupExpanded(string fullKey)
{
if (mSearchIndex.IsActive)
return true;
return !mCollapsedGroups.Contains(fullKey);
}
static PropertyDiff ToFlatDiff(PropertyDiffNode node)
{
return new PropertyDiff
{
Path = node.Path,
DisplayName = node.DisplayName,
TypeTag = node.TypeTag,
DiffType = node.DiffType,
SrcValue = node.SrcValue,
DstValue = node.DstValue,
SrcTag = node.SrcTag,
DstTag = node.DstTag
};
}
void AddPropertyRow(
ObjectDiff owner, PropertyDiff propDiff, int indentLevel)
{
mVisibleRows.Add(new DiffRow(
DiffRowKind.PropertyDiff, owner, propDiff, indentLevel));
if (PropertyRow.IsTallProperty(propDiff.SrcTag)
|| PropertyRow.IsTallProperty(propDiff.DstTag))
{
mVisibleRows.Add(new DiffRow(
DiffRowKind.PropertyDiff, owner, propDiff,
indentLevel, isSpacer: true));
}
}
void AddObjectRowsWithSearch(ObjectDiff objDiff)
{
bool selfPasses = PassesDiffFilter(objDiff.DiffType)
&& PassesTypeFilter(objDiff);
bool objectNameMatches =
SearchMatcher.Contains(objDiff.GetSrcDisplayName(), mSearchFilter) ||
SearchMatcher.Contains(objDiff.GetDstDisplayName(), mSearchFilter);
bool hasOwnPropertyMatch = selfPasses && SubtreeHasSearchMatch(objDiff);
bool hasComponentMatch = HasComponentSearchMatch(objDiff);
bool selfWouldShow = selfPasses
&& (hasOwnPropertyMatch || objectNameMatches);
bool nameMatchSurfacesChildren =
objectNameMatches && HasVisibleChildComponent(objDiff);
if (!selfWouldShow && !hasComponentMatch && !nameMatchSurfacesChildren)
return;
mVisibleRows.Add(new DiffRow(
DiffRowKind.ObjectHeader, objDiff, null));
if (selfPasses && (hasOwnPropertyMatch || objectNameMatches))
AddPropertyRows(objDiff, 0);
AddComponentRowsWithSearch(objDiff, objectNameMatches);
}
void AddComponentRowsWithSearch(
ObjectDiff parentDiff, bool parentNameMatches)
{
if (parentDiff.ComponentDiffs == null)
return;
foreach (ObjectDiff compDiff in parentDiff.ComponentDiffs)
{
if (!PassesDiffFilter(compDiff.DiffType))
continue;
if (!PassesTypeFilter(compDiff))
continue;
bool compNameMatches =
SearchMatcher.Contains(
compDiff.GetSrcDisplayName(), mSearchFilter) ||
SearchMatcher.Contains(
compDiff.GetDstDisplayName(), mSearchFilter);
bool compHasPropertyMatch = SubtreeHasSearchMatch(compDiff);
if (!parentNameMatches && !compNameMatches && !compHasPropertyMatch)
continue;
mVisibleRows.Add(new DiffRow(
DiffRowKind.ComponentHeader, compDiff, null, 1));
if (compHasPropertyMatch
|| mExpandedObjects.Contains(compDiff.GetObjectId()))
{
AddPropertyRows(compDiff, 1);
}
}
}
bool SubtreeHasSearchMatch(ObjectDiff objDiff)
{
if (objDiff.PropertyDiffTree == null)
return false;
foreach (PropertyDiffNode child in objDiff.PropertyDiffTree.Children)
{
if (mSearchIndex.IsNodeVisible(child) && HasFilterMatchInSubtree(child))
return true;
}
return false;
}
bool HasComponentSearchMatch(ObjectDiff objDiff)
{
if (objDiff.ComponentDiffs == null)
return false;
foreach (ObjectDiff compDiff in objDiff.ComponentDiffs)
{
if (!PassesDiffFilter(compDiff.DiffType))
continue;
if (!PassesTypeFilter(compDiff))
continue;
if (SearchMatcher.Contains(
compDiff.GetSrcDisplayName(), mSearchFilter) ||
SearchMatcher.Contains(
compDiff.GetDstDisplayName(), mSearchFilter))
return true;
if (SubtreeHasSearchMatch(compDiff))
return true;
}
return false;
}
static void CountByDiffType(
DiffType diffType, ref int modified, ref int added, ref int removed)
{
switch (diffType)
{
case DiffType.Modified: modified++; break;
case DiffType.Added: added++; break;
case DiffType.Removed: removed++; break;
}
}
bool PassesDiffFilter(DiffType diffType)
{
switch (mDiffFilter)
{
case DiffFilter.All: return diffType != DiffType.Unchanged;
case DiffFilter.Modified: return diffType == DiffType.Modified;
case DiffFilter.Added: return diffType == DiffType.Added;
case DiffFilter.Removed: return diffType == DiffType.Removed;
default: return true;
}
}
bool PassesGameObjectFilter(ObjectDiff diff)
{
return ObjectDiffFilters.PassesGameObjectFilter(diff, mSelectedGameObjects);
}
bool PassesTypeFilter(ObjectDiff diff)
{
return ObjectDiffFilters.PassesTypeFilter(diff, mSelectedTypes);
}
void OnBindRow(VisualElement element, int index)
{
if (index < 0 || index >= mVisibleRows.Count)
return;
DiffRow row = mVisibleRows[index];
DiffRowElement rowElement = (DiffRowElement)element;
if (row.IsSpacer)
{
rowElement.BindSpacer(row.PropertyDiff, row.IndentLevel);
return;
}
switch (row.Kind)
{
case DiffRowKind.ObjectHeader:
case DiffRowKind.ComponentHeader:
bool isExpanded = mExpandedObjects.Contains(
row.ObjectDiff.GetObjectId());
rowElement.BindHeader(
row.ObjectDiff,
isExpanded,
mSearchFilter,
row.IndentLevel);
return;
case DiffRowKind.ContainerHeader:
rowElement.BindGroupHeader(
row.GroupDisplayName,
row.GroupDiffType,
row.GroupKey,
IsGroupExpanded(row.GroupKey),
mSearchFilter,
row.IndentLevel);
return;
default:
rowElement.BindProperty(
row.PropertyDiff,
mSearchFilter,
row.IndentLevel);
return;
}
}
void OnObjectToggled(ObjectDiff objDiff)
{
int id = objDiff.GetObjectId();
if (!mExpandedObjects.Remove(id))
mExpandedObjects.Add(id);
RebuildVisibleRows();
}
void OnGroupToggled(string groupFullKey)
{
if (!mCollapsedGroups.Remove(groupFullKey))
mCollapsedGroups.Add(groupFullKey);
RebuildVisibleRows();
}
void SetDiffFilter(DiffFilter filter)
{
mDiffFilter = filter;
RebuildVisibleRows();
}
void SetSearchFilter(string searchFilter)
{
mSearchFilter = searchFilter ?? string.Empty;
RebuildVisibleRows();
}
void SetGameObjectFilter(HashSet<string> selected)
{
mSelectedGameObjects = selected;
RebuildVisibleRows();
}
void SetTypeFilter(HashSet<string> selected)
{
mSelectedTypes = selected;
RebuildVisibleRows();
}
void ExpandAll()
{
foreach (ObjectDiff objDiff in mObjectDiffs)
{
mExpandedObjects.Add(objDiff.GetObjectId());
if (objDiff.ComponentDiffs == null)
continue;
foreach (ObjectDiff compDiff in objDiff.ComponentDiffs)
mExpandedObjects.Add(compDiff.GetObjectId());
}
mCollapsedGroups.Clear();
RebuildVisibleRows();
}
void CollapseAll()
{
mExpandedObjects.Clear();
foreach (string fullKey in mKnownGroups)
mCollapsedGroups.Add(fullKey);
RebuildVisibleRows();
}
void UpdateDataLossBanner(List<ObjectDiff> diffs)
{
int dataLossCount = CountObjectsWithDataLoss(diffs);
if (dataLossCount == 0)
{
mMessagePanel.Hide();
return;
}
mMessagePanel.HandleMessage(
DataLossDescriptions.GetBannerMessage(dataLossCount),
DataLossDescriptions.GetViewAsTextDiffButtonText(),
mOnViewAsTextDiff);
}
// Counts every ObjectDiff (top-level or nested under a GameObject
// container) whose own DataLoss is non-None. We don't add the
// container's rolled-up signal because containers don't have their
// own data — counting them would double-count the children.
static int CountObjectsWithDataLoss(List<ObjectDiff> diffs)
{
int n = 0;
foreach (ObjectDiff d in diffs)
{
if (d.DataLoss != DataLossKind.None)
n++;
if (d.ComponentDiffs == null)
continue;
foreach (ObjectDiff c in d.ComponentDiffs)
{
if (c.DataLoss != DataLossKind.None)
n++;
}
}
return n;
}
void CreateGUI()
{
style.flexGrow = 1;
mMessagePanel = new MessagePanel();
mDiffToolbarPanel = new DiffToolbarPanel(
SetDiffFilter, SetSearchFilter, ExpandAll, CollapseAll,
SetGameObjectFilter, SetTypeFilter);
mContributorsHeaderPanel = new ContributorsHeaderPanel();
mListView = CreateListView();
mContainerPanel = new VisualElement();
mContainerPanel.style.flexGrow = 1;
mContentPanel = new VisualElement();
mContentPanel.style.flexGrow = 1;
mContentPanel.Add(mMessagePanel);
mContentPanel.Add(mDiffToolbarPanel);
mContentPanel.Add(mContributorsHeaderPanel);
mContentPanel.Add(mContainerPanel);
Add(mContentPanel);
ReplaceView(mListView);
}
ListView CreateListView()
{
ListView result = new ListView();
result.style.flexGrow = 1;
result.fixedItemHeight = DiffRowElement.ROW_HEIGHT;
result.makeItem = () => new DiffRowElement(OnObjectToggled, OnGroupToggled);
result.bindItem = OnBindRow;
result.selectionType = SelectionType.None;
result.itemsSource = mVisibleRows;
return result;
}
DiffToolbarPanel mDiffToolbarPanel;
ContributorsHeaderPanel mContributorsHeaderPanel;
MessagePanel mMessagePanel;
ListView mListView;
VisualElement mContentPanel;
VisualElement mContainerPanel;
VisualElement mCurrentView;
BigFileMessagePanel mBigFileMessagePanel;
PurgedRevisionControl mPurgedRevisionControl;
DiffMessagePanel mEmptyStatePanel;
List<ObjectDiff> mObjectDiffs = new List<ObjectDiff>();
readonly HashSet<int> mExpandedObjects = new HashSet<int>();
readonly HashSet<string> mCollapsedGroups = new HashSet<string>();
readonly HashSet<string> mKnownGroups = new HashSet<string>();
readonly List<DiffRow> mVisibleRows = new List<DiffRow>();
PropertyDiffSearchIndex mSearchIndex = PropertyDiffSearchIndex.Build(
new List<ObjectDiff>(), null);
DiffFilter mDiffFilter = DiffFilter.All;
HashSet<string> mSelectedGameObjects;
HashSet<string> mSelectedTypes;
string mSearchFilter = string.Empty;
DiffViewerData mDiffViewerData;
readonly IBigFileDownloader mBigFileDownloader;
readonly IBigFileChecker mBigFileChecker;
readonly Action mOnViewAsTextDiff;
static readonly PropertyTreeWalker<PropertyDiffNode> mWalker =
new PropertyTreeWalker<PropertyDiffNode>(
node => node.Kind,
node => node.Children);
class ExpansionSnapshot
{
internal readonly Dictionary<string, bool> Objects =
new Dictionary<string, bool>();
internal readonly HashSet<string> CollapsedGroups =
new HashSet<string>();
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 83ac42cfcef844f98fd021a805db6392
timeCreated: 1772182350
@@ -0,0 +1,83 @@
using PlasticGui;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff
{
// The diff was produced from an object whose serialized data was
// dropped by Unity's loader (LoadSerializedFileAndForget). The diff is
// incomplete — fields the loader couldn't materialize are missing from
// it — and the user should be steered to text diff.
//
// Each kind corresponds to a specific failure mode in Unity's loader
// that we have explicitly identified. We do not surface a generic
// "something might be wrong" signal — every entry here names a concrete
// problem so the UI can give the user an accurate explanation. Higher
// values are more specific — see DataLossDetection.PickMoreSpecific for
// the precedence used when multiple signals fire on the same object pair.
internal enum DataLossKind
{
None = 0,
// AnimatorOverrideController whose runtimeAnimatorController is
// null. AwakeFromLoad → BuildAsset wipes m_Clips whenever the
// controller is null (see Modules/Animation/AnimatorOverrideController.cpp
// in the Unity source), so any clip overrides serialized in the
// YAML are silently dropped and never reach the diff.
UnresolvedAnimatorController = 1,
// MonoBehaviour with no resolvable MonoScript reference (missing
// script). Serialized fields beyond the base MonoBehaviour are lost.
UnresolvedMonoScript = 2,
// The loader replaced the object with UnityEditor.FallbackEditorWindow
// because its script could not be loaded into the editor AppDomain
// (typically: package not installed or AppDomain reload timing). All
// fields except the base EditorWindow members are stripped.
FallbackEditorWindow = 3
}
// Localized copy for every data-loss surface — per-row tooltip,
// file-level banner, and the "switch to text diff" button. Kept
// alongside DataLossKind so adding a new kind forces the maintainer
// to also choose the user-facing message.
internal static class DataLossDescriptions
{
internal static string GetRowTooltip(DataLossKind kind)
{
switch (kind)
{
case DataLossKind.UnresolvedAnimatorController:
return PlasticLocalization.Name
.DiffDataLossUnresolvedAnimatorController.GetString();
case DataLossKind.UnresolvedMonoScript:
return PlasticLocalization.Name
.DiffDataLossUnresolvedMonoScript.GetString();
case DataLossKind.FallbackEditorWindow:
return PlasticLocalization.Name
.DiffDataLossFallbackEditorWindow.GetString();
default:
return string.Empty;
}
}
internal static string GetBannerMessage(int dataLossCount)
{
if (dataLossCount <= 0)
return string.Empty;
if (dataLossCount == 1)
{
return PlasticLocalization.Name
.DiffDataLossBannerSingular.GetString();
}
return PlasticLocalization.Name
.DiffDataLossBannerPlural.GetString(dataLossCount);
}
internal static string GetViewAsTextDiffButtonText()
{
return PlasticLocalization.Name
.DiffDataLossViewAsTextButton.GetString();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6eaff6a39d1545778e6362a438cb9da4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,10 @@
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff
{
internal enum DiffFilter : byte
{
All,
Modified,
Added,
Removed
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: fbb5000a0504a4acd8b805b122326c9f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,39 @@
using Unity.PlasticSCM.Editor.UI;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff
{
internal static class DiffGutter
{
internal static Color GetColor(DiffType diffType)
{
switch (diffType)
{
case DiffType.Added:
return UnityStyles.Colors.Diff.AssetDiff.GutterAdded;
case DiffType.Removed:
return UnityStyles.Colors.Diff.AssetDiff.GutterRemoved;
case DiffType.Modified:
return UnityStyles.Colors.Diff.AssetDiff.GutterModified;
default:
return Color.clear;
}
}
internal static void Apply(
VisualElement panel, Color color, float paddingLeft)
{
SetColor(panel, color);
panel.style.paddingLeft = paddingLeft;
}
internal static void SetColor(VisualElement panel, Color color)
{
panel.style.borderLeftWidth = GUTTER_WIDTH;
panel.style.borderLeftColor = color;
}
const float GUTTER_WIDTH = 3f;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c10e8fc853bad4a54a96aedac078a036
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,257 @@
using PlasticGui;
using UnityEngine;
using UnityEngine.UIElements;
using Unity.PlasticSCM.Editor.Diff.Asset.Common;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff
{
internal class DiffHeaderRow : VisualElement
{
internal DiffHeaderRow()
{
CreateGUI();
}
internal void Bind(
ObjectDiff objDiff,
bool isExpanded,
string searchFilter,
int indentLevel)
{
// Container GameObjects (no own changes, only nested component
// changes) are stored as Unchanged so they don't inflate status
// counts, but visually they should display like Modified.
DiffType displayType = IsContainer(objDiff)
? DiffType.Modified
: objDiff.DiffType;
mHasSrc = displayType != DiffType.Added;
mHasDst = displayType != DiffType.Removed;
mbIsLeftHovered = false;
mbIsRightHovered = false;
float padding = HeaderRow.BASE_PADDING_LEFT
+ indentLevel * HeaderRow.INDENT_PX;
Color gutterColor = DiffGutter.GetColor(displayType);
DiffGutter.SetColor(mLeftPanel, mHasSrc ? gutterColor : Color.clear);
DiffGutter.SetColor(mRightPanel, mHasDst ? gutterColor : Color.clear);
bool suppressBottomBorder = objDiff.IsGameObject();
HeaderRow.ApplyContentBorder(mLeftContent, mHasSrc, padding, isExpanded, suppressBottomBorder);
HeaderRow.ApplyContentBorder(mRightContent, mHasDst, padding, isExpanded, suppressBottomBorder);
string arrowText = isExpanded
? HeaderRow.ARROW_DOWN : HeaderRow.ARROW_RIGHT;
UnityEngine.Texture icon = ObjectIconResolver.GetIcon(objDiff);
string leftAnnotation = BuildLeftAnnotation(objDiff);
string rightAnnotation = BuildRightAnnotation(objDiff);
bool isExpandable =
(objDiff.PropertyDiffTree != null
&& objDiff.PropertyDiffTree.Children.Count > 0)
|| (objDiff.ComponentDiffs != null && objDiff.ComponentDiffs.Count > 0);
HeaderRow.ConfigurePanel(
mLeftArrow, mLeftIcon, mLeftLabel, mLeftAnnotation, mLeftPanel,
mHasSrc, arrowText,
HeaderRow.GetBackgroundColor(mHasSrc, mbIsLeftHovered), icon,
mHasSrc ? objDiff.GetSrcDisplayName() : string.Empty,
searchFilter,
leftAnnotation,
isExpandable);
HeaderRow.ConfigurePanel(
mRightArrow, mRightIcon, mRightLabel, mRightAnnotation, mRightPanel,
mHasDst, arrowText,
HeaderRow.GetBackgroundColor(mHasDst, mbIsRightHovered), icon,
mHasDst ? objDiff.GetDstDisplayName() : string.Empty,
searchFilter,
rightAnnotation,
isExpandable);
ApplyDataLossTooltip(objDiff, mLeftAnnotation, mRightAnnotation);
}
// The annotation Label is hardcoded italic in HeaderRow.BuildPanel
// — fine for "moved up 1 position" but visually off for the data-
// loss glyph. Toggle the font style + add the tooltip in one pass
// so the two stay in sync.
static void ApplyDataLossTooltip(
ObjectDiff objDiff, Label leftAnnotation, Label rightAnnotation)
{
DataLossKind kind = GetEffectiveDataLoss(objDiff);
bool showingDataLoss = kind != DataLossKind.None;
string tooltip = showingDataLoss
? DataLossDescriptions.GetRowTooltip(kind)
: string.Empty;
FontStyle fontStyle = showingDataLoss
? FontStyle.Normal
: FontStyle.Italic;
leftAnnotation.tooltip = tooltip;
leftAnnotation.style.unityFontStyleAndWeight = fontStyle;
rightAnnotation.tooltip = tooltip;
rightAnnotation.style.unityFontStyleAndWeight = fontStyle;
}
// Reparenting and sibling reorder are mutually exclusive on the same
// GameObject — see ParentChangeDiffs / SiblingReorderDiffs.
// Reparent annotation is per-side (prior location on src, new location
// on dst); sibling reorder uses the same delta-based annotation on both.
//
// Data-loss takes precedence over reorder/reparent text — the
// user needs to know the diff is incomplete before they reason
// about position changes. The two rarely co-occur in practice
// (broken objects don't typically get reordered alongside their
// breakage). The annotation slot then carries a short warning
// glyph and the full description goes on the Label's tooltip
// (set in Bind after ConfigurePanel runs).
static string BuildLeftAnnotation(ObjectDiff objDiff)
{
if (GetEffectiveDataLoss(objDiff) != DataLossKind.None)
return DATA_LOSS_GLYPH;
if (objDiff.HasParentChange())
return BuildParentLocationAnnotation(objDiff.SrcParent, isDst: false);
return BuildPositionAnnotation(objDiff.PositionDelta);
}
static string BuildRightAnnotation(ObjectDiff objDiff)
{
if (GetEffectiveDataLoss(objDiff) != DataLossKind.None)
return DATA_LOSS_GLYPH;
if (objDiff.HasParentChange())
return BuildParentLocationAnnotation(objDiff.DstParent, isDst: true);
return BuildPositionAnnotation(objDiff.PositionDelta);
}
// Returns this row's own DataLoss when set, otherwise the worst
// DataLoss across nested ComponentDiffs. This lets a collapsed
// GameObject container surface the warning when any nested
// component is broken — the user shouldn't have to expand every
// row to discover where data was dropped.
static DataLossKind GetEffectiveDataLoss(ObjectDiff objDiff)
{
if (objDiff.DataLoss != DataLossKind.None)
return objDiff.DataLoss;
if (objDiff.ComponentDiffs == null)
return DataLossKind.None;
DataLossKind worst = DataLossKind.None;
foreach (ObjectDiff comp in objDiff.ComponentDiffs)
{
if ((int)comp.DataLoss > (int)worst)
worst = comp.DataLoss;
}
return worst;
}
static string BuildParentLocationAnnotation(
UnityEngine.GameObject parent, bool isDst)
{
string parentLabel = parent == null
? PlasticLocalization.Name.DiffSceneRoot.GetString()
: "'" + parent.name + "'";
return isDst
? PlasticLocalization.Name.DiffMovedToLocation.GetString(parentLabel)
: PlasticLocalization.Name.DiffInLocation.GetString(parentLabel);
}
static bool IsContainer(ObjectDiff objDiff)
{
return objDiff.DiffType == DiffType.Unchanged
&& objDiff.ComponentDiffs != null
&& objDiff.ComponentDiffs.Count > 0;
}
static string BuildPositionAnnotation(int delta)
{
if (delta == 0)
return null;
int abs = delta < 0 ? -delta : delta;
if (delta < 0)
{
return abs == 1
? PlasticLocalization.Name.DiffMovedUpOnePosition.GetString(abs)
: PlasticLocalization.Name.DiffMovedUpPositions.GetString(abs);
}
return abs == 1
? PlasticLocalization.Name.DiffMovedDownOnePosition.GetString(abs)
: PlasticLocalization.Name.DiffMovedDownPositions.GetString(abs);
}
void CreateGUI()
{
style.flexDirection = FlexDirection.Row;
style.flexGrow = 1;
mLeftPanel = HeaderRow.BuildPanel(
out mLeftContent, out mLeftArrow, out mLeftIcon,
out mLeftLabel, out mLeftAnnotation);
mLeftPanel.RegisterCallback<MouseEnterEvent>(OnLeftPanelMouseEnter);
mLeftPanel.RegisterCallback<MouseLeaveEvent>(OnLeftPanelMouseLeave);
Add(mLeftPanel);
mRightPanel = HeaderRow.BuildPanel(
out mRightContent, out mRightArrow, out mRightIcon,
out mRightLabel, out mRightAnnotation);
mRightPanel.RegisterCallback<MouseEnterEvent>(OnRightPanelMouseEnter);
mRightPanel.RegisterCallback<MouseLeaveEvent>(OnRightPanelMouseLeave);
Add(mRightPanel);
}
void OnLeftPanelMouseEnter(MouseEnterEvent evt)
{
HeaderRow.SetHovered(
ref mbIsLeftHovered, mHasSrc, mLeftPanel, bIsHovered: true);
}
void OnLeftPanelMouseLeave(MouseLeaveEvent evt)
{
HeaderRow.SetHovered(
ref mbIsLeftHovered, mHasSrc, mLeftPanel, bIsHovered: false);
}
void OnRightPanelMouseEnter(MouseEnterEvent evt)
{
HeaderRow.SetHovered(
ref mbIsRightHovered, mHasDst, mRightPanel, bIsHovered: true);
}
void OnRightPanelMouseLeave(MouseLeaveEvent evt)
{
HeaderRow.SetHovered(
ref mbIsRightHovered, mHasDst, mRightPanel, bIsHovered: false);
}
VisualElement mLeftPanel;
VisualElement mLeftContent;
Label mLeftArrow;
Image mLeftIcon;
Label mLeftLabel;
Label mLeftAnnotation;
VisualElement mRightPanel;
VisualElement mRightContent;
Label mRightArrow;
Image mRightIcon;
Label mRightLabel;
Label mRightAnnotation;
bool mHasSrc;
bool mHasDst;
bool mbIsLeftHovered;
bool mbIsRightHovered;
const string DATA_LOSS_GLYPH = "⚠";
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e5cbdaec4d63a4013ad3089e2435b53f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,137 @@
using Unity.PlasticSCM.Editor.Diff.Asset.Diff.Property;
using Unity.PlasticSCM.Editor.UI;
using UnityEngine;
using UnityEngine.UIElements;
using Unity.PlasticSCM.Editor.Diff.Asset.Common;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff
{
internal class DiffPropertyRow : VisualElement
{
internal DiffPropertyRow()
{
CreateGUI();
}
internal void BindSpacer(PropertyDiff propDiff, int indentLevel)
{
DiffType diffType = propDiff.DiffType;
bool hasSrc = diffType != DiffType.Added;
bool hasDst = diffType != DiffType.Removed;
float padding = PropertyRow.BASE_PADDING_LEFT
+ indentLevel * PropertyRow.INDENT_PX;
Color gutterColor = DiffGutter.GetColor(diffType);
DiffGutter.Apply(mLeftPanel, hasSrc ? gutterColor : Color.clear, padding);
DiffGutter.Apply(mRightPanel, hasDst ? gutterColor : Color.clear, padding);
mLeftPanel.style.backgroundColor = Color.clear;
mRightPanel.style.backgroundColor = Color.clear;
mLeftLabel.style.display = DisplayStyle.None;
mRightLabel.style.display = DisplayStyle.None;
mLeftValue.style.display = DisplayStyle.None;
mRightValue.style.display = DisplayStyle.None;
pickingMode = PickingMode.Ignore;
mLeftPanel.pickingMode = PickingMode.Ignore;
mRightPanel.pickingMode = PickingMode.Ignore;
}
internal void Bind(
PropertyDiff propDiff,
string searchFilter,
int indentLevel)
{
DiffType diffType = propDiff.DiffType;
bool hasSrc = diffType != DiffType.Added;
bool hasDst = diffType != DiffType.Removed;
float padding = PropertyRow.BASE_PADDING_LEFT
+ indentLevel * PropertyRow.INDENT_PX;
Color gutterColor = DiffGutter.GetColor(diffType);
DiffGutter.Apply(mLeftPanel, hasSrc ? gutterColor : Color.clear, padding);
DiffGutter.Apply(mRightPanel, hasDst ? gutterColor : Color.clear, padding);
ApplyPanelBackground(mLeftPanel, diffType, isLeftSide: true);
ApplyPanelBackground(mRightPanel, diffType, isLeftSide: false);
pickingMode = PickingMode.Position;
mLeftPanel.pickingMode = PickingMode.Position;
mRightPanel.pickingMode = PickingMode.Position;
string label = propDiff.DisplayName ?? propDiff.Path;
bool hasSearch = !string.IsNullOrEmpty(searchFilter);
string displayLabel = hasSearch
? SearchHighlight.Apply(label, searchFilter)
: label;
PropertyRow.ConfigureNameLabel(
mLeftLabel, hasSrc, hasSearch, displayLabel, propDiff.Path);
PropertyRow.ConfigureNameLabel(
mRightLabel, hasDst, hasSearch, displayLabel, propDiff.Path);
mLeftValue.style.display = hasSrc
? DisplayStyle.Flex : DisplayStyle.None;
mRightValue.style.display = hasDst
? DisplayStyle.Flex : DisplayStyle.None;
mLeftValue.SetData(
propDiff.SrcTag, propDiff.SrcValue, hasSrc,
hasDst ? propDiff.DstTag : null);
mRightValue.SetData(
propDiff.DstTag, propDiff.DstValue, hasDst,
hasSrc ? propDiff.SrcTag : null);
}
void CreateGUI()
{
style.flexDirection = FlexDirection.Row;
style.flexGrow = 1;
mLeftPanel = BuildPanel(out mLeftLabel, out mLeftValue);
Add(mLeftPanel);
mRightPanel = BuildPanel(out mRightLabel, out mRightValue);
Add(mRightPanel);
}
static VisualElement BuildPanel(
out Label nameLabel,
out DiffValueDisplay valueDisplay)
{
VisualElement panel = PropertyRow.BuildPanel(out nameLabel);
valueDisplay = new DiffValueDisplay();
panel.Add(valueDisplay);
return panel;
}
static void ApplyPanelBackground(
VisualElement panel,
DiffType diffType,
bool isLeftSide)
{
bool isEmpty =
(diffType == DiffType.Added && isLeftSide) ||
(diffType == DiffType.Removed && !isLeftSide);
panel.style.backgroundColor = isEmpty
? UnityStyles.Colors.Diff.AssetDiff.EmptyPanelBackground
: UnityStyles.Colors.Diff.AssetDiff.PropertyRowBackground;
}
VisualElement mLeftPanel;
Label mLeftLabel;
DiffValueDisplay mLeftValue;
VisualElement mRightPanel;
Label mRightLabel;
DiffValueDisplay mRightValue;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0beb995ef89b74dd4880e1d7c7b342f9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,59 @@
using Unity.PlasticSCM.Editor.Diff.Asset.Diff.Property;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff
{
internal enum DiffRowKind : byte
{
ObjectHeader,
ComponentHeader,
ContainerHeader,
PropertyDiff
}
internal readonly struct DiffRow
{
internal readonly DiffRowKind Kind;
internal readonly ObjectDiff ObjectDiff;
internal readonly PropertyDiff PropertyDiff;
internal readonly int IndentLevel;
internal readonly bool IsSpacer;
internal readonly string GroupKey;
internal readonly string GroupDisplayName;
internal readonly DiffType GroupDiffType;
internal DiffRow(
DiffRowKind kind,
ObjectDiff objectDiff,
PropertyDiff propertyDiff,
int indentLevel = 0,
bool isSpacer = false)
{
Kind = kind;
ObjectDiff = objectDiff;
PropertyDiff = propertyDiff;
IndentLevel = indentLevel;
IsSpacer = isSpacer;
GroupKey = null;
GroupDisplayName = null;
GroupDiffType = DiffType.Unchanged;
}
internal DiffRow(
DiffRowKind kind,
ObjectDiff objectDiff,
string groupKey,
string groupDisplayName,
DiffType groupDiffType,
int indentLevel)
{
Kind = kind;
ObjectDiff = objectDiff;
PropertyDiff = null;
IndentLevel = indentLevel;
IsSpacer = false;
GroupKey = groupKey;
GroupDisplayName = groupDisplayName;
GroupDiffType = groupDiffType;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 15065be9d58284ff3a0be3d0e4527920
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,144 @@
using System;
using Unity.PlasticSCM.Editor.Diff.Asset.Diff.Property;
using UnityEngine.UIElements;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff
{
internal class DiffRowElement : VisualElement
{
internal const float ROW_HEIGHT = 22f;
internal DiffRowElement(
Action<ObjectDiff> toggleObjectCallback,
Action<string> toggleGroupCallback)
{
mToggleObjectCallback = toggleObjectCallback;
mToggleGroupCallback = toggleGroupCallback;
CreateGUI();
RegisterCallback<ClickEvent>(OnClicked);
}
internal void BindHeader(
ObjectDiff objDiff,
bool isExpanded,
string searchFilter,
int indentLevel = 0)
{
mBoundObjectDiff = objDiff;
mBoundGroupKey = null;
mBoundKind = BoundKind.ObjectHeader;
pickingMode = PickingMode.Position;
mHeaderRow.style.display = DisplayStyle.Flex;
mPropertyRow.style.display = DisplayStyle.None;
mGroupHeaderRow.style.display = DisplayStyle.None;
mHeaderRow.Bind(objDiff, isExpanded, searchFilter, indentLevel);
}
internal void BindGroupHeader(
string label,
DiffType groupDiffType,
string groupKey,
bool isExpanded,
string searchFilter,
int indentLevel)
{
mBoundObjectDiff = null;
mBoundGroupKey = groupKey;
mBoundKind = BoundKind.GroupHeader;
pickingMode = PickingMode.Position;
mHeaderRow.style.display = DisplayStyle.None;
mPropertyRow.style.display = DisplayStyle.None;
mGroupHeaderRow.style.display = DisplayStyle.Flex;
mGroupHeaderRow.Bind(
label, groupDiffType, isExpanded, searchFilter, indentLevel);
}
internal void BindProperty(
PropertyDiff propDiff,
string searchFilter,
int indentLevel = 0)
{
mBoundObjectDiff = null;
mBoundGroupKey = null;
mBoundKind = BoundKind.PropertyRow;
pickingMode = PickingMode.Position;
mHeaderRow.style.display = DisplayStyle.None;
mPropertyRow.style.display = DisplayStyle.Flex;
mGroupHeaderRow.style.display = DisplayStyle.None;
mPropertyRow.Bind(propDiff, searchFilter, indentLevel);
}
internal void BindSpacer(PropertyDiff propDiff, int indentLevel)
{
mBoundObjectDiff = null;
mBoundGroupKey = null;
mBoundKind = BoundKind.PropertyRow;
pickingMode = PickingMode.Ignore;
mHeaderRow.style.display = DisplayStyle.None;
mPropertyRow.style.display = DisplayStyle.Flex;
mGroupHeaderRow.style.display = DisplayStyle.None;
mPropertyRow.BindSpacer(propDiff, indentLevel);
}
void CreateGUI()
{
style.flexDirection = FlexDirection.Column;
style.minHeight = ROW_HEIGHT;
style.overflow = Overflow.Visible;
mHeaderRow = new DiffHeaderRow();
Add(mHeaderRow);
mGroupHeaderRow = new GroupHeaderRow();
Add(mGroupHeaderRow);
mPropertyRow = new DiffPropertyRow();
Add(mPropertyRow);
}
void OnClicked(ClickEvent evt)
{
switch (mBoundKind)
{
case BoundKind.ObjectHeader:
if (mBoundObjectDiff != null)
mToggleObjectCallback?.Invoke(mBoundObjectDiff);
return;
case BoundKind.GroupHeader:
if (mBoundGroupKey != null)
mToggleGroupCallback?.Invoke(mBoundGroupKey);
return;
}
}
readonly Action<ObjectDiff> mToggleObjectCallback;
readonly Action<string> mToggleGroupCallback;
DiffHeaderRow mHeaderRow;
GroupHeaderRow mGroupHeaderRow;
DiffPropertyRow mPropertyRow;
ObjectDiff mBoundObjectDiff;
string mBoundGroupKey;
BoundKind mBoundKind;
enum BoundKind : byte
{
None,
ObjectHeader,
GroupHeader,
PropertyRow
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f868eac0bc3ab44cfbc98c7099fce8cb
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,239 @@
using System;
using System.Collections.Generic;
using PlasticGui;
using Unity.PlasticSCM.Editor.UI;
using Unity.PlasticSCM.Editor.UI.UIElements;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff
{
internal class DiffToolbarPanel : VisualElement
{
internal DiffToolbarPanel(
Action<DiffFilter> setDiffFilter,
Action<string> filterChanged,
Action expandAll,
Action collapseAll,
Action<HashSet<string>> setGameObjectFilter,
Action<HashSet<string>> setTypeFilter)
{
mSetDiffFilter = setDiffFilter;
mFilterChanged = filterChanged;
mExpandAll = expandAll;
mCollapseAll = collapseAll;
mSetGameObjectFilter = setGameObjectFilter;
mSetTypeFilter = setTypeFilter;
CreateGUI();
mDelayedFilterAction = new DelayedActionBySecondsRunner(
DelayedSearchChanged, UnityConstants.SEARCH_DELAYED_INPUT_ACTION_INTERVAL);
}
internal void Dispose()
{
mFilterAllButton.UnregisterValueChangedCallback(
OnFilterAllToggleChanged);
mFilterModifiedButton.UnregisterValueChangedCallback(
OnFilterModifiedToggleChanged);
mFilterAddedButton.UnregisterValueChangedCallback(
OnFilterAddedToggleChanged);
mFilterRemovedButton.UnregisterValueChangedCallback(
OnFilterRemovedToggleChanged);
mSearchField.UnregisterValueChangedCallback(OnSearchFieldValueChanged);
mGameObjectDropdown.SelectionChanged -= OnGameObjectSelectionChanged;
mTypeDropdown.SelectionChanged -= OnTypeSelectionChanged;
}
internal void UpdateAvailableFilters(
IList<MultiSelectDropdownItem> gameObjects,
IList<MultiSelectDropdownItem> types,
bool show)
{
DisplayStyle display = show ? DisplayStyle.Flex : DisplayStyle.None;
mGameObjectDropdown.style.display = display;
mTypeDropdown.style.display = display;
if (!show)
return;
mGameObjectDropdown.SetItems(gameObjects);
mTypeDropdown.SetItems(types);
}
internal void UpdateFilterButtons(
int modified,
int added,
int removed,
DiffFilter diffFilter)
{
int total = modified + added + removed;
mFilterAllButton.text =
$"{PlasticLocalization.Name.DiffFilterAll.GetString()} ({total})";
mFilterModifiedButton.text =
$"{PlasticLocalization.Name.DiffFilterModified.GetString()} ({modified})";
mFilterAddedButton.text =
$"{PlasticLocalization.Name.DiffFilterAdded.GetString()} ({added})";
mFilterRemovedButton.text =
$"{PlasticLocalization.Name.DiffFilterRemoved.GetString()} ({removed})";
mFilterAllButton.SetEnabled(total > 0);
mFilterModifiedButton.SetEnabled(modified > 0);
mFilterAddedButton.SetEnabled(added > 0);
mFilterRemovedButton.SetEnabled(removed > 0);
mFilterAllButton.SetValueWithoutNotify(diffFilter == DiffFilter.All);
mFilterModifiedButton.SetValueWithoutNotify(diffFilter == DiffFilter.Modified);
mFilterAddedButton.SetValueWithoutNotify(diffFilter == DiffFilter.Added);
mFilterRemovedButton.SetValueWithoutNotify(diffFilter == DiffFilter.Removed);
}
void DelayedSearchChanged()
{
mFilterChanged(mSearchField.value);
}
void CreateGUI()
{
UnityEditor.UIElements.Toolbar toolbar = ControlBuilder.Toolbar.Create();
mFilterAllButton = ControlBuilder.Toolbar.CreateToggle(
PlasticLocalization.Name.DiffFilterAll.GetString(),
PlasticLocalization.Name.DiffFilterAllTooltip.GetString());
mFilterAllButton.RegisterValueChangedCallback(
OnFilterAllToggleChanged);
mFilterModifiedButton = ControlBuilder.Toolbar.CreateToggle(
PlasticLocalization.Name.DiffFilterModified.GetString(),
PlasticLocalization.Name.DiffFilterModifiedTooltip.GetString());
mFilterModifiedButton.RegisterValueChangedCallback(
OnFilterModifiedToggleChanged);
mFilterAddedButton = ControlBuilder.Toolbar.CreateToggle(
PlasticLocalization.Name.DiffFilterAdded.GetString(),
PlasticLocalization.Name.DiffFilterAddedTooltip.GetString());
mFilterAddedButton.RegisterValueChangedCallback(
OnFilterAddedToggleChanged);
mFilterRemovedButton = ControlBuilder.Toolbar.CreateToggleLeft(
PlasticLocalization.Name.DiffFilterRemoved.GetString(),
PlasticLocalization.Name.DiffFilterRemovedTooltip.GetString());
mFilterRemovedButton.RegisterValueChangedCallback(
OnFilterRemovedToggleChanged);
mGameObjectDropdown = ControlBuilder.Toolbar.CreateMultiSelectDropdownLeft(
PlasticLocalization.Name.DiffGameObjectFilterLabel.GetString());
mGameObjectDropdown.SelectionChanged += OnGameObjectSelectionChanged;
mGameObjectDropdown.style.display = DisplayStyle.None;
mTypeDropdown = ControlBuilder.Toolbar.CreateMultiSelectDropdown(
PlasticLocalization.Name.DiffTypeFilterLabel.GetString());
mTypeDropdown.SelectionChanged += OnTypeSelectionChanged;
mTypeDropdown.style.display = DisplayStyle.None;
mSearchField = ControlBuilder.Toolbar.CreateSearchField();
mSearchField.RegisterValueChangedCallback(OnSearchFieldValueChanged);
toolbar.Add(mFilterAllButton);
toolbar.Add(mFilterModifiedButton);
toolbar.Add(mFilterAddedButton);
toolbar.Add(mFilterRemovedButton);
toolbar.Add(mGameObjectDropdown);
toolbar.Add(mTypeDropdown);
VisualElement spacer = new VisualElement();
spacer.style.flexGrow = 1;
toolbar.Add(spacer);
mExpandAllButton = ControlBuilder.Toolbar.CreateButtonLeft(
PlasticLocalization.Name.DiffExpandAllButton.GetString(), mExpandAll);
toolbar.Add(mExpandAllButton);
mCollapseAllButton = ControlBuilder.Toolbar.CreateButton(
PlasticLocalization.Name.DiffCollapseAllButton.GetString(), mCollapseAll);
toolbar.Add(mCollapseAllButton);
toolbar.Add(mSearchField);
Add(toolbar);
}
void OnFilterAllToggleChanged(ChangeEvent<bool> evt)
{
if (!evt.newValue)
return;
mSetDiffFilter(DiffFilter.All);
}
void OnFilterModifiedToggleChanged(ChangeEvent<bool> evt)
{
if (!evt.newValue)
return;
mSetDiffFilter(DiffFilter.Modified);
}
void OnFilterAddedToggleChanged(ChangeEvent<bool> evt)
{
if (!evt.newValue)
return;
mSetDiffFilter(DiffFilter.Added);
}
void OnFilterRemovedToggleChanged(ChangeEvent<bool> evt)
{
if (!evt.newValue)
return;
mSetDiffFilter(DiffFilter.Removed);
}
void OnSearchFieldValueChanged(ChangeEvent<string> evt)
{
mDelayedFilterAction.Run();
}
void OnGameObjectSelectionChanged()
{
mSetGameObjectFilter(mGameObjectDropdown.Selected);
}
void OnTypeSelectionChanged()
{
mSetTypeFilter(mTypeDropdown.Selected);
}
readonly Action<DiffFilter> mSetDiffFilter;
readonly Action<string> mFilterChanged;
readonly Action mExpandAll;
readonly Action mCollapseAll;
readonly Action<HashSet<string>> mSetGameObjectFilter;
readonly Action<HashSet<string>> mSetTypeFilter;
readonly DelayedActionBySecondsRunner mDelayedFilterAction;
ToolbarToggle mFilterAllButton;
ToolbarToggle mFilterModifiedButton;
ToolbarToggle mFilterAddedButton;
ToolbarToggle mFilterRemovedButton;
ToolbarButton mExpandAllButton;
ToolbarButton mCollapseAllButton;
MultiSelectDropdown mGameObjectDropdown;
MultiSelectDropdown mTypeDropdown;
ToolbarSearchField mSearchField;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 694f4474a0854a2bab3e880bbcb004c6
timeCreated: 1778487152
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 9831c3a3f4a4645309f76e99ac9844c2
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,27 @@
using System.Collections.Generic;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff.Filtering
{
internal static class ObjectDiffFilters
{
internal static bool PassesGameObjectFilter(
ObjectDiff diff, HashSet<string> selected)
{
if (selected == null)
return true;
string name = diff.GetObjectName();
return name != null && selected.Contains(name);
}
internal static bool PassesTypeFilter(
ObjectDiff diff, HashSet<string> selected)
{
if (selected == null)
return true;
string typeName = diff.GetTypeName();
return typeName != null && selected.Contains(typeName);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4371d9087059f4476a33331774fdb3b8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,66 @@
using System;
using System.Collections.Generic;
using Unity.PlasticSCM.Editor.UI.UIElements;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff.Filtering
{
internal static class ObjectDiffOptions
{
internal static List<MultiSelectDropdownItem> ExtractGameObjects(
IList<ObjectDiff> objectDiffs,
Func<ObjectDiff, UnityEngine.Texture> iconResolver)
{
List<MultiSelectDropdownItem> result = new List<MultiSelectDropdownItem>();
HashSet<string> seen = new HashSet<string>();
foreach (ObjectDiff diff in objectDiffs)
{
string name = diff.GetObjectName();
if (string.IsNullOrEmpty(name) || !seen.Add(name))
continue;
result.Add(new MultiSelectDropdownItem(name, iconResolver(diff)));
}
return result;
}
internal static List<MultiSelectDropdownItem> ExtractTypes(
IList<ObjectDiff> objectDiffs,
Func<ObjectDiff, UnityEngine.Texture> iconResolver)
{
List<MultiSelectDropdownItem> result = new List<MultiSelectDropdownItem>();
HashSet<string> seen = new HashSet<string>();
foreach (ObjectDiff diff in objectDiffs)
{
AddTypeIfPresent(diff, result, seen, iconResolver);
if (diff.ComponentDiffs == null)
continue;
foreach (ObjectDiff comp in diff.ComponentDiffs)
AddTypeIfPresent(comp, result, seen, iconResolver);
}
return result;
}
static void AddTypeIfPresent(
ObjectDiff diff,
List<MultiSelectDropdownItem> result,
HashSet<string> seen,
Func<ObjectDiff, UnityEngine.Texture> iconResolver)
{
if (diff.DiffType == DiffType.Unchanged)
return;
string typeName = diff.GetTypeName();
if (string.IsNullOrEmpty(typeName) || !seen.Add(typeName))
return;
result.Add(new MultiSelectDropdownItem(typeName, iconResolver(diff)));
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7f0fe0843a02c4ed6a7606ee4d655343
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,129 @@
using Unity.PlasticSCM.Editor.UI;
using UnityEngine;
using UnityEngine.UIElements;
using Unity.PlasticSCM.Editor.Diff.Asset.Common;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff
{
internal class GroupHeaderRow : VisualElement
{
internal GroupHeaderRow()
{
CreateGUI();
}
internal void Bind(
string label,
DiffType groupDiffType,
bool isExpanded,
string searchFilter,
int indentLevel)
{
bool hasSrc = groupDiffType != DiffType.Added;
bool hasDst = groupDiffType != DiffType.Removed;
float padding = PropertyRow.BASE_PADDING_LEFT
+ indentLevel * PropertyRow.INDENT_PX;
Color gutterColor = DiffGutter.GetColor(groupDiffType);
DiffGutter.Apply(mLeftPanel, hasSrc ? gutterColor : Color.clear, padding);
DiffGutter.Apply(mRightPanel, hasDst ? gutterColor : Color.clear, padding);
ApplyPanelBackground(mLeftPanel, groupDiffType, isLeftSide: true);
ApplyPanelBackground(mRightPanel, groupDiffType, isLeftSide: false);
string arrowText = isExpanded
? HeaderRow.ARROW_DOWN : HeaderRow.ARROW_RIGHT;
bool hasSearch = !string.IsNullOrEmpty(searchFilter);
string displayLabel = hasSearch
? SearchHighlight.Apply(label, searchFilter)
: label;
ConfigureSide(
mLeftArrow, mLeftLabel, hasSrc, arrowText, displayLabel, hasSearch);
ConfigureSide(
mRightArrow, mRightLabel, hasDst, arrowText, displayLabel, hasSearch);
}
void CreateGUI()
{
style.flexDirection = FlexDirection.Row;
style.flexGrow = 1;
mLeftPanel = BuildPanel(out mLeftArrow, out mLeftLabel);
Add(mLeftPanel);
mRightPanel = BuildPanel(out mRightArrow, out mRightLabel);
Add(mRightPanel);
}
static VisualElement BuildPanel(out Label arrow, out Label label)
{
VisualElement panel = new VisualElement();
panel.style.flexGrow = 1;
panel.style.flexBasis = 0;
panel.style.flexDirection = FlexDirection.Row;
panel.style.alignItems = Align.Center;
panel.style.paddingLeft = PropertyRow.BASE_PADDING_LEFT;
panel.style.paddingRight = 4;
panel.style.paddingTop = 1;
panel.style.paddingBottom = 1;
arrow = new Label(HeaderRow.ARROW_RIGHT);
arrow.style.width = 16;
arrow.style.fontSize = 10;
arrow.style.unityTextAlign = TextAnchor.MiddleCenter;
arrow.style.color = UnityStyles.Colors.Diff.AssetDiff.ExpanderColor;
panel.Add(arrow);
label = new Label();
label.style.fontSize = 12;
label.style.unityFontStyleAndWeight = FontStyle.Bold;
label.style.flexShrink = 1;
label.style.overflow = Overflow.Hidden;
label.style.textOverflow = TextOverflow.Ellipsis;
label.style.color = UnityStyles.Colors.DefaultText;
panel.Add(label);
return panel;
}
static void ConfigureSide(
Label arrow, Label label, bool hasContent,
string arrowText, string text, bool enableRichText)
{
arrow.text = arrowText;
arrow.style.display = hasContent
? DisplayStyle.Flex : DisplayStyle.None;
label.enableRichText = enableRichText;
label.text = hasContent ? text : string.Empty;
label.style.display = hasContent
? DisplayStyle.Flex : DisplayStyle.None;
}
static void ApplyPanelBackground(
VisualElement panel,
DiffType diffType,
bool isLeftSide)
{
bool isEmpty =
(diffType == DiffType.Added && isLeftSide) ||
(diffType == DiffType.Removed && !isLeftSide);
panel.style.backgroundColor = isEmpty
? UnityStyles.Colors.Diff.AssetDiff.EmptyPanelBackground
: UnityStyles.Colors.Diff.AssetDiff.PropertyRowBackground;
}
VisualElement mLeftPanel;
Label mLeftArrow;
Label mLeftLabel;
VisualElement mRightPanel;
Label mRightArrow;
Label mRightLabel;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 98697e16f5be4c5dbaf28a10798b108f
timeCreated: 1747310400
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 772402f8aab2e44a089edb3142c706cd
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,76 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Codice.LogWrapper;
using Unity.PlasticSCM.Editor.Diff.Asset.Common.Property;
using Unity.PlasticSCM.Editor.Diff.Asset.Diff.Property;
using Unity.PlasticSCM.Editor.Diff.Asset.Common.Meta;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff.Meta
{
internal static class MetaFileDiffs
{
internal static List<ObjectDiff> BuildDiffData(
string srcFile,
string dstFile)
{
Stopwatch sw = Stopwatch.StartNew();
string metaFileName = Path.GetFileName(srcFile);
PropertyTreeNode filteredSrc = MetaTreeHelpers.FilterIgnoredKeys(
MetaPropertyTreeBuilder.Build(File.ReadAllBytes(srcFile)));
PropertyTreeNode filteredDst = MetaTreeHelpers.FilterIgnoredKeys(
MetaPropertyTreeBuilder.Build(File.ReadAllBytes(dstFile)));
PropertyDiffNode diffTree = PropertyDiffs.BuildDiffTree(
filteredSrc, filteredDst);
if (diffTree == null || diffTree.Children.Count == 0)
return EmptyList;
// Each top-level YAML key that changed becomes its own ObjectDiff
// — analogous to a Component in a UnityObject diff. The section's
// diff tree carries the key's children directly so the renderer
// doesn't duplicate "AudioImporter" as both the section header and
// the first child row.
List<ObjectDiff> result = new List<ObjectDiff>(
diffTree.Children.Count);
foreach (PropertyDiffNode section in diffTree.Children)
{
result.Add(new ObjectDiff
{
MetaFileName = metaFileName,
MetaSectionName = section.DisplayName,
DiffType = section.DiffType,
PropertyDiffTree = WrapAsSectionRoot(section)
});
}
mLog.DebugFormat(
"{0} meta diff sections calculated in {1} ms for '{2}'",
result.Count, sw.ElapsedMilliseconds, metaFileName);
return result;
}
static PropertyDiffNode WrapAsSectionRoot(PropertyDiffNode section)
{
if (section.Kind == NodeKind.Leaf)
{
return PropertyDiffNode.CreateRoot(
new List<PropertyDiffNode> { section });
}
return PropertyDiffNode.CreateRoot(
new List<PropertyDiffNode>(section.Children));
}
static readonly List<ObjectDiff> EmptyList =
new List<ObjectDiff>();
static readonly ILog mLog = PlasticApp.GetLogger("MetaFileDiffs");
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a7096a557efd546c09f08a5d12fb1a43
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,128 @@
using System.Collections.Generic;
using PlasticGui;
using Unity.PlasticSCM.Editor.Diff.Asset.Diff.Property;
using Unity.PlasticSCM.Editor.Diff.Asset.Common;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff
{
internal enum DiffType
{
Unchanged,
Added,
Removed,
Modified
}
internal class ObjectDiff
{
internal UnityEngine.Object SrcObject;
internal UnityEngine.Object DstObject;
internal DiffType DiffType;
internal DataLossKind DataLoss;
internal PropertyDiffNode PropertyDiffTree;
internal List<ObjectDiff> ComponentDiffs;
// Component reorder annotation. 0 = no position change.
// Positive = moved down N positions, negative = moved up N positions.
internal int PositionDelta;
// Reparent annotation. Both null = no parent change. Either non-null
// means the GameObject was reparented; null on a side means that side
// had it at the scene root (or as the prefab's top-level).
internal UnityEngine.GameObject SrcParent;
internal UnityEngine.GameObject DstParent;
// Populated when this row represents a section of a .meta file —
// the originating .meta filename (MetaFileName) and the nicified
// top-level YAML key (MetaSectionName, e.g. "Audio Importer"),
// analogous to a Component header in UnityObject diffs. MetaFileName
// is the canonical "this is a meta row" flag (see IsMetaFileObject);
// Src/DstObject are null on meta rows.
internal string MetaFileName;
internal string MetaSectionName;
// Gated on MetaFileName rather than Src/DstObject being null, so we
// don't misclassify a UnityObject row whose underlying native object
// has been destroyed (Unity's overloaded == reports it null) as a
// meta row.
internal bool IsMetaFileObject
{
get { return !string.IsNullOrEmpty(MetaFileName); }
}
internal bool HasParentChange()
{
return SrcParent != null || DstParent != null;
}
internal int GetObjectId()
{
if (IsMetaFileObject)
return (MetaFileName + ":" + MetaSectionName).GetHashCode();
UnityEngine.Object obj = DstObject ?? SrcObject;
return obj != null ? obj.GetObjectId() : 0;
}
internal string GetSrcDisplayName()
{
if (IsMetaFileObject)
return GetMetaDisplayName();
return BuildDisplayName(SrcObject ?? DstObject);
}
internal string GetDstDisplayName()
{
if (IsMetaFileObject)
return GetMetaDisplayName();
return BuildDisplayName(DstObject ?? SrcObject);
}
string GetMetaDisplayName()
{
return string.IsNullOrEmpty(MetaSectionName)
? MetaFileName
: MetaSectionName;
}
// Components share their GameObject's name, so showing it would
// duplicate the parent header. For everything else the icon already
// conveys the type — show the object's own name.
static string BuildDisplayName(UnityEngine.Object obj)
{
if (obj == null)
return PlasticLocalization.Name.DiffUnknownObject.GetString();
if (obj is UnityEngine.Component)
return obj.GetType().Name;
return string.IsNullOrEmpty(obj.name) ? obj.GetType().Name : obj.name;
}
internal string GetTypeName()
{
UnityEngine.Object obj = SrcObject ?? DstObject;
return obj == null ? null : obj.GetType().Name;
}
internal string GetObjectName()
{
UnityEngine.Object obj = SrcObject ?? DstObject;
return obj == null ? null : obj.name;
}
internal bool IsGameObject()
{
return (SrcObject ?? DstObject) is UnityEngine.GameObject;
}
internal UnityEngine.GameObject GetGameObject()
{
UnityEngine.Object obj = SrcObject ?? DstObject;
if (obj is UnityEngine.GameObject go)
return go;
if (obj is UnityEngine.Component c)
return c.gameObject;
return null;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 50a8f133cd03453893ff0072b6c1f3be
timeCreated: 1774982258
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: c5fe7e62b877408882a2c7096800559b
timeCreated: 1774972739
@@ -0,0 +1,14 @@
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff.Property
{
internal class PropertyDiff
{
internal string Path;
internal string DisplayName;
internal string TypeTag;
internal DiffType DiffType;
internal string SrcValue;
internal string DstValue;
internal object SrcTag;
internal object DstTag;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 4d3910fb8d3a4d2c9bd83623e82e0875
timeCreated: 1774968693
@@ -0,0 +1,152 @@
using System.Collections.Generic;
using Unity.PlasticSCM.Editor.Diff.Asset.Common.Property;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff.Property
{
internal class PropertyDiffNode
{
internal NodeKind Kind { get; }
internal string Path { get; }
internal string DisplayName { get; }
internal string TypeTag { get; }
internal DiffType DiffType { get; }
internal string SrcValue { get; }
internal string DstValue { get; }
internal object SrcTag { get; }
internal object DstTag { get; }
internal IReadOnlyList<PropertyDiffNode> Children => mChildren;
internal int LeafCount { get; }
internal DiffTypeFlags DescendantDiffTypes { get; }
internal PropertyDiffNode(
NodeKind kind,
string path,
string displayName,
string typeTag,
DiffType diffType,
string srcValue,
string dstValue,
object srcTag,
object dstTag,
List<PropertyDiffNode> children)
{
Kind = kind;
Path = path ?? string.Empty;
DisplayName = displayName ?? string.Empty;
TypeTag = typeTag ?? string.Empty;
DiffType = diffType;
SrcValue = srcValue;
DstValue = dstValue;
SrcTag = srcTag;
DstTag = dstTag;
mChildren = children ?? EMPTY_CHILDREN;
if (kind == NodeKind.Leaf)
{
LeafCount = 1;
DescendantDiffTypes = ToFlag(diffType);
return;
}
int leafCount = 0;
DiffTypeFlags flags = DiffTypeFlags.None;
foreach (PropertyDiffNode child in mChildren)
{
leafCount += child.LeafCount;
flags |= child.DescendantDiffTypes;
}
LeafCount = leafCount;
DescendantDiffTypes = flags;
}
internal bool HasDescendantOfType(DiffType type)
{
return (DescendantDiffTypes & ToFlag(type)) != DiffTypeFlags.None;
}
internal static PropertyDiffNode CreateLeaf(
string name,
string path,
string typeTag,
DiffType diffType,
string srcValue,
string dstValue,
object srcTag,
object dstTag)
{
return new PropertyDiffNode(
NodeKind.Leaf, path, name, typeTag, diffType,
srcValue, dstValue, srcTag, dstTag, null);
}
internal static PropertyDiffNode CreateContainer(
NodeKind kind,
string name,
string path,
DiffType diffType,
List<PropertyDiffNode> children)
{
return new PropertyDiffNode(
kind, path, name, GetContainerTypeTag(kind), diffType,
null, null, null, null, children);
}
internal static PropertyDiffNode CreateRoot(List<PropertyDiffNode> children)
{
return CreateContainer(
NodeKind.Object, string.Empty, string.Empty,
AggregateDiffType(children), children);
}
internal static DiffType AggregateDiffType(IReadOnlyList<PropertyDiffNode> children)
{
if (children == null || children.Count == 0)
return DiffType.Unchanged;
DiffTypeFlags flags = DiffTypeFlags.None;
foreach (PropertyDiffNode child in children)
flags |= child.DescendantDiffTypes;
int kinds = 0;
if ((flags & DiffTypeFlags.Modified) != 0) kinds++;
if ((flags & DiffTypeFlags.Added) != 0) kinds++;
if ((flags & DiffTypeFlags.Removed) != 0) kinds++;
if (kinds > 1)
return DiffType.Modified;
if ((flags & DiffTypeFlags.Modified) != 0) return DiffType.Modified;
if ((flags & DiffTypeFlags.Added) != 0) return DiffType.Added;
if ((flags & DiffTypeFlags.Removed) != 0) return DiffType.Removed;
return DiffType.Unchanged;
}
static string GetContainerTypeTag(NodeKind kind)
{
return kind == NodeKind.Array ? "Array" : "Generic";
}
static DiffTypeFlags ToFlag(DiffType diffType)
{
switch (diffType)
{
case DiffType.Modified: return DiffTypeFlags.Modified;
case DiffType.Added: return DiffTypeFlags.Added;
case DiffType.Removed: return DiffTypeFlags.Removed;
default: return DiffTypeFlags.None;
}
}
static readonly List<PropertyDiffNode> EMPTY_CHILDREN = new List<PropertyDiffNode>();
readonly List<PropertyDiffNode> mChildren;
}
[System.Flags]
internal enum DiffTypeFlags : byte
{
None = 0,
Modified = 1,
Added = 2,
Removed = 4
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: c51db94de72c446c9a3f5e6752c3cc3b
timeCreated: 1747310500
@@ -0,0 +1,697 @@
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using Unity.PlasticSCM.Editor.Diff.Asset.Common.Property;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff.Property
{
internal static class PropertyDiffs
{
internal static List<PropertyDiff> Compare(
PropertyTreeNode src,
PropertyTreeNode dst)
{
return Flatten(BuildDiffTree(src, dst));
}
internal static PropertyDiffNode BuildDiffTree(
PropertyTreeNode src,
PropertyTreeNode dst)
{
return BuildDiffTree(src, dst, DEFAULT_ARRAY_MATCH_THRESHOLD);
}
internal static List<PropertyDiff> Flatten(PropertyDiffNode tree)
{
List<PropertyDiff> results = new List<PropertyDiff>();
if (tree != null)
FlattenInto(tree, results);
return results;
}
static PropertyDiffNode BuildDiffTree(
PropertyTreeNode src,
PropertyTreeNode dst,
double arrayMatchThreshold)
{
if (src == null && dst == null)
return null;
if (src == null)
return BuildAllAdded(dst);
if (dst == null)
return BuildAllRemoved(src);
List<PropertyDiffNode> children = new List<PropertyDiffNode>();
BuildChildren(src, dst, arrayMatchThreshold, children);
if (children.Count == 0)
return null;
StableSortByDiffType(children);
return PropertyDiffNode.CreateRoot(children);
}
static void StableSortByDiffType(List<PropertyDiffNode> children)
{
int count = children.Count;
if (count <= 1)
return;
int[] order = new int[count];
for (int i = 0; i < count; i++)
order[i] = i;
System.Array.Sort(order, (a, b) =>
{
int delta = GetDiffTypeOrder(children[a].DiffType)
- GetDiffTypeOrder(children[b].DiffType);
if (delta != 0)
return delta;
return a - b;
});
PropertyDiffNode[] sorted = new PropertyDiffNode[count];
for (int i = 0; i < count; i++)
sorted[i] = children[order[i]];
for (int i = 0; i < count; i++)
children[i] = sorted[i];
}
static int GetDiffTypeOrder(DiffType diffType)
{
switch (diffType)
{
case DiffType.Modified: return 0;
case DiffType.Added: return 1;
case DiffType.Removed: return 2;
default: return 3;
}
}
static void FlattenInto(PropertyDiffNode node, List<PropertyDiff> results)
{
if (node.Kind == NodeKind.Leaf)
{
results.Add(ToFlatDiff(node));
return;
}
foreach (PropertyDiffNode child in node.Children)
FlattenInto(child, results);
}
static PropertyDiff ToFlatDiff(PropertyDiffNode node)
{
return new PropertyDiff
{
Path = node.Path,
DisplayName = node.DisplayName,
TypeTag = node.TypeTag,
DiffType = node.DiffType,
SrcValue = node.SrcValue,
DstValue = node.DstValue,
SrcTag = node.SrcTag,
DstTag = node.DstTag
};
}
static void AppendPair(
PropertyTreeNode src,
PropertyTreeNode dst,
double arrayMatchThreshold,
List<PropertyDiffNode> results)
{
if (src.Kind == NodeKind.Leaf && dst.Kind == NodeKind.Leaf)
{
if (LeafValuesEqual(src, dst))
return;
results.Add(PropertyDiffNode.CreateLeaf(
dst.DisplayName, dst.Path, dst.TypeTag,
DiffType.Modified,
src.Value, dst.Value, src.Tag, dst.Tag));
return;
}
if (src.Kind == NodeKind.Leaf || dst.Kind == NodeKind.Leaf)
{
results.Add(BuildAllRemoved(src));
results.Add(BuildAllAdded(dst));
return;
}
List<PropertyDiffNode> children = new List<PropertyDiffNode>();
BuildChildren(src, dst, arrayMatchThreshold, children);
if (children.Count == 0)
return;
StableSortByDiffType(children);
// When the parent exists on both sides (we're inside AppendPair)
// but one side was empty, AggregateDiffType would collapse to
// Added/Removed because every child carries a single DiffType.
// The parent itself didn't appear or disappear — its contents
// changed — so the right rollup is Modified.
DiffType parentDiffType =
(src.Children.Count == 0) != (dst.Children.Count == 0)
? DiffType.Modified
: PropertyDiffNode.AggregateDiffType(children);
results.Add(PropertyDiffNode.CreateContainer(
dst.Kind, dst.DisplayName, dst.Path,
parentDiffType,
children));
}
static void BuildChildren(
PropertyTreeNode src,
PropertyTreeNode dst,
double arrayMatchThreshold,
List<PropertyDiffNode> results)
{
if (src.Kind == NodeKind.Array && dst.Kind == NodeKind.Array)
BuildArrayChildren(src, dst, arrayMatchThreshold, results);
else
BuildNamedChildren(src, dst, arrayMatchThreshold, results);
}
static void BuildNamedChildren(
PropertyTreeNode src,
PropertyTreeNode dst,
double arrayMatchThreshold,
List<PropertyDiffNode> results)
{
NameIndex dstIndex = NameIndex.Build(dst.Children);
HashSet<PropertyTreeNode> matchedDst = new HashSet<PropertyTreeNode>(
ReferenceEqualityComparer.Instance);
foreach (PropertyTreeNode srcChild in src.Children)
{
PropertyTreeNode dstChild = dstIndex.FindAndRemove(srcChild.Name);
if (dstChild != null)
{
matchedDst.Add(dstChild);
AppendPair(srcChild, dstChild, arrayMatchThreshold, results);
}
else
{
results.Add(BuildAllRemoved(srcChild));
}
}
foreach (PropertyTreeNode dstChild in dst.Children)
{
if (!matchedDst.Contains(dstChild))
results.Add(BuildAllAdded(dstChild));
}
}
static void BuildArrayChildren(
PropertyTreeNode srcArray,
PropertyTreeNode dstArray,
double arrayMatchThreshold,
List<PropertyDiffNode> results)
{
IReadOnlyList<PropertyTreeNode> srcChildren = srcArray.Children;
IReadOnlyList<PropertyTreeNode> dstChildren = dstArray.Children;
HashSet<PropertyTreeNode> matchedSrc = new HashSet<PropertyTreeNode>(
ReferenceEqualityComparer.Instance);
HashSet<PropertyTreeNode> matchedDst = new HashSet<PropertyTreeNode>(
ReferenceEqualityComparer.Instance);
// Pair elements equal at the same index first, so a single value
// change in an ordered array (e.g. m_Materials[0]) is not drowned
// out by bag-style matching of duplicates elsewhere.
int commonLen = System.Math.Min(srcChildren.Count, dstChildren.Count);
for (int i = 0; i < commonLen; i++)
{
PropertyTreeNode srcAtI = srcChildren[i];
PropertyTreeNode dstAtI = dstChildren[i];
if (!EqualElementsSearcher.StructuralEquals(srcAtI, dstAtI))
continue;
matchedSrc.Add(srcAtI);
matchedDst.Add(dstAtI);
}
List<PropertyTreeNode> srcRemaining = BuildUnmatched(srcChildren, matchedSrc);
List<PropertyTreeNode> dstRemaining = BuildUnmatched(dstChildren, matchedDst);
List<NodeMatch> equalMatches =
EqualElementsSearcher.Find(srcRemaining, dstRemaining);
foreach (NodeMatch match in equalMatches)
{
matchedSrc.Add(match.Src);
matchedDst.Add(match.Dst);
}
srcRemaining = BuildUnmatched(srcChildren, matchedSrc);
dstRemaining = BuildUnmatched(dstChildren, matchedDst);
List<NodeMatch> modifiedMatches =
ModifiedElementsSearcher.Find(
srcRemaining, dstRemaining, arrayMatchThreshold);
foreach (NodeMatch match in modifiedMatches)
{
AppendPair(match.Src, match.Dst, arrayMatchThreshold, results);
matchedSrc.Add(match.Src);
matchedDst.Add(match.Dst);
}
// Leaves cannot match through the similarity searcher (leaf
// similarity is 0 or 1). Pair the survivors by their relative
// order so a single-leaf change becomes Modified, not Add+Remove.
PairRemainingLeavesByPosition(
srcChildren, dstChildren, matchedSrc, matchedDst,
arrayMatchThreshold, results);
foreach (PropertyTreeNode node in srcChildren)
if (!matchedSrc.Contains(node))
results.Add(BuildAllRemoved(node));
foreach (PropertyTreeNode node in dstChildren)
if (!matchedDst.Contains(node))
results.Add(BuildAllAdded(node));
}
static void PairRemainingLeavesByPosition(
IReadOnlyList<PropertyTreeNode> srcChildren,
IReadOnlyList<PropertyTreeNode> dstChildren,
HashSet<PropertyTreeNode> matchedSrc,
HashSet<PropertyTreeNode> matchedDst,
double arrayMatchThreshold,
List<PropertyDiffNode> results)
{
List<PropertyTreeNode> srcLeaves = CollectUnmatchedLeaves(srcChildren, matchedSrc);
List<PropertyTreeNode> dstLeaves = CollectUnmatchedLeaves(dstChildren, matchedDst);
int pairCount = System.Math.Min(srcLeaves.Count, dstLeaves.Count);
for (int i = 0; i < pairCount; i++)
{
PropertyTreeNode srcLeaf = srcLeaves[i];
PropertyTreeNode dstLeaf = dstLeaves[i];
if (srcLeaf.TypeTag != dstLeaf.TypeTag)
continue;
AppendPair(srcLeaf, dstLeaf, arrayMatchThreshold, results);
matchedSrc.Add(srcLeaf);
matchedDst.Add(dstLeaf);
}
}
static List<PropertyTreeNode> CollectUnmatchedLeaves(
IReadOnlyList<PropertyTreeNode> children,
HashSet<PropertyTreeNode> matched)
{
List<PropertyTreeNode> leaves = new List<PropertyTreeNode>();
foreach (PropertyTreeNode node in children)
{
if (node.Kind != NodeKind.Leaf)
continue;
if (matched.Contains(node))
continue;
leaves.Add(node);
}
return leaves;
}
static PropertyDiffNode BuildAllAdded(PropertyTreeNode node)
{
if (node.Kind == NodeKind.Leaf)
{
return PropertyDiffNode.CreateLeaf(
node.DisplayName, node.Path, node.TypeTag,
DiffType.Added,
null, node.Value, null, node.Tag);
}
List<PropertyDiffNode> children = new List<PropertyDiffNode>(node.Children.Count);
foreach (PropertyTreeNode child in node.Children)
children.Add(BuildAllAdded(child));
return PropertyDiffNode.CreateContainer(
node.Kind, node.DisplayName, node.Path,
DiffType.Added, children);
}
static PropertyDiffNode BuildAllRemoved(PropertyTreeNode node)
{
if (node.Kind == NodeKind.Leaf)
{
return PropertyDiffNode.CreateLeaf(
node.DisplayName, node.Path, node.TypeTag,
DiffType.Removed,
node.Value, null, node.Tag, null);
}
List<PropertyDiffNode> children = new List<PropertyDiffNode>(node.Children.Count);
foreach (PropertyTreeNode child in node.Children)
children.Add(BuildAllRemoved(child));
return PropertyDiffNode.CreateContainer(
node.Kind, node.DisplayName, node.Path,
DiffType.Removed, children);
}
static List<PropertyTreeNode> BuildUnmatched(
IReadOnlyList<PropertyTreeNode> children,
HashSet<PropertyTreeNode> matched)
{
List<PropertyTreeNode> remaining = new List<PropertyTreeNode>(
children.Count - matched.Count);
foreach (PropertyTreeNode node in children)
if (!matched.Contains(node))
remaining.Add(node);
return remaining;
}
internal static bool LeafValuesEqual(PropertyTreeNode src, PropertyTreeNode dst)
{
if (src.TypeTag != dst.TypeTag
|| !(src.Tag is LeafPropertyData srcData)
|| !(dst.Tag is LeafPropertyData dstData))
{
return src.Value == dst.Value;
}
switch (srcData.PropertyType)
{
case SerializedPropertyType.Float:
return srcData.FloatValue.Equals(dstData.FloatValue);
case SerializedPropertyType.Integer:
case SerializedPropertyType.LayerMask:
case SerializedPropertyType.Character:
case SerializedPropertyType.Enum:
return srcData.IntValue == dstData.IntValue;
case SerializedPropertyType.Boolean:
return srcData.BoolValue == dstData.BoolValue;
case SerializedPropertyType.String:
return srcData.StringValue == dstData.StringValue;
case SerializedPropertyType.Vector2:
return srcData.Vector2Value.Equals(dstData.Vector2Value);
case SerializedPropertyType.Vector3:
return srcData.Vector3Value.Equals(dstData.Vector3Value);
case SerializedPropertyType.Vector4:
return srcData.Vector4Value.Equals(dstData.Vector4Value);
case SerializedPropertyType.Vector2Int:
return srcData.Vector2IntValue.Equals(dstData.Vector2IntValue);
case SerializedPropertyType.Vector3Int:
return srcData.Vector3IntValue.Equals(dstData.Vector3IntValue);
case SerializedPropertyType.Color:
return srcData.ColorValue.Equals(dstData.ColorValue);
case SerializedPropertyType.Quaternion:
return srcData.QuaternionValue.Equals(dstData.QuaternionValue);
case SerializedPropertyType.Rect:
return srcData.RectValue.Equals(dstData.RectValue);
case SerializedPropertyType.Bounds:
return srcData.BoundsValue.Equals(dstData.BoundsValue);
case SerializedPropertyType.RectInt:
return srcData.RectIntValue.Equals(dstData.RectIntValue);
case SerializedPropertyType.BoundsInt:
return srcData.BoundsIntValue.Equals(dstData.BoundsIntValue);
case SerializedPropertyType.Hash128:
return srcData.Hash128Value.Equals(dstData.Hash128Value);
case SerializedPropertyType.AnimationCurve:
return Equals(srcData.AnimationCurveValue, dstData.AnimationCurveValue);
case SerializedPropertyType.Gradient:
return Equals(srcData.GradientValue, dstData.GradientValue);
default:
return src.Value == dst.Value;
}
}
const double DEFAULT_ARRAY_MATCH_THRESHOLD = 0.5;
}
static class EqualElementsSearcher
{
internal static List<NodeMatch> Find(
IReadOnlyList<PropertyTreeNode> srcElements,
IReadOnlyList<PropertyTreeNode> dstElements)
{
List<NodeMatch> matches = new List<NodeMatch>();
HashSet<PropertyTreeNode> usedDst = new HashSet<PropertyTreeNode>(
ReferenceEqualityComparer.Instance);
foreach (PropertyTreeNode src in srcElements)
{
foreach (PropertyTreeNode dst in dstElements)
{
if (usedDst.Contains(dst))
continue;
if (!StructuralEquals(src, dst))
continue;
matches.Add(new NodeMatch(src, dst));
usedDst.Add(dst);
break;
}
}
return matches;
}
internal static bool StructuralEquals(
PropertyTreeNode a, PropertyTreeNode b)
{
if (a.Kind != b.Kind)
return false;
if (a.Kind == NodeKind.Leaf)
return a.TypeTag == b.TypeTag && PropertyDiffs.LeafValuesEqual(a, b);
if (a.Children.Count != b.Children.Count)
return false;
for (int i = 0; i < a.Children.Count; i++)
{
if (a.Kind == NodeKind.Object &&
a.Children[i].Name != b.Children[i].Name)
return false;
if (!StructuralEquals(a.Children[i], b.Children[i]))
return false;
}
return true;
}
}
static class ModifiedElementsSearcher
{
internal static List<NodeMatch> Find(
IReadOnlyList<PropertyTreeNode> srcElements,
IReadOnlyList<PropertyTreeNode> dstElements,
double minSimilarityThreshold)
{
Dictionary<string, string>[] srcLeaves = SimilarityCalculator.BuildLeafMaps(srcElements);
Dictionary<string, string>[] dstLeaves = SimilarityCalculator.BuildLeafMaps(dstElements);
List<NodeMatch> matches = new List<NodeMatch>();
HashSet<int> usedDst = new HashSet<int>();
for (int i = 0; i < srcElements.Count; i++)
{
int bestIdx = -1;
double bestSimilarity = minSimilarityThreshold;
for (int j = 0; j < dstElements.Count; j++)
{
if (usedDst.Contains(j))
continue;
double similarity = SimilarityCalculator.CalculateFromLeaves(
srcLeaves[i], dstLeaves[j]);
if (similarity <= bestSimilarity)
continue;
bestIdx = j;
bestSimilarity = similarity;
}
if (bestIdx < 0)
continue;
matches.Add(new NodeMatch(srcElements[i], dstElements[bestIdx]));
usedDst.Add(bestIdx);
}
return matches;
}
}
static class SimilarityCalculator
{
internal static Dictionary<string, string>[] BuildLeafMaps(
IReadOnlyList<PropertyTreeNode> elements)
{
Dictionary<string, string>[] maps = new Dictionary<string, string>[elements.Count];
for (int i = 0; i < elements.Count; i++)
{
maps[i] = new Dictionary<string, string>();
CollectRelativeLeaves(elements[i], string.Empty, maps[i]);
}
return maps;
}
internal static double Calculate(
PropertyTreeNode a, PropertyTreeNode b)
{
if (a.Kind == NodeKind.Leaf && b.Kind == NodeKind.Leaf)
{
if (a.TypeTag != b.TypeTag)
return 0.0;
return a.Value == b.Value ? 1.0 : 0.0;
}
if (a.Kind == NodeKind.Leaf || b.Kind == NodeKind.Leaf)
return 0.0;
Dictionary<string, string> leavesA = new Dictionary<string, string>();
Dictionary<string, string> leavesB = new Dictionary<string, string>();
CollectRelativeLeaves(a, string.Empty, leavesA);
CollectRelativeLeaves(b, string.Empty, leavesB);
return CalculateFromLeaves(leavesA, leavesB);
}
internal static double CalculateFromLeaves(
Dictionary<string, string> leavesA,
Dictionary<string, string> leavesB)
{
if (leavesA.Count == 0 && leavesB.Count == 0)
return 1.0;
int totalPaths = leavesA.Count;
int matchCount = 0;
foreach (KeyValuePair<string, string> kvp in leavesA)
{
if (leavesB.TryGetValue(kvp.Key, out string valueB))
{
if (kvp.Value == valueB)
matchCount++;
}
}
foreach (KeyValuePair<string, string> kvp in leavesB)
{
if (!leavesA.ContainsKey(kvp.Key))
totalPaths++;
}
if (totalPaths == 0)
return 1.0;
return (double)matchCount / totalPaths;
}
internal static void CollectRelativeLeaves(
PropertyTreeNode node,
string prefix,
Dictionary<string, string> leaves)
{
if (node.Kind == NodeKind.Leaf)
{
string key = string.IsNullOrEmpty(prefix) ? node.Name : prefix;
leaves[key] = string.Concat(node.TypeTag, "\0", node.Value ?? string.Empty);
return;
}
foreach (PropertyTreeNode child in node.Children)
{
string childPath = string.IsNullOrEmpty(prefix)
? child.Name
: prefix + "." + child.Name;
CollectRelativeLeaves(child, childPath, leaves);
}
}
}
class NameIndex
{
internal static NameIndex Build(IReadOnlyList<PropertyTreeNode> children)
{
NameIndex index = new NameIndex();
foreach (PropertyTreeNode child in children)
{
if (!index.mPropertiesByName.TryGetValue(child.Name, out List<PropertyTreeNode> list))
{
list = new List<PropertyTreeNode>();
index.mPropertiesByName[child.Name] = list;
}
list.Add(child);
}
return index;
}
internal PropertyTreeNode FindAndRemove(string name)
{
if (!mPropertiesByName.TryGetValue(name, out List<PropertyTreeNode> list))
return null;
if (!mCursorsByName.TryGetValue(name, out int cursor))
cursor = 0;
if (cursor >= list.Count)
return null;
mCursorsByName[name] = cursor + 1;
return list[cursor];
}
readonly Dictionary<string, List<PropertyTreeNode>> mPropertiesByName =
new Dictionary<string, List<PropertyTreeNode>>();
readonly Dictionary<string, int> mCursorsByName =
new Dictionary<string, int>();
}
class ReferenceEqualityComparer : IEqualityComparer<PropertyTreeNode>
{
internal static readonly ReferenceEqualityComparer Instance =
new ReferenceEqualityComparer();
public bool Equals(PropertyTreeNode x, PropertyTreeNode y)
{
return ReferenceEquals(x, y);
}
public int GetHashCode(PropertyTreeNode obj)
{
return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj);
}
}
struct NodeMatch
{
internal PropertyTreeNode Src;
internal PropertyTreeNode Dst;
internal NodeMatch(PropertyTreeNode src, PropertyTreeNode dst)
{
Src = src;
Dst = dst;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 4f44bcd033dc4c30a0456a2cc9a47818
timeCreated: 1774968514
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 4ab5cfecaea4f4c34a32783932e0b88e
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,149 @@
using System.Collections.Generic;
using Unity.PlasticSCM.Editor.Diff.Asset.Common.Property;
using Unity.PlasticSCM.Editor.Diff.Asset.Diff.Property;
using Unity.PlasticSCM.Editor.Diff.Asset.Common;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff.Search
{
internal class PropertyDiffSearchIndex
{
internal bool IsActive { get; }
internal static PropertyDiffSearchIndex Build(
IList<ObjectDiff> objectDiffs, string searchTerm)
{
if (string.IsNullOrEmpty(searchTerm))
return new PropertyDiffSearchIndex(isActive: false, null);
HashSet<PropertyDiffNode> visible = new HashSet<PropertyDiffNode>();
foreach (ObjectDiff objDiff in objectDiffs)
{
bool objectInScope = ObjectNameMatches(objDiff, searchTerm);
CollectVisibleForObject(
objDiff.PropertyDiffTree, searchTerm, objectInScope, visible);
if (objDiff.ComponentDiffs == null)
continue;
foreach (ObjectDiff comp in objDiff.ComponentDiffs)
{
bool componentInScope = objectInScope
|| ObjectNameMatches(comp, searchTerm);
CollectVisibleForObject(
comp.PropertyDiffTree, searchTerm, componentInScope, visible);
}
}
return new PropertyDiffSearchIndex(isActive: true, visible);
}
static bool ObjectNameMatches(ObjectDiff diff, string searchTerm)
{
return SearchMatcher.Contains(diff.GetSrcDisplayName(), searchTerm)
|| SearchMatcher.Contains(diff.GetDstDisplayName(), searchTerm);
}
static void CollectVisibleForObject(
PropertyDiffNode root,
string searchTerm,
bool ownerNameMatches,
HashSet<PropertyDiffNode> visible)
{
if (root == null)
return;
if (ownerNameMatches)
{
foreach (PropertyDiffNode child in root.Children)
AddSubtree(child, visible);
return;
}
CollectVisible(root, searchTerm, visible);
}
internal bool IsNodeVisible(PropertyDiffNode node)
{
if (!IsActive)
return true;
return mVisibleNodes.Contains(node);
}
internal bool SubtreeHasMatch(ObjectDiff diff)
{
if (!IsActive)
return false;
if (diff.PropertyDiffTree == null)
return false;
foreach (PropertyDiffNode child in diff.PropertyDiffTree.Children)
{
if (mVisibleNodes.Contains(child))
return true;
}
return false;
}
PropertyDiffSearchIndex(bool isActive, HashSet<PropertyDiffNode> visibleNodes)
{
IsActive = isActive;
mVisibleNodes = visibleNodes;
}
static bool CollectVisible(
PropertyDiffNode node,
string searchTerm,
HashSet<PropertyDiffNode> visible)
{
if (node == null)
return false;
if (node.Kind == NodeKind.Leaf)
{
string label = node.DisplayName ?? node.Path;
bool matches =
SearchMatcher.Contains(label, searchTerm) ||
SearchMatcher.Contains(node.Path, searchTerm);
if (matches)
visible.Add(node);
return matches;
}
bool nodeMatches =
SearchMatcher.Contains(node.DisplayName, searchTerm) ||
SearchMatcher.Contains(node.Path, searchTerm);
if (nodeMatches)
{
AddSubtree(node, visible);
return true;
}
bool anyChildMatches = false;
foreach (PropertyDiffNode child in node.Children)
{
if (CollectVisible(child, searchTerm, visible))
anyChildMatches = true;
}
if (anyChildMatches)
visible.Add(node);
return anyChildMatches;
}
static void AddSubtree(
PropertyDiffNode node, HashSet<PropertyDiffNode> visible)
{
visible.Add(node);
foreach (PropertyDiffNode child in node.Children)
AddSubtree(child, visible);
}
readonly HashSet<PropertyDiffNode> mVisibleNodes;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 89b3139f91265476ca27e556676deaaa
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: b76140aafe154f1aaa659bebc7f9316e
timeCreated: 1775037677
@@ -0,0 +1,161 @@
using System.Collections.Generic;
using UnityEngine;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff.UnityObject
{
// Detects component reorders inside each paired GameObject. Components
// are matched by type-name labels (with #N suffix to disambiguate
// duplicates), and "common" labels — present on both sides — define the
// reference order. Pure moves emit a Modified ObjectDiff with no
// PropertyDiffs and a non-zero PositionDelta.
internal static class ComponentReorderDiffs
{
internal static void Append(
Dictionary<long, UnityEngine.Object> srcById,
Dictionary<long, UnityEngine.Object> dstById,
List<ObjectDiff> objectDiffs)
{
// Index existing Component diffs so a reorder annotation can update
// them in place instead of creating a duplicate row.
Dictionary<Component, ObjectDiff> bySrcComponent =
new Dictionary<Component, ObjectDiff>();
Dictionary<Component, ObjectDiff> byDstComponent =
new Dictionary<Component, ObjectDiff>();
foreach (ObjectDiff diff in objectDiffs)
{
if (diff.SrcObject is Component sc) bySrcComponent[sc] = diff;
if (diff.DstObject is Component dc) byDstComponent[dc] = diff;
}
foreach (KeyValuePair<long, UnityEngine.Object> kvp in srcById)
{
if (!(kvp.Value is GameObject srcGo))
continue;
if (!dstById.TryGetValue(kvp.Key, out UnityEngine.Object dstObj))
continue;
if (!(dstObj is GameObject dstGo))
continue;
AppendReordersForGameObjectPair(
srcGo, dstGo,
bySrcComponent, byDstComponent,
objectDiffs);
}
}
static void AppendReordersForGameObjectPair(
GameObject srcGo,
GameObject dstGo,
Dictionary<Component, ObjectDiff> bySrcComponent,
Dictionary<Component, ObjectDiff> byDstComponent,
List<ObjectDiff> objectDiffs)
{
List<LabeledComponent> srcLabeled = BuildLabeledComponents(
srcGo.GetComponents<Component>());
List<LabeledComponent> dstLabeled = BuildLabeledComponents(
dstGo.GetComponents<Component>());
HashSet<string> srcLabelSet = new HashSet<string>();
foreach (LabeledComponent lc in srcLabeled)
srcLabelSet.Add(lc.Label);
HashSet<string> common = new HashSet<string>();
foreach (LabeledComponent lc in dstLabeled)
{
if (srcLabelSet.Contains(lc.Label))
common.Add(lc.Label);
}
if (common.Count < 2)
return;
// Position is measured against the relative order of components
// present on both sides — additions and removals don't count as
// "everyone moved".
List<LabeledComponent> srcCommon = FilterByCommon(srcLabeled, common);
List<LabeledComponent> dstCommon = FilterByCommon(dstLabeled, common);
Dictionary<string, int> srcPos = BuildPositionIndex(srcCommon);
Dictionary<string, int> dstPos = BuildPositionIndex(dstCommon);
foreach (string label in common)
{
int delta = dstPos[label] - srcPos[label];
if (delta == 0)
continue;
Component srcComp = srcCommon[srcPos[label]].Component;
Component dstComp = dstCommon[dstPos[label]].Component;
ObjectDiff existing = null;
if (srcComp != null) bySrcComponent.TryGetValue(srcComp, out existing);
if (existing == null && dstComp != null)
byDstComponent.TryGetValue(dstComp, out existing);
if (existing != null)
{
existing.PositionDelta = delta;
continue;
}
// Component moved but its content is unchanged — emit a
// Modified diff with no PropertyDiffs so the row still appears.
objectDiffs.Add(new ObjectDiff
{
SrcObject = srcComp,
DstObject = dstComp,
DiffType = DiffType.Modified,
PositionDelta = delta
});
}
}
static List<LabeledComponent> BuildLabeledComponents(Component[] components)
{
List<LabeledComponent> result = new List<LabeledComponent>(components.Length);
Dictionary<string, int> seen = new Dictionary<string, int>();
foreach (Component c in components)
{
string typeName = c == null ? "<missing>" : c.GetType().Name;
string label = seen.TryGetValue(typeName, out int n)
? typeName + "#" + (n + 1)
: typeName;
seen[typeName] = n + 1;
result.Add(new LabeledComponent { Label = label, Component = c });
}
return result;
}
static List<LabeledComponent> FilterByCommon(
List<LabeledComponent> labeled, HashSet<string> common)
{
List<LabeledComponent> result = new List<LabeledComponent>(labeled.Count);
foreach (LabeledComponent lc in labeled)
{
if (common.Contains(lc.Label))
result.Add(lc);
}
return result;
}
static Dictionary<string, int> BuildPositionIndex(List<LabeledComponent> labeled)
{
Dictionary<string, int> result = new Dictionary<string, int>(labeled.Count);
for (int i = 0; i < labeled.Count; i++)
result[labeled[i].Label] = i;
return result;
}
struct LabeledComponent
{
internal string Label;
internal Component Component;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f3dabef31c2a490faec225c13c37076d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,105 @@
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff.UnityObject
{
// Classifies objects returned by InternalEditorUtility.LoadSerializedFileAndForget
// to detect cases where the loader silently dropped serialized data.
//
// Each rule below names a specific failure mode in Unity's loader:
//
// - Type was substituted with UnityEditor.FallbackEditorWindow because
// the MonoScript could not be resolved (the loader uses the
// kAutoreplaceEditorWindow flag — see EditorWindowController.cpp in
// the Unity reference repo).
// - MonoBehaviour with no resolvable script reference. Fields beyond
// base MonoBehaviour are gone.
// - AnimatorOverrideController with a null runtimeAnimatorController.
// AwakeFromLoad → BuildAsset wipes m_Clips whenever the controller
// is null (see Modules/Animation/AnimatorOverrideController.cpp),
// so any clip-override data in the YAML is hidden from the diff.
//
// New failure modes go here as new rules. We deliberately do not
// surface a generic "something looks off" signal — every kind names a
// concrete problem so the UI can explain it accurately.
internal static class DataLossDetection
{
internal static Dictionary<UnityEngine.Object, DataLossKind> DetectPerObject(
UnityEngine.Object[] loadedObjects)
{
Dictionary<UnityEngine.Object, DataLossKind> map =
new Dictionary<UnityEngine.Object, DataLossKind>();
if (loadedObjects == null)
return map;
foreach (UnityEngine.Object obj in loadedObjects)
{
if (obj == null)
continue;
DataLossKind kind = Classify(obj);
if (kind != DataLossKind.None)
map[obj] = kind;
}
return map;
}
internal static DataLossKind LookupOrNone(
Dictionary<UnityEngine.Object, DataLossKind> map,
UnityEngine.Object obj)
{
if (obj == null || map == null)
return DataLossKind.None;
return map.TryGetValue(obj, out DataLossKind kind)
? kind
: DataLossKind.None;
}
// Higher enum value wins (most specific reason surfaced to the user).
internal static DataLossKind PickMoreSpecific(DataLossKind a, DataLossKind b)
{
return (int)a >= (int)b ? a : b;
}
static DataLossKind Classify(UnityEngine.Object obj)
{
// UnityEditor.FallbackEditorWindow is internal; match by full
// type name to avoid a hard reference. Catches the case where
// the loader substituted the type because the script couldn't
// be resolved.
if (obj.GetType().FullName == FALLBACK_EDITOR_WINDOW_TYPE_NAME)
return DataLossKind.FallbackEditorWindow;
if (obj is MonoBehaviour mb)
{
MonoScript script = MonoScript.FromMonoBehaviour(mb);
if (script == null || script.GetClass() == null)
return DataLossKind.UnresolvedMonoScript;
}
if (obj is AnimatorOverrideController aoc
&& aoc.runtimeAnimatorController == null)
{
// BuildAsset wipes m_Clips whenever the controller is
// null, regardless of WHY it's null (unresolvable external
// reference, deleted asset, or genuinely unassigned). The
// warning is accurate either way: any clip-override data
// in the YAML will be hidden from the diff. An AOC that
// legitimately has no controller AND no clips is
// byte-identical across src/dst, so the diff layer never
// calls into this detector for that case.
return DataLossKind.UnresolvedAnimatorController;
}
return DataLossKind.None;
}
const string FALLBACK_EDITOR_WINDOW_TYPE_NAME =
"UnityEditor.FallbackEditorWindow";
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 96b536fd344e43cfbc9a81e3c6f151a0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,91 @@
using System;
using System.Collections.Generic;
using System.IO;
using Codice.LogWrapper;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff.UnityObject
{
internal struct FileIdInfo
{
internal List<long> FileIds;
internal Dictionary<long, long> HashByFileId;
}
internal static class FileIdReader
{
internal static FileIdInfo Read(string yamlFilePath)
{
FileIdInfo result = new FileIdInfo
{
FileIds = new List<long>(),
HashByFileId = new Dictionary<long, long>()
};
try
{
using (StreamReader reader = new StreamReader(yamlFilePath))
{
string line;
long currentFileId = 0;
long currentHash = 0;
bool inBlock = false;
while ((line = reader.ReadLine()) != null)
{
if (line.StartsWith("--- !u!", StringComparison.Ordinal))
{
if (inBlock)
result.HashByFileId[currentFileId] = currentHash;
inBlock = false;
currentFileId = 0;
currentHash = 0;
int ampIdx = line.IndexOf('&');
if (ampIdx < 0)
continue;
ReadOnlySpan<char> idSpan = line.AsSpan(ampIdx + 1).Trim();
if (long.TryParse(idSpan, out long fileId))
{
result.FileIds.Add(fileId);
currentFileId = fileId;
inBlock = true;
}
continue;
}
if (inBlock)
{
unchecked
{
currentHash = currentHash * 1099511628211 + line.GetHashCode();
}
}
}
if (inBlock)
result.HashByFileId[currentFileId] = currentHash;
}
}
catch (Exception ex)
{
mLog.ErrorFormat(
"Error reading file IDs from '{0}': {1}",
yamlFilePath, ex.Message);
mLog.DebugFormat(
"Stack trace:{0}{1}",
Environment.NewLine, ex.StackTrace);
result.FileIds = new List<long>();
result.HashByFileId = new Dictionary<long, long>();
}
return result;
}
static readonly ILog mLog = PlasticApp.GetLogger("FileIdReader");
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: dc310e3d65493434fbd4ee114db86a19
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,179 @@
using System.Collections.Generic;
using Unity.PlasticSCM.Editor.Diff.Asset.Common.Property;
using Unity.PlasticSCM.Editor.Diff.Asset.Diff.Property;
using UnityEditor;
using Unity.PlasticSCM.Editor.Diff.Asset.Common;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff.UnityObject
{
internal static class IdentityPairedDiffs
{
internal static void Build(
Dictionary<long, UnityEngine.Object> srcById,
Dictionary<long, UnityEngine.Object> dstById,
Dictionary<long, long> srcBlockHashes,
Dictionary<long, long> dstBlockHashes,
Dictionary<UnityEngine.Object, DataLossKind> srcDataLoss,
Dictionary<UnityEngine.Object, DataLossKind> dstDataLoss,
List<ObjectDiff> objectDiffs)
{
HashSet<long> matchedDstIds = new HashSet<long>();
foreach (KeyValuePair<long, UnityEngine.Object> kvp in srcById)
{
if (!dstById.TryGetValue(kvp.Key, out UnityEngine.Object dstObj))
{
AddRemovedDiff(kvp.Value, srcDataLoss, objectDiffs);
continue;
}
matchedDstIds.Add(kvp.Key);
if (IsBlockUnchanged(kvp.Key, srcBlockHashes, dstBlockHashes))
continue;
AddModifiedDiff(
kvp.Value, dstObj, srcDataLoss, dstDataLoss, objectDiffs);
}
foreach (KeyValuePair<long, UnityEngine.Object> kvp in dstById)
{
if (!matchedDstIds.Contains(kvp.Key))
AddAddedDiff(kvp.Value, dstDataLoss, objectDiffs);
}
}
internal static Dictionary<long, UnityEngine.Object> BuildFileIdMap(
UnityEngine.Object[] objects)
{
// LoadSerializedFileAndForget returns objects in an order that does not
// match the YAML block order, so we cannot zip by index. Read each
// object's actual local file ID from its serialized state instead.
Dictionary<long, UnityEngine.Object> map =
new Dictionary<long, UnityEngine.Object>(objects.Length);
foreach (UnityEngine.Object obj in objects)
{
if (obj == null)
continue;
long fileId = obj.GetLocalFileId();
if (fileId == 0)
continue;
map[fileId] = obj;
}
return map;
}
internal static int CountNonNull(UnityEngine.Object[] objects)
{
int n = 0;
foreach (UnityEngine.Object o in objects)
if (o != null) n++;
return n;
}
// Foundational diff builders. Used by both this pass and NameMatchedDiffs.
internal static void AddModifiedDiff(
UnityEngine.Object srcObj,
UnityEngine.Object dstObj,
Dictionary<UnityEngine.Object, DataLossKind> srcDataLoss,
Dictionary<UnityEngine.Object, DataLossKind> dstDataLoss,
List<ObjectDiff> objectDiffs)
{
ObjectDiff diff = new ObjectDiff
{
SrcObject = srcObj,
DstObject = dstObj,
DataLoss = DataLossDetection.PickMoreSpecific(
DataLossDetection.LookupOrNone(srcDataLoss, srcObj),
DataLossDetection.LookupOrNone(dstDataLoss, dstObj))
};
using (SerializedObject srcSO = new SerializedObject(srcObj))
using (SerializedObject dstSO = new SerializedObject(dstObj))
{
PropertyTreeNode srcTree = PropertyTreeBuilder.Build(srcSO);
PropertyTreeNode dstTree = PropertyTreeBuilder.Build(dstSO);
diff.PropertyDiffTree = PropertyDiffs.BuildDiffTree(srcTree, dstTree);
if (diff.PropertyDiffTree == null)
{
// No visible property diff. Keep the entry only when a
// per-object DataLossDetection rule already flagged the
// object — the loader dropped serialized data and the
// empty tree is a symptom of that loss (e.g. AOC with
// null controller wipes m_Clips, FallbackEditorWindow
// strips everything but base EditorWindow fields).
// Otherwise the YAML difference was in fields the
// property tree filters out (m_Component reorder,
// etc.) and there is nothing for the user to see.
if (diff.DataLoss == DataLossKind.None)
return;
}
diff.DiffType = DiffType.Modified;
objectDiffs.Add(diff);
}
}
internal static void AddAddedDiff(
UnityEngine.Object dstObj,
Dictionary<UnityEngine.Object, DataLossKind> dstDataLoss,
List<ObjectDiff> objectDiffs)
{
ObjectDiff diff = new ObjectDiff
{
SrcObject = null,
DstObject = dstObj,
DiffType = DiffType.Added,
DataLoss = DataLossDetection.LookupOrNone(dstDataLoss, dstObj)
};
using (SerializedObject dstSO = new SerializedObject(dstObj))
{
PropertyTreeNode dstTree = PropertyTreeBuilder.Build(dstSO);
diff.PropertyDiffTree = PropertyDiffs.BuildDiffTree(null, dstTree);
}
objectDiffs.Add(diff);
}
internal static void AddRemovedDiff(
UnityEngine.Object srcObj,
Dictionary<UnityEngine.Object, DataLossKind> srcDataLoss,
List<ObjectDiff> objectDiffs)
{
ObjectDiff diff = new ObjectDiff
{
SrcObject = srcObj,
DstObject = null,
DiffType = DiffType.Removed,
DataLoss = DataLossDetection.LookupOrNone(srcDataLoss, srcObj)
};
using (SerializedObject srcSO = new SerializedObject(srcObj))
{
PropertyTreeNode srcTree = PropertyTreeBuilder.Build(srcSO);
diff.PropertyDiffTree = PropertyDiffs.BuildDiffTree(srcTree, null);
}
objectDiffs.Add(diff);
}
static bool IsBlockUnchanged(
long fileId,
Dictionary<long, long> srcBlockHashes,
Dictionary<long, long> dstBlockHashes)
{
return srcBlockHashes.TryGetValue(fileId, out long srcHash)
&& dstBlockHashes.TryGetValue(fileId, out long dstHash)
&& srcHash == dstHash;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 918b82076ea84e349af17dcbf45fa884
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,289 @@
using System;
using System.Collections.Generic;
using System.Text;
using Unity.PlasticSCM.Editor.Diff.Asset.Common.Property;
using Unity.PlasticSCM.Editor.Diff.Asset.Diff.Property;
using UnityEditor;
using UnityEngine;
using Unity.PlasticSCM.Editor.Diff.Asset.Common;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff.UnityObject
{
// Fallback path used when the m_LocalIdentfierInFile property cannot be
// read for every object (i.e. binary serialization or unexpected schema).
// Pairs objects by hierarchical name/path key and falls back to property
// similarity for the leftovers.
internal static class NameMatchedDiffs
{
internal static void Build(
UnityEngine.Object[] srcObjects,
UnityEngine.Object[] dstObjects,
Dictionary<UnityEngine.Object, DataLossKind> srcDataLoss,
Dictionary<UnityEngine.Object, DataLossKind> dstDataLoss,
List<ObjectDiff> objectDiffs)
{
Dictionary<string, List<UnityEngine.Object>> srcByKey = GroupByKey(srcObjects, GetObjectKey);
Dictionary<string, List<UnityEngine.Object>> dstByKey = GroupByKey(dstObjects, GetObjectKey);
List<UnityEngine.Object> unmatchedSrc = new List<UnityEngine.Object>();
List<UnityEngine.Object> unmatchedDst = new List<UnityEngine.Object>();
HashSet<string> allKeys = new HashSet<string>(srcByKey.Keys);
allKeys.UnionWith(dstByKey.Keys);
foreach (string key in allKeys)
{
srcByKey.TryGetValue(key, out List<UnityEngine.Object> srcList);
dstByKey.TryGetValue(key, out List<UnityEngine.Object> dstList);
srcList = srcList ?? EmptyList;
dstList = dstList ?? EmptyList;
int srcCount = srcList.Count;
int dstCount = dstList.Count;
int matchCount = Math.Min(srcCount, dstCount);
for (int i = 0; i < matchCount; i++)
IdentityPairedDiffs.AddModifiedDiff(
srcList[i], dstList[i],
srcDataLoss, dstDataLoss,
objectDiffs);
for (int i = matchCount; i < srcCount; i++)
unmatchedSrc.Add(srcList[i]);
for (int i = matchCount; i < dstCount; i++)
unmatchedDst.Add(dstList[i]);
}
MatchUnmatchedBySimilarity(
unmatchedSrc, unmatchedDst,
srcDataLoss, dstDataLoss,
objectDiffs);
}
static string GetObjectKey(UnityEngine.Object obj)
{
if (obj == null) return string.Empty;
string typeName = obj.GetType().Name;
string objName = obj.name;
if (obj is GameObject go)
{
Transform transform = go.transform;
int depth = 0;
Transform t = transform;
while (t.parent != null) { depth++; t = t.parent; }
if (depth == 0)
return string.Concat(typeName, ":", objName);
StringBuilder sb = new StringBuilder(
typeName.Length + 1 + (depth + 1) * 16);
sb.Append(typeName).Append(':');
AppendHierarchyPath(sb, transform);
return sb.ToString();
}
return string.Concat(typeName, ":", objName);
}
static void AppendHierarchyPath(StringBuilder sb, Transform transform)
{
if (transform.parent != null)
{
AppendHierarchyPath(sb, transform.parent);
sb.Append('/');
}
sb.Append(transform.name);
}
static void MatchUnmatchedBySimilarity(
List<UnityEngine.Object> unmatchedSrc,
List<UnityEngine.Object> unmatchedDst,
Dictionary<UnityEngine.Object, DataLossKind> srcDataLoss,
Dictionary<UnityEngine.Object, DataLossKind> dstDataLoss,
List<ObjectDiff> objectDiffs)
{
if (unmatchedSrc.Count == 0 || unmatchedDst.Count == 0)
{
AddAsAddedRemoved(
unmatchedSrc, unmatchedDst,
srcDataLoss, dstDataLoss,
objectDiffs);
return;
}
Dictionary<string, List<UnityEngine.Object>> srcByType = GroupByKey(unmatchedSrc, o => o.GetType().Name);
Dictionary<string, List<UnityEngine.Object>> dstByType = GroupByKey(unmatchedDst, o => o.GetType().Name);
HashSet<UnityEngine.Object> matchedSrc = new HashSet<UnityEngine.Object>();
HashSet<UnityEngine.Object> matchedDst = new HashSet<UnityEngine.Object>();
foreach (KeyValuePair<string, List<UnityEngine.Object>> kvp in srcByType)
{
if (!dstByType.TryGetValue(kvp.Key, out List<UnityEngine.Object> dstTypeList))
continue;
List<ObjectTreeEntry> srcEntries = BuildTreeEntries(kvp.Value);
List<ObjectTreeEntry> dstEntries = BuildTreeEntries(dstTypeList);
IReadOnlyList<PropertyTreeNode> srcTrees = ExtractTrees(srcEntries);
IReadOnlyList<PropertyTreeNode> dstTrees = ExtractTrees(dstEntries);
Dictionary<string, string>[] srcLeaves = SimilarityCalculator.BuildLeafMaps(srcTrees);
Dictionary<string, string>[] dstLeaves = SimilarityCalculator.BuildLeafMaps(dstTrees);
HashSet<int> usedDst = new HashSet<int>();
for (int i = 0; i < srcEntries.Count; i++)
{
int bestIdx = -1;
double bestSimilarity = OBJECT_MATCH_THRESHOLD;
for (int j = 0; j < dstEntries.Count; j++)
{
if (usedDst.Contains(j))
continue;
double similarity = SimilarityCalculator.CalculateFromLeaves(
srcLeaves[i], dstLeaves[j]);
if (similarity > bestSimilarity)
{
bestIdx = j;
bestSimilarity = similarity;
}
}
if (bestIdx < 0)
continue;
usedDst.Add(bestIdx);
matchedSrc.Add(srcEntries[i].Object);
matchedDst.Add(dstEntries[bestIdx].Object);
AddModifiedDiffFromTrees(
srcEntries[i].Object, dstEntries[bestIdx].Object,
srcEntries[i].Tree, dstEntries[bestIdx].Tree,
srcDataLoss, dstDataLoss,
objectDiffs);
}
}
foreach (UnityEngine.Object srcObj in unmatchedSrc)
{
if (!matchedSrc.Contains(srcObj))
IdentityPairedDiffs.AddRemovedDiff(srcObj, srcDataLoss, objectDiffs);
}
foreach (UnityEngine.Object dstObj in unmatchedDst)
{
if (!matchedDst.Contains(dstObj))
IdentityPairedDiffs.AddAddedDiff(dstObj, dstDataLoss, objectDiffs);
}
}
static void AddAsAddedRemoved(
List<UnityEngine.Object> srcObjects,
List<UnityEngine.Object> dstObjects,
Dictionary<UnityEngine.Object, DataLossKind> srcDataLoss,
Dictionary<UnityEngine.Object, DataLossKind> dstDataLoss,
List<ObjectDiff> objectDiffs)
{
foreach (UnityEngine.Object srcObj in srcObjects)
IdentityPairedDiffs.AddRemovedDiff(srcObj, srcDataLoss, objectDiffs);
foreach (UnityEngine.Object dstObj in dstObjects)
IdentityPairedDiffs.AddAddedDiff(dstObj, dstDataLoss, objectDiffs);
}
static void AddModifiedDiffFromTrees(
UnityEngine.Object srcObj,
UnityEngine.Object dstObj,
PropertyTreeNode srcTree,
PropertyTreeNode dstTree,
Dictionary<UnityEngine.Object, DataLossKind> srcDataLoss,
Dictionary<UnityEngine.Object, DataLossKind> dstDataLoss,
List<ObjectDiff> objectDiffs)
{
ObjectDiff diff = new ObjectDiff
{
SrcObject = srcObj,
DstObject = dstObj,
DataLoss = DataLossDetection.PickMoreSpecific(
DataLossDetection.LookupOrNone(srcDataLoss, srcObj),
DataLossDetection.LookupOrNone(dstDataLoss, dstObj))
};
diff.PropertyDiffTree = PropertyDiffs.BuildDiffTree(srcTree, dstTree);
if (diff.PropertyDiffTree == null && diff.DataLoss == DataLossKind.None)
return;
diff.DiffType = DiffType.Modified;
objectDiffs.Add(diff);
}
static List<ObjectTreeEntry> BuildTreeEntries(
List<UnityEngine.Object> objects)
{
List<ObjectTreeEntry> entries = new List<ObjectTreeEntry>(objects.Count);
foreach (UnityEngine.Object obj in objects)
{
using (SerializedObject so = new SerializedObject(obj))
{
entries.Add(new ObjectTreeEntry
{
Object = obj,
Tree = PropertyTreeBuilder.Build(so)
});
}
}
return entries;
}
static IReadOnlyList<PropertyTreeNode> ExtractTrees(
List<ObjectTreeEntry> entries)
{
PropertyTreeNode[] trees = new PropertyTreeNode[entries.Count];
for (int i = 0; i < entries.Count; i++)
trees[i] = entries[i].Tree;
return trees;
}
static Dictionary<string, List<T>> GroupByKey<T>(
IList<T> items, Func<T, string> keySelector)
{
Dictionary<string, List<T>> map = new Dictionary<string, List<T>>(items.Count);
for (int i = 0; i < items.Count; i++)
{
string key = keySelector(items[i]);
if (!map.TryGetValue(key, out List<T> list))
{
list = new List<T>();
map[key] = list;
}
list.Add(items[i]);
}
return map;
}
struct ObjectTreeEntry
{
internal UnityEngine.Object Object;
internal PropertyTreeNode Tree;
}
static readonly List<UnityEngine.Object> EmptyList =
new List<UnityEngine.Object>();
const double OBJECT_MATCH_THRESHOLD = 0.5;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 49b91d95e97c47a49b9234bc11be2413
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,115 @@
using System.Collections.Generic;
using UnityEngine;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff.UnityObject
{
// Restructures a flat list of ObjectDiffs into a tree where each Component
// diff is nested under its owning GameObject diff (creating a synthetic
// Unchanged container when the GameObject itself has no own changes).
// Sorts each GameObject's components to match the inspector order.
internal static class ObjectDiffGrouping
{
internal static void GroupComponentsUnderGameObjects(List<ObjectDiff> objectDiffs)
{
Dictionary<GameObject, ObjectDiff> goDiffs = new Dictionary<GameObject, ObjectDiff>();
foreach (ObjectDiff diff in objectDiffs)
{
if (diff.SrcObject is GameObject srcGo) goDiffs[srcGo] = diff;
if (diff.DstObject is GameObject dstGo) goDiffs[dstGo] = diff;
}
List<ObjectDiff> topLevel = new List<ObjectDiff>(objectDiffs.Count);
foreach (ObjectDiff diff in objectDiffs)
{
Component c = (diff.DstObject ?? diff.SrcObject) as Component;
if (c == null)
{
topLevel.Add(diff);
continue;
}
ObjectDiff parent = GetOrCreateGameObjectDiff(diff, goDiffs, topLevel);
if (parent.ComponentDiffs == null)
parent.ComponentDiffs = new List<ObjectDiff>();
parent.ComponentDiffs.Add(diff);
}
objectDiffs.Clear();
objectDiffs.AddRange(topLevel);
foreach (ObjectDiff diff in objectDiffs)
SortComponentsByGameObjectOrder(diff);
}
static ObjectDiff GetOrCreateGameObjectDiff(
ObjectDiff componentDiff,
Dictionary<GameObject, ObjectDiff> goDiffs,
List<ObjectDiff> topLevel)
{
GameObject srcParent = (componentDiff.SrcObject as Component)?.gameObject;
GameObject dstParent = (componentDiff.DstObject as Component)?.gameObject;
if (srcParent != null && goDiffs.TryGetValue(srcParent, out ObjectDiff existing))
return existing;
if (dstParent != null && goDiffs.TryGetValue(dstParent, out existing))
return existing;
ObjectDiff container = new ObjectDiff
{
SrcObject = srcParent,
DstObject = dstParent,
DiffType = DiffType.Unchanged
};
if (srcParent != null) goDiffs[srcParent] = container;
if (dstParent != null) goDiffs[dstParent] = container;
topLevel.Add(container);
return container;
}
static void SortComponentsByGameObjectOrder(ObjectDiff gameObjectDiff)
{
if (gameObjectDiff.ComponentDiffs == null)
return;
GameObject go = (gameObjectDiff.DstObject ?? gameObjectDiff.SrcObject) as GameObject;
if (go == null)
return;
Component[] orderedComponents = go.GetComponents<Component>();
Dictionary<Component, int> orderIndex = new Dictionary<Component, int>(
orderedComponents.Length);
for (int i = 0; i < orderedComponents.Length; i++)
{
if (orderedComponents[i] != null)
orderIndex[orderedComponents[i]] = i;
}
gameObjectDiff.ComponentDiffs.Sort((a, b) =>
{
int ia = GetComponentOrder(a, orderIndex);
int ib = GetComponentOrder(b, orderIndex);
return ia.CompareTo(ib);
});
}
static int GetComponentOrder(
ObjectDiff diff,
Dictionary<Component, int> orderIndex)
{
if (diff.DstObject is Component dstComp
&& orderIndex.TryGetValue(dstComp, out int dstIdx))
return dstIdx;
if (diff.SrcObject is Component srcComp
&& orderIndex.TryGetValue(srcComp, out int srcIdx))
return srcIdx;
return int.MaxValue;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 42bc4cfe52d940d0b8b6f005cf6b0b12
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,29 @@
using System.Collections.Generic;
using Unity.PlasticSCM.Editor.Diff.Asset.Diff.Property;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff.UnityObject
{
internal static class ObjectDiffSorting
{
internal static int GetOrder(DiffType diffType)
{
switch (diffType)
{
case DiffType.Modified: return 0;
case DiffType.Added: return 1;
case DiffType.Removed: return 2;
default: return 3;
}
}
internal class PropertyDiffComparer : IComparer<PropertyDiff>
{
internal static readonly PropertyDiffComparer Instance = new PropertyDiffComparer();
public int Compare(PropertyDiff x, PropertyDiff y)
{
return GetOrder(x.DiffType).CompareTo(GetOrder(y.DiffType));
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 30ee8c95d04f4c29864412b78f8ae8ab
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,72 @@
using System.Collections.Generic;
using UnityEngine;
using Unity.PlasticSCM.Editor.Diff.Asset.Common;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff.UnityObject
{
// Detects re-parenting (a GameObject's transform.parent fileId differs
// between sides). Sibling reorder and parent change are mutually
// exclusive: a reparented GO is never in the common-children set of
// either old or new parent, so SiblingReorderDiffs won't fire on it.
internal static class ParentChangeDiffs
{
internal static void Append(
Dictionary<long, UnityEngine.Object> srcById,
Dictionary<long, UnityEngine.Object> dstById,
List<ObjectDiff> objectDiffs)
{
Dictionary<GameObject, ObjectDiff> bySrcGameObject =
new Dictionary<GameObject, ObjectDiff>();
Dictionary<GameObject, ObjectDiff> byDstGameObject =
new Dictionary<GameObject, ObjectDiff>();
foreach (ObjectDiff diff in objectDiffs)
{
if (diff.SrcObject is GameObject sg) bySrcGameObject[sg] = diff;
if (diff.DstObject is GameObject dg) byDstGameObject[dg] = diff;
}
foreach (KeyValuePair<long, UnityEngine.Object> kvp in srcById)
{
if (!(kvp.Value is GameObject srcGo))
continue;
if (!dstById.TryGetValue(kvp.Key, out UnityEngine.Object dstObj))
continue;
if (!(dstObj is GameObject dstGo))
continue;
Transform srcParentT = srcGo.transform.parent;
Transform dstParentT = dstGo.transform.parent;
long srcParentId = srcParentT == null ? 0 : srcParentT.GetLocalFileId();
long dstParentId = dstParentT == null ? 0 : dstParentT.GetLocalFileId();
if (srcParentId == dstParentId)
continue;
ObjectDiff existing = null;
if (!bySrcGameObject.TryGetValue(srcGo, out existing))
byDstGameObject.TryGetValue(dstGo, out existing);
if (existing == null)
{
// GameObject reparented but otherwise unchanged — emit a
// Modified diff with no PropertyDiffs so the row still appears.
existing = new ObjectDiff
{
SrcObject = srcGo,
DstObject = dstGo,
DiffType = DiffType.Modified
};
objectDiffs.Add(existing);
bySrcGameObject[srcGo] = existing;
byDstGameObject[dstGo] = existing;
}
existing.SrcParent = srcParentT == null ? null : srcParentT.gameObject;
existing.DstParent = dstParentT == null ? null : dstParentT.gameObject;
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: da41f0c6c4104a20994b9c08feb4e13f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,194 @@
using System.Collections.Generic;
using UnityEngine;
using Unity.PlasticSCM.Editor.Diff.Asset.Common;
using Unity.PlasticSCM.Editor.Diff.Asset.Common.UnityObject;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff.UnityObject
{
// Detects sibling reorders at any level of the GameObject hierarchy:
// both the scene-root level (via SceneRoots.m_Roots) and inside every
// Transform's m_Children list. The same reorder algorithm used for
// components is applied per parent — common siblings (present on both
// sides) define the reference order, additions/removals don't count.
internal static class SiblingReorderDiffs
{
internal static void Append(
UnityEngine.Object[] srcObjects,
UnityEngine.Object[] dstObjects,
Dictionary<long, UnityEngine.Object> srcById,
Dictionary<long, UnityEngine.Object> dstById,
List<ObjectDiff> objectDiffs)
{
Dictionary<GameObject, ObjectDiff> bySrcGameObject =
new Dictionary<GameObject, ObjectDiff>();
Dictionary<GameObject, ObjectDiff> byDstGameObject =
new Dictionary<GameObject, ObjectDiff>();
foreach (ObjectDiff diff in objectDiffs)
{
if (diff.SrcObject is GameObject sg) bySrcGameObject[sg] = diff;
if (diff.DstObject is GameObject dg) byDstGameObject[dg] = diff;
}
// Scene-root level (not modeled as a Transform parent).
UnityEngine.Object srcSceneRoots = SceneRootsReader.Find(srcObjects);
UnityEngine.Object dstSceneRoots = SceneRootsReader.Find(dstObjects);
if (srcSceneRoots != null && dstSceneRoots != null)
{
EmitDiffs(
SceneRootsReader.ReadRootGameObjects(srcSceneRoots),
SceneRootsReader.ReadRootGameObjects(dstSceneRoots),
bySrcGameObject, byDstGameObject, objectDiffs);
}
// Every paired Transform's m_Children. Covers prefabs (no SceneRoots)
// and nested hierarchy reorders inside scenes.
foreach (KeyValuePair<long, UnityEngine.Object> kvp in srcById)
{
if (!(kvp.Value is Transform srcParent))
continue;
if (!dstById.TryGetValue(kvp.Key, out UnityEngine.Object dstObj))
continue;
if (!(dstObj is Transform dstParent))
continue;
if (srcParent == null || dstParent == null)
continue;
EmitDiffs(
ReadChildGameObjects(srcParent),
ReadChildGameObjects(dstParent),
bySrcGameObject, byDstGameObject, objectDiffs);
}
}
static void EmitDiffs(
List<GameObject> srcOrdered,
List<GameObject> dstOrdered,
Dictionary<GameObject, ObjectDiff> bySrcGameObject,
Dictionary<GameObject, ObjectDiff> byDstGameObject,
List<ObjectDiff> objectDiffs)
{
if (srcOrdered.Count == 0 || dstOrdered.Count == 0)
return;
Dictionary<long, GameObject> srcByFileId = BuildGameObjectFileIdMap(srcOrdered);
Dictionary<long, GameObject> dstByFileId = BuildGameObjectFileIdMap(dstOrdered);
HashSet<long> common = new HashSet<long>();
foreach (long fileId in srcByFileId.Keys)
{
if (dstByFileId.ContainsKey(fileId))
common.Add(fileId);
}
// Position is measured against the relative order of siblings
// present on both sides — additions and removals don't count as
// "everyone moved".
if (common.Count < 2)
return;
List<long> srcCommonOrder = FilterByCommonFileId(srcOrdered, common);
List<long> dstCommonOrder = FilterByCommonFileId(dstOrdered, common);
Dictionary<long, int> srcPos = ToPositionIndex(srcCommonOrder);
Dictionary<long, int> dstPos = ToPositionIndex(dstCommonOrder);
foreach (long fileId in common)
{
int delta = dstPos[fileId] - srcPos[fileId];
if (delta == 0)
continue;
GameObject srcGo = srcByFileId[fileId];
GameObject dstGo = dstByFileId[fileId];
ObjectDiff existing = null;
if (srcGo != null) bySrcGameObject.TryGetValue(srcGo, out existing);
if (existing == null && dstGo != null)
byDstGameObject.TryGetValue(dstGo, out existing);
if (existing != null)
{
existing.PositionDelta = delta;
continue;
}
// Sibling moved but its content is unchanged — emit a
// Modified diff with no PropertyDiffs so the row still appears.
ObjectDiff newDiff = new ObjectDiff
{
SrcObject = srcGo,
DstObject = dstGo,
DiffType = DiffType.Modified,
PositionDelta = delta
};
objectDiffs.Add(newDiff);
if (srcGo != null) bySrcGameObject[srcGo] = newDiff;
if (dstGo != null) byDstGameObject[dstGo] = newDiff;
}
}
static List<GameObject> ReadChildGameObjects(Transform parent)
{
int count = parent.childCount;
List<GameObject> result = new List<GameObject>(count);
for (int i = 0; i < count; i++)
{
Transform child = parent.GetChild(i);
if (child != null && child.gameObject != null)
result.Add(child.gameObject);
}
return result;
}
static Dictionary<long, GameObject> BuildGameObjectFileIdMap(List<GameObject> gameObjects)
{
Dictionary<long, GameObject> map = new Dictionary<long, GameObject>(gameObjects.Count);
foreach (GameObject go in gameObjects)
{
if (go == null)
continue;
long fileId = go.GetLocalFileId();
if (fileId == 0)
continue;
map[fileId] = go;
}
return map;
}
static List<long> FilterByCommonFileId(
List<GameObject> gameObjects, HashSet<long> common)
{
List<long> result = new List<long>(gameObjects.Count);
foreach (GameObject go in gameObjects)
{
if (go == null)
continue;
long fileId = go.GetLocalFileId();
if (common.Contains(fileId))
result.Add(fileId);
}
return result;
}
static Dictionary<long, int> ToPositionIndex(List<long> orderedFileIds)
{
Dictionary<long, int> result = new Dictionary<long, int>(orderedFileIds.Count);
for (int i = 0; i < orderedFileIds.Count; i++)
result[orderedFileIds[i]] = i;
return result;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2c8fed4a76fae4229855015e0ab109b1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,120 @@
using System.Collections.Generic;
using System.Diagnostics;
using UnityEditorInternal;
using Codice.LogWrapper;
using Unity.PlasticSCM.Editor.Diff.Asset.Common.UnityObject;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff.UnityObject
{
internal static class UnityObjectDiffs
{
internal static List<ObjectDiff> BuildDiffData(
string srcFile,
string dstFile)
{
Stopwatch sw = Stopwatch.StartNew();
List<ObjectDiff> objectDiffs = new List<ObjectDiff>();
UnityEngine.Object[] srcObjects = InternalEditorUtility.LoadSerializedFileAndForget(srcFile);
UnityEngine.Object[] dstObjects = InternalEditorUtility.LoadSerializedFileAndForget(dstFile);
FileIdInfo srcFileIdInfo = FileIdReader.Read(srcFile);
FileIdInfo dstFileIdInfo = FileIdReader.Read(dstFile);
Dictionary<long, UnityEngine.Object> srcById = IdentityPairedDiffs.BuildFileIdMap(srcObjects);
Dictionary<long, UnityEngine.Object> dstById = IdentityPairedDiffs.BuildFileIdMap(dstObjects);
// Detect objects where LoadSerializedFileAndForget silently dropped
// data — missing scripts substituted as UnityEditor.FallbackEditorWindow,
// MonoBehaviours with unresolved MonoScript references,
// AnimatorOverrideControllers whose controller couldn't be
// resolved (BuildAsset wipes m_Clips in that state). These maps
// are consumed by the diff builders to tag each ObjectDiff with a
// DataLoss reason. See DataLossDetection for the per-object rules.
Dictionary<UnityEngine.Object, DataLossKind> srcDataLoss =
DataLossDetection.DetectPerObject(srcObjects);
Dictionary<UnityEngine.Object, DataLossKind> dstDataLoss =
DataLossDetection.DetectPerObject(dstObjects);
if (CanPairByFileId(srcObjects, dstObjects, srcById, dstById))
{
IdentityPairedDiffs.Build(
srcById, dstById,
srcFileIdInfo.HashByFileId,
dstFileIdInfo.HashByFileId,
srcDataLoss, dstDataLoss,
objectDiffs);
ComponentReorderDiffs.Append(srcById, dstById, objectDiffs);
SiblingReorderDiffs.Append(
srcObjects, dstObjects, srcById, dstById, objectDiffs);
ParentChangeDiffs.Append(srcById, dstById, objectDiffs);
}
else
{
// Component, sibling and parent change detection are skipped on
// the fallback path because the name-based matcher cannot
// reliably pair GameObjects across the two sides.
mLog.InfoFormat("Falling back to name-based diff for files '{0}' and '{1}' " +
"because file IDs could not be read", srcFile, dstFile);
NameMatchedDiffs.Build(
srcObjects, dstObjects,
srcDataLoss, dstDataLoss,
objectDiffs);
}
ObjectDiffGrouping.GroupComponentsUnderGameObjects(objectDiffs);
HierarchyOrderSorting.SortByHierarchyOrder(
objectDiffs,
d => d.DstObject ?? d.SrcObject,
// dst hierarchy first — matches what the user sees in their
// workspace after pulling/checking out the destination. Then
// src-only objects (Removed) keep their src-side position.
dstObjects, srcObjects);
int dataLossCount = CountObjectsWithDataLoss(objectDiffs);
if (dataLossCount > 0)
{
mLog.InfoFormat(
"LoadSerializedFileAndForget dropped data on {0} object(s) " +
"while diffing '{1}' and '{2}' — these diffs are incomplete " +
"and the user should be steered to text diff",
dataLossCount, srcFile, dstFile);
}
mLog.DebugFormat(
"{0} object diffs calculated in {1} ms",
objectDiffs.Count, sw.ElapsedMilliseconds);
return objectDiffs;
}
static bool CanPairByFileId(
UnityEngine.Object[] srcObjects,
UnityEngine.Object[] dstObjects,
Dictionary<long, UnityEngine.Object> srcById,
Dictionary<long, UnityEngine.Object> dstById)
{
return srcById.Count == IdentityPairedDiffs.CountNonNull(srcObjects)
&& dstById.Count == IdentityPairedDiffs.CountNonNull(dstObjects);
}
static int CountObjectsWithDataLoss(List<ObjectDiff> diffs)
{
int n = 0;
foreach (ObjectDiff d in diffs)
{
if (d.DataLoss != DataLossKind.None)
n++;
}
return n;
}
static readonly ILog mLog = PlasticApp.GetLogger("UnityObjectDiffs");
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: c9091bce433442d9b53aa8c577305e57
timeCreated: 1774969041