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,67 @@
using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common
{
class AssetReloadNotifier : AssetPostprocessor
{
internal static event Action<HashSet<string>> AssetsChanged;
internal static bool IsWatchedPath(
string file, HashSet<string> changedFullPaths)
{
if (string.IsNullOrEmpty(file))
return false;
if (file.StartsWith(Path.GetTempPath(), StringComparison.OrdinalIgnoreCase))
return false;
string fullPath = Path.GetFullPath(file);
if (changedFullPaths.Contains(fullPath))
return true;
if (!MetaPath.IsMetaPath(file))
return false;
string assetFullPath = Path.GetFullPath(
MetaPath.GetPathFromMetaPath(file));
return changedFullPaths.Contains(assetFullPath);
}
static void OnPostprocessAllAssets(
string[] importedAssets,
string[] deletedAssets,
string[] movedAssets,
string[] movedFromAssetPaths)
{
Action<HashSet<string>> handler = AssetsChanged;
if (handler == null)
return;
HashSet<string> changedFullPaths = new HashSet<string>(
StringComparer.OrdinalIgnoreCase);
AddFullPaths(changedFullPaths, importedAssets);
AddFullPaths(changedFullPaths, deletedAssets);
AddFullPaths(changedFullPaths, movedAssets);
AddFullPaths(changedFullPaths, movedFromAssetPaths);
if (changedFullPaths.Count == 0)
return;
handler(changedFullPaths);
}
static void AddFullPaths(HashSet<string> set, string[] assetPaths)
{
foreach (string assetPath in assetPaths)
set.Add(Path.GetFullPath(assetPath));
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c1920ac5329fb48e680e865d9a8567f8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,537 @@
using Unity.PlasticSCM.Editor.Diff.Asset.Common.Property;
using Unity.PlasticSCM.Editor.Diff.Asset.Diff.Property;
using Unity.PlasticSCM.Editor.Diff.Asset.Content.Property;
using Unity.PlasticSCM.Editor.UI;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common
{
internal class DiffValueDisplay : VisualElement
{
internal DiffValueDisplay()
{
CreateGUI();
}
internal void SetData(
object tag,
string fallbackText,
bool hasContent,
object counterpartTag)
{
HideActiveField();
if (!hasContent)
return;
if (tag is LeafPropertyData leaf)
{
LeafPropertyData? counterpart = counterpartTag is LeafPropertyData cp
? cp
: (LeafPropertyData?)null;
ShowTypedField(leaf, counterpart);
return;
}
ShowField(mTextField);
mTextField.SetValueWithoutNotify(fallbackText ?? string.Empty);
}
void CreateGUI()
{
style.flexGrow = 1;
style.overflow = Overflow.Visible;
mFloatField = AddField(new FloatField { label = string.Empty });
mIntField = AddField(new IntegerField { label = string.Empty });
mToggleField = AddField(new Toggle { label = string.Empty });
mTextField = AddField(new TextField { label = string.Empty });
mColorField = AddField(new ColorField
{
label = string.Empty,
showAlpha = true,
hdr = false,
showEyeDropper = false
});
mCurveField = AddField(new CurveField { label = string.Empty });
mGradientField = AddField(new GradientField { label = string.Empty });
mVector2Field = AddField(new Vector2Field { label = string.Empty });
mVector3Field = AddField(new Vector3Field { label = string.Empty });
mVector4Field = AddField(new Vector4Field { label = string.Empty });
mVector2IntField = AddField(new Vector2IntField { label = string.Empty });
mVector3IntField = AddField(new Vector3IntField { label = string.Empty });
mRectField = AddField(new RectField { label = string.Empty });
mRectIntField = AddField(new RectIntField { label = string.Empty });
mBoundsField = AddField(new BoundsField { label = string.Empty });
mBoundsIntField = AddField(new BoundsIntField { label = string.Empty });
mHash128Field = AddField(new Hash128Field { label = string.Empty });
}
T AddField<T>(T field) where T : VisualElement
{
field.SetEnabled(false);
field.style.opacity = 1f;
field.style.display = DisplayStyle.None;
field.style.flexGrow = 1;
field.style.marginTop = 0;
field.style.marginBottom = 0;
field.style.marginLeft = 0;
field.style.marginRight = 0;
Add(field);
field.RegisterCallback<AttachToPanelEvent>(_ =>
{
StyleColor readonlyBg = new StyleColor(
UnityStyles.Colors.Diff.AssetDiff.ReadonlyFieldBackgroundColor);
field.Query(className: INPUT_CLASS).ForEach(input =>
input.style.backgroundColor = readonlyBg);
field.Query(className: TOGGLE_CHECKMARK_CLASS).ForEach(checkmark =>
checkmark.style.unityBackgroundImageTintColor = new StyleColor(
UnityStyles.Colors.Diff.AssetDiff.ReadonlyToggleTintColor));
});
return field;
}
void HideActiveField()
{
if (mActiveField == null)
return;
mActiveField.style.display = DisplayStyle.None;
mActiveField = null;
}
void ShowField(VisualElement field)
{
field.style.display = DisplayStyle.Flex;
mActiveField = field;
}
void ShowTypedField(LeafPropertyData data, LeafPropertyData? counterpart)
{
switch (data.PropertyType)
{
case SerializedPropertyType.Float:
ShowField(mFloatField);
mFloatField.SetValueWithoutNotify(data.FloatValue);
return;
case SerializedPropertyType.Integer:
if (data.HasFormattedDisplay)
{
ShowField(mTextField);
mTextField.SetValueWithoutNotify(data.StringValue ?? string.Empty);
return;
}
ShowField(mIntField);
mIntField.SetValueWithoutNotify(data.IntValue);
return;
case SerializedPropertyType.LayerMask:
if (data.HasFormattedDisplay)
{
ShowField(mTextField);
mTextField.SetValueWithoutNotify(data.StringValue ?? string.Empty);
return;
}
ShowField(mIntField);
mIntField.SetValueWithoutNotify(data.IntValue);
return;
case SerializedPropertyType.Character:
case SerializedPropertyType.ArraySize:
case SerializedPropertyType.FixedBufferSize:
ShowField(mIntField);
mIntField.SetValueWithoutNotify(data.IntValue);
return;
case SerializedPropertyType.Boolean:
ShowField(mToggleField);
mToggleField.SetValueWithoutNotify(data.BoolValue);
return;
case SerializedPropertyType.String:
ShowField(mTextField);
mTextField.SetValueWithoutNotify(data.StringValue ?? string.Empty);
return;
case SerializedPropertyType.Color:
ShowField(mColorField);
mColorField.SetValueWithoutNotify(data.ColorValue);
return;
case SerializedPropertyType.AnimationCurve:
ShowField(mCurveField);
mCurveField.SetValueWithoutNotify(
data.AnimationCurveValue ?? new AnimationCurve());
return;
case SerializedPropertyType.Gradient:
ShowField(mGradientField);
mGradientField.SetValueWithoutNotify(
data.GradientValue ?? new Gradient());
return;
case SerializedPropertyType.Vector2:
ShowVector2(data.Vector2Value, counterpart);
return;
case SerializedPropertyType.Vector3:
ShowVector3(data.Vector3Value, counterpart);
return;
case SerializedPropertyType.Vector4:
ShowVector4(data.Vector4Value, counterpart);
return;
case SerializedPropertyType.Quaternion:
ShowQuaternion(data.QuaternionValue, counterpart);
return;
case SerializedPropertyType.Vector2Int:
ShowVector2Int(data.Vector2IntValue, counterpart);
return;
case SerializedPropertyType.Vector3Int:
ShowVector3Int(data.Vector3IntValue, counterpart);
return;
case SerializedPropertyType.Rect:
ShowRect(data.RectValue, counterpart);
return;
case SerializedPropertyType.RectInt:
ShowRectInt(data.RectIntValue, counterpart);
return;
case SerializedPropertyType.Bounds:
ShowBounds(data.BoundsValue, counterpart);
return;
case SerializedPropertyType.BoundsInt:
ShowBoundsInt(data.BoundsIntValue, counterpart);
return;
case SerializedPropertyType.Hash128:
ShowField(mHash128Field);
mHash128Field.SetValueWithoutNotify(data.Hash128Value);
return;
default:
ShowField(mTextField);
mTextField.SetValueWithoutNotify(data.StringValue ?? string.Empty);
return;
}
}
void ShowVector2(Vector2 value, LeafPropertyData? counterpart)
{
ShowField(mVector2Field);
mVector2Field.SetValueWithoutNotify(value);
float[] otherValues = TryGetVector2Components(counterpart);
HighlightFloatComponents(
mVector2Field, new[] { value.x, value.y }, otherValues);
}
void ShowVector3(Vector3 value, LeafPropertyData? counterpart)
{
ShowField(mVector3Field);
mVector3Field.SetValueWithoutNotify(value);
float[] otherValues = TryGetVector3Components(counterpart);
HighlightFloatComponents(
mVector3Field, new[] { value.x, value.y, value.z }, otherValues);
}
void ShowVector4(Vector4 value, LeafPropertyData? counterpart)
{
ShowField(mVector4Field);
mVector4Field.SetValueWithoutNotify(value);
float[] otherValues = TryGetVector4Components(counterpart);
HighlightFloatComponents(
mVector4Field,
new[] { value.x, value.y, value.z, value.w },
otherValues);
}
void ShowQuaternion(Quaternion value, LeafPropertyData? counterpart)
{
Vector3 euler = value.eulerAngles;
ShowField(mVector3Field);
mVector3Field.SetValueWithoutNotify(euler);
float[] otherValues = null;
if (counterpart.HasValue &&
counterpart.Value.PropertyType == SerializedPropertyType.Quaternion)
{
Vector3 otherEuler = counterpart.Value.QuaternionValue.eulerAngles;
otherValues = new[] { otherEuler.x, otherEuler.y, otherEuler.z };
}
HighlightFloatComponents(
mVector3Field, new[] { euler.x, euler.y, euler.z }, otherValues);
}
void ShowVector2Int(Vector2Int value, LeafPropertyData? counterpart)
{
ShowField(mVector2IntField);
mVector2IntField.SetValueWithoutNotify(value);
int[] otherValues = TryGetVector2IntComponents(counterpart);
HighlightIntComponents(
mVector2IntField, new[] { value.x, value.y }, otherValues);
}
void ShowVector3Int(Vector3Int value, LeafPropertyData? counterpart)
{
ShowField(mVector3IntField);
mVector3IntField.SetValueWithoutNotify(value);
int[] otherValues = TryGetVector3IntComponents(counterpart);
HighlightIntComponents(
mVector3IntField,
new[] { value.x, value.y, value.z },
otherValues);
}
void ShowRect(Rect value, LeafPropertyData? counterpart)
{
ShowField(mRectField);
mRectField.SetValueWithoutNotify(value);
float[] otherValues = TryGetRectComponents(counterpart);
HighlightFloatComponents(
mRectField,
new[] { value.x, value.y, value.width, value.height },
otherValues);
}
void ShowRectInt(RectInt value, LeafPropertyData? counterpart)
{
ShowField(mRectIntField);
mRectIntField.SetValueWithoutNotify(value);
int[] otherValues = TryGetRectIntComponents(counterpart);
HighlightIntComponents(
mRectIntField,
new[] { value.x, value.y, value.width, value.height },
otherValues);
}
void ShowBounds(Bounds value, LeafPropertyData? counterpart)
{
ShowField(mBoundsField);
mBoundsField.SetValueWithoutNotify(value);
float[] otherValues = TryGetBoundsComponents(counterpart);
HighlightFloatComponents(
mBoundsField,
new[]
{
value.center.x, value.center.y, value.center.z,
value.extents.x, value.extents.y, value.extents.z
},
otherValues);
}
void ShowBoundsInt(BoundsInt value, LeafPropertyData? counterpart)
{
ShowField(mBoundsIntField);
mBoundsIntField.SetValueWithoutNotify(value);
int[] otherValues = TryGetBoundsIntComponents(counterpart);
HighlightIntComponents(
mBoundsIntField,
new[]
{
value.position.x, value.position.y, value.position.z,
value.size.x, value.size.y, value.size.z
},
otherValues);
}
static float[] TryGetVector2Components(LeafPropertyData? counterpart)
{
if (!counterpart.HasValue ||
counterpart.Value.PropertyType != SerializedPropertyType.Vector2)
return null;
Vector2 v = counterpart.Value.Vector2Value;
return new[] { v.x, v.y };
}
static float[] TryGetVector3Components(LeafPropertyData? counterpart)
{
if (!counterpart.HasValue ||
counterpart.Value.PropertyType != SerializedPropertyType.Vector3)
return null;
Vector3 v = counterpart.Value.Vector3Value;
return new[] { v.x, v.y, v.z };
}
static float[] TryGetVector4Components(LeafPropertyData? counterpart)
{
if (!counterpart.HasValue ||
counterpart.Value.PropertyType != SerializedPropertyType.Vector4)
return null;
Vector4 v = counterpart.Value.Vector4Value;
return new[] { v.x, v.y, v.z, v.w };
}
static int[] TryGetVector2IntComponents(LeafPropertyData? counterpart)
{
if (!counterpart.HasValue ||
counterpart.Value.PropertyType != SerializedPropertyType.Vector2Int)
return null;
Vector2Int v = counterpart.Value.Vector2IntValue;
return new[] { v.x, v.y };
}
static int[] TryGetVector3IntComponents(LeafPropertyData? counterpart)
{
if (!counterpart.HasValue ||
counterpart.Value.PropertyType != SerializedPropertyType.Vector3Int)
return null;
Vector3Int v = counterpart.Value.Vector3IntValue;
return new[] { v.x, v.y, v.z };
}
static float[] TryGetRectComponents(LeafPropertyData? counterpart)
{
if (!counterpart.HasValue ||
counterpart.Value.PropertyType != SerializedPropertyType.Rect)
return null;
Rect r = counterpart.Value.RectValue;
return new[] { r.x, r.y, r.width, r.height };
}
static int[] TryGetRectIntComponents(LeafPropertyData? counterpart)
{
if (!counterpart.HasValue ||
counterpart.Value.PropertyType != SerializedPropertyType.RectInt)
return null;
RectInt r = counterpart.Value.RectIntValue;
return new[] { r.x, r.y, r.width, r.height };
}
static float[] TryGetBoundsComponents(LeafPropertyData? counterpart)
{
if (!counterpart.HasValue ||
counterpart.Value.PropertyType != SerializedPropertyType.Bounds)
return null;
Bounds b = counterpart.Value.BoundsValue;
return new[]
{
b.center.x, b.center.y, b.center.z,
b.extents.x, b.extents.y, b.extents.z
};
}
static int[] TryGetBoundsIntComponents(LeafPropertyData? counterpart)
{
if (!counterpart.HasValue ||
counterpart.Value.PropertyType != SerializedPropertyType.BoundsInt)
return null;
BoundsInt b = counterpart.Value.BoundsIntValue;
return new[]
{
b.position.x, b.position.y, b.position.z,
b.size.x, b.size.y, b.size.z
};
}
static void HighlightFloatComponents(
VisualElement vectorField,
float[] values,
float[] counterpartValues)
{
var floatFields = vectorField.Query<FloatField>().ToList();
bool hasComparison = counterpartValues != null;
for (int i = 0; i < floatFields.Count && i < values.Length; i++)
{
bool changed = hasComparison
&& i < counterpartValues.Length
&& !Mathf.Approximately(values[i], counterpartValues[i]);
ApplyInputHighlight(floatFields[i], changed, hasComparison);
}
}
static void HighlightIntComponents(
VisualElement vectorField,
int[] values,
int[] counterpartValues)
{
var intFields = vectorField.Query<IntegerField>().ToList();
bool hasComparison = counterpartValues != null;
for (int i = 0; i < intFields.Count && i < values.Length; i++)
{
bool changed = hasComparison
&& i < counterpartValues.Length
&& values[i] != counterpartValues[i];
ApplyInputHighlight(intFields[i], changed, hasComparison);
}
}
static void ApplyInputHighlight(
VisualElement field, bool highlight, bool hasComparison)
{
VisualElement input = field.Q(className: INPUT_CLASS);
if (input == null)
return;
StyleColor color = highlight
? new StyleColor(UnityStyles.Colors.Diff.AssetDiff.VectorComponentHighlight)
: new StyleColor(StyleKeyword.Null);
input.style.borderTopColor = color;
input.style.borderBottomColor = color;
input.style.borderLeftColor = color;
input.style.borderRightColor = color;
input.style.opacity = (highlight || !hasComparison) ? 1f : 0.4f;
}
VisualElement mActiveField;
FloatField mFloatField;
IntegerField mIntField;
Toggle mToggleField;
TextField mTextField;
ColorField mColorField;
CurveField mCurveField;
GradientField mGradientField;
Vector2Field mVector2Field;
Vector3Field mVector3Field;
Vector4Field mVector4Field;
Vector2IntField mVector2IntField;
Vector3IntField mVector3IntField;
RectField mRectField;
RectIntField mRectIntField;
BoundsField mBoundsField;
BoundsIntField mBoundsIntField;
Hash128Field mHash128Field;
const string INPUT_CLASS = "unity-base-text-field__input";
const string TOGGLE_CHECKMARK_CLASS = "unity-toggle__checkmark";
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: cb707ab51a8fe45748564daa6476d9b8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,151 @@
using Unity.PlasticSCM.Editor.UI;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common
{
internal static class HeaderRow
{
internal const float BASE_PADDING_LEFT = 4f;
internal const float INDENT_PX = 16f;
internal const string ARROW_RIGHT = "▶";
internal const string ARROW_DOWN = "▼";
internal static VisualElement BuildPanel(
out VisualElement content,
out Label arrow,
out Image icon,
out Label nameLabel,
out Label annotationLabel)
{
VisualElement panel = new VisualElement();
panel.style.flexGrow = 1;
panel.style.flexBasis = 0;
panel.style.flexDirection = FlexDirection.Row;
content = new VisualElement();
content.style.flexGrow = 1;
content.style.flexDirection = FlexDirection.Row;
content.style.alignItems = Align.Center;
content.style.borderTopWidth = 1;
content.style.borderBottomWidth = 1;
panel.Add(content);
arrow = new Label(ARROW_RIGHT);
arrow.style.width = 16;
arrow.style.fontSize = 10;
arrow.style.unityTextAlign = TextAnchor.MiddleCenter;
arrow.style.color = UnityStyles.Colors.Diff.AssetDiff.ExpanderColor;
content.Add(arrow);
icon = new Image();
icon.style.width = 16;
icon.style.height = 16;
icon.style.marginRight = 4;
content.Add(icon);
nameLabel = new Label();
nameLabel.style.unityFontStyleAndWeight = FontStyle.Bold;
nameLabel.style.fontSize = 12;
nameLabel.style.flexShrink = 1;
nameLabel.style.overflow = Overflow.Hidden;
nameLabel.style.textOverflow = TextOverflow.Ellipsis;
content.Add(nameLabel);
annotationLabel = new Label();
annotationLabel.style.unityFontStyleAndWeight = FontStyle.Italic;
annotationLabel.style.fontSize = 12;
annotationLabel.style.marginLeft = 8;
annotationLabel.style.flexShrink = 0;
annotationLabel.style.color = UnityStyles.Colors.Diff.AssetDiff.AnnotationText;
annotationLabel.style.display = DisplayStyle.None;
content.Add(annotationLabel);
return panel;
}
internal static void ConfigurePanel(
Label arrow,
Image icon,
Label nameLabel,
Label annotationLabel,
VisualElement panel,
bool hasContent,
string arrowText,
Color panelBg,
UnityEngine.Texture objectIcon,
string displayName,
string searchFilter,
string annotation = null,
bool isExpandable = true)
{
panel.style.backgroundColor = panelBg;
arrow.text = arrowText;
arrow.style.display = (hasContent && isExpandable)
? DisplayStyle.Flex : DisplayStyle.None;
icon.image = hasContent ? objectIcon : null;
icon.style.display = hasContent
? DisplayStyle.Flex : DisplayStyle.None;
bool hasSearch = !string.IsNullOrEmpty(searchFilter);
nameLabel.enableRichText = hasSearch;
nameLabel.text = hasSearch
? SearchHighlight.Apply(displayName, searchFilter)
: displayName;
nameLabel.style.display = hasContent
? DisplayStyle.Flex : DisplayStyle.None;
nameLabel.style.color = hasContent
? UnityStyles.Colors.DefaultText
: UnityStyles.Colors.DefaultTextDisabled;
bool hasAnnotation = hasContent && !string.IsNullOrEmpty(annotation);
annotationLabel.style.display = hasAnnotation
? DisplayStyle.Flex : DisplayStyle.None;
if (hasAnnotation)
annotationLabel.text = annotation;
}
internal static void ApplyContentBorder(
VisualElement content,
bool hasContent,
float paddingLeft,
bool isExpanded,
bool suppressBottomBorder = false)
{
content.style.paddingLeft = paddingLeft;
content.style.borderTopColor = hasContent
? UnityStyles.Colors.Diff.AssetDiff.HeaderBorder
: Color.clear;
content.style.borderBottomColor = hasContent && isExpanded && !suppressBottomBorder
? UnityStyles.Colors.Diff.AssetDiff.HeaderBorderLight
: Color.clear;
}
internal static Color GetBackgroundColor(bool hasContent, bool bIsHovered)
{
if (!hasContent)
return UnityStyles.Colors.Diff.AssetDiff.EmptyPanelBackground;
return bIsHovered
? UnityStyles.Colors.Diff.AssetDiff.ObjectHeaderBackgroundHovered
: UnityStyles.Colors.Diff.AssetDiff.ObjectHeaderBackground;
}
internal static void SetHovered(
ref bool sideHovered,
bool hasContent,
VisualElement panel,
bool bIsHovered)
{
if (!hasContent || sideHovered == bIsHovered)
return;
sideHovered = bIsHovered;
panel.style.backgroundColor = GetBackgroundColor(hasContent, bIsHovered);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: edc2dbba232594aabbbad8bb87466a80
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 54ada74a1e58348099b007e35677f3aa
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,779 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Unity.PlasticSCM.Editor.Diff.Asset.Common.Property;
using UnityEditor;
using UnityEngine;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common.Meta
{
internal static class MetaPropertyTreeBuilder
{
internal static PropertyTreeNode Build(byte[] fileBytes)
{
if (fileBytes == null || fileBytes.Length == 0)
return PropertyTreeNode.CreateRoot(new List<PropertyTreeNode>());
string[] lines = Encoding.UTF8.GetString(fileBytes).Split('\n');
int lineIdx = 0;
List<PropertyTreeNode> children = ParseMappingEntries(lines, ref lineIdx, -1, string.Empty);
return PropertyTreeNode.CreateRoot(children);
}
#region Block Parsing
static List<PropertyTreeNode> ParseMappingEntries(
string[] lines, ref int lineIdx, int parentIndent, string parentPath)
{
List<PropertyTreeNode> children = new List<PropertyTreeNode>();
while (lineIdx < lines.Length)
{
string line = TrimLineEnd(lines[lineIdx]);
if (string.IsNullOrWhiteSpace(line))
{
lineIdx++;
continue;
}
int indent = CountLeadingSpaces(line);
string content = line.Substring(indent);
if (IsDirectiveLine(content))
{
lineIdx++;
continue;
}
if (indent <= parentIndent)
break;
// Sequence items are handled by ParseSequenceItems, not here
if (content.StartsWith("- ", StringComparison.Ordinal))
break;
if (!TrySplitKeyValue(content, out string key, out string value))
{
lineIdx++;
continue;
}
lineIdx++;
string path = AppendPath(parentPath, key);
string displayName = ObjectNames.NicifyVariableName(key);
PropertyTreeNode node = BuildValueNode(
lines, ref lineIdx, indent, key, path, displayName, value);
children.Add(node);
}
return children;
}
static PropertyTreeNode BuildValueNode(
string[] lines, ref int lineIdx, int keyIndent,
string name, string path, string displayName, string value)
{
if (string.IsNullOrEmpty(value))
return BuildBlockValueNode(
lines, ref lineIdx, keyIndent, name, path, displayName);
if (value == "{}")
return PropertyTreeNode.CreateObject(
name, path, new List<PropertyTreeNode>(), displayName);
if (value == "[]")
return PropertyTreeNode.CreateArray(
name, path, new List<PropertyTreeNode>(), displayName);
if (value.StartsWith("{", StringComparison.Ordinal) &&
value.EndsWith("}", StringComparison.Ordinal))
return ParseInlineMap(name, path, displayName, value);
if (value.StartsWith("[", StringComparison.Ordinal) &&
value.EndsWith("]", StringComparison.Ordinal))
return ParseInlineSequence(name, path, displayName, value);
return CreateTypedLeaf(name, path, displayName, value);
}
static PropertyTreeNode BuildBlockValueNode(
string[] lines, ref int lineIdx, int keyIndent,
string name, string path, string displayName)
{
SkipBlankAndDirectiveLines(lines, ref lineIdx);
if (lineIdx >= lines.Length)
return CreateTypedLeaf(name, path, displayName, string.Empty);
string nextLine = TrimLineEnd(lines[lineIdx]);
int nextIndent = CountLeadingSpaces(nextLine);
string nextContent = nextLine.Substring(nextIndent);
// Sequences can appear at the same indent as the key (Unity's standard format)
// or indented further
bool isSequence = nextContent.StartsWith("- ", StringComparison.Ordinal)
&& nextIndent >= keyIndent;
if (isSequence)
{
List<PropertyTreeNode> items = ParseSequenceItems(
lines, ref lineIdx, nextIndent, path);
return PropertyTreeNode.CreateArray(name, path, items, displayName);
}
if (nextIndent > keyIndent)
{
List<PropertyTreeNode> children = ParseMappingEntries(
lines, ref lineIdx, keyIndent, path);
return PropertyTreeNode.CreateObject(name, path, children, displayName);
}
return CreateTypedLeaf(name, path, displayName, string.Empty);
}
static List<PropertyTreeNode> ParseSequenceItems(
string[] lines, ref int lineIdx, int dashIndent, string parentPath)
{
List<PropertyTreeNode> items = new List<PropertyTreeNode>();
int itemIndex = 0;
while (lineIdx < lines.Length)
{
string line = TrimLineEnd(lines[lineIdx]);
if (string.IsNullOrWhiteSpace(line))
{
lineIdx++;
continue;
}
int indent = CountLeadingSpaces(line);
if (indent < dashIndent)
break;
string content = line.Substring(indent);
if (IsDirectiveLine(content))
{
lineIdx++;
continue;
}
if (indent != dashIndent ||
!content.StartsWith("- ", StringComparison.Ordinal))
break;
lineIdx++;
string itemPath = $"{parentPath}[{itemIndex}]";
string itemName = $"[{itemIndex}]";
string itemContent = content.Substring(2).Trim();
int contentIndent = indent + 2;
PropertyTreeNode itemNode;
if (string.IsNullOrEmpty(itemContent))
{
List<PropertyTreeNode> children = ParseMappingEntries(
lines, ref lineIdx, indent, itemPath);
string label = FindNameLabel(children);
itemNode = PropertyTreeNode.CreateObject(
itemName, itemPath, children, label);
}
else if (TrySplitKeyValue(
itemContent, out string key, out string value))
{
List<PropertyTreeNode> itemChildren = new List<PropertyTreeNode>();
string firstPath = AppendPath(itemPath, key);
string firstDisplay = ObjectNames.NicifyVariableName(key);
PropertyTreeNode firstChild = BuildValueNode(
lines, ref lineIdx, contentIndent,
key, firstPath, firstDisplay, value);
itemChildren.Add(firstChild);
List<PropertyTreeNode> siblings = ParseMappingEntries(
lines, ref lineIdx, indent, itemPath);
itemChildren.AddRange(siblings);
string label = FindNameLabel(itemChildren);
itemNode = PropertyTreeNode.CreateObject(
itemName, itemPath, itemChildren, label);
}
else
{
LeafPropertyData leafData = InferScalarType(
string.Empty, itemPath, itemContent);
itemNode = PropertyTreeNode.CreateLeaf(
itemName, itemPath, leafData.PropertyType.ToString(),
leafData.StringValue, null, leafData);
}
items.Add(itemNode);
itemIndex++;
}
return items;
}
static string FindNameLabel(List<PropertyTreeNode> children)
{
foreach (PropertyTreeNode child in children)
{
if (child.Kind != NodeKind.Leaf)
continue;
bool isLabelKey =
string.Equals(child.Name, "name", StringComparison.OrdinalIgnoreCase) ||
string.Equals(child.Name, "buildTarget", StringComparison.OrdinalIgnoreCase);
if (!isLabelKey)
continue;
string value = child.Value?.Trim();
if (!string.IsNullOrEmpty(value))
return value;
}
return null;
}
#endregion
#region Inline Parsing
static PropertyTreeNode ParseInlineMap(
string name, string path, string displayName, string text)
{
string inner = text.Substring(1, text.Length - 2).Trim();
if (string.IsNullOrEmpty(inner))
return PropertyTreeNode.CreateObject(
name, path, new List<PropertyTreeNode>(), displayName);
if (TryBuildInlineVector(
name, path, displayName, inner, out PropertyTreeNode vectorNode))
return vectorNode;
if (TryBuildInlineRect(
name, path, displayName, inner, out PropertyTreeNode rectNode))
return rectNode;
List<PropertyTreeNode> children = new List<PropertyTreeNode>();
foreach (string part in SplitInlineElements(inner))
{
if (!TrySplitKeyValue(part, out string key, out string value))
continue;
string childPath = AppendPath(path, key);
string childDisplay = ObjectNames.NicifyVariableName(key);
children.Add(CreateTypedLeaf(key, childPath, childDisplay, value));
}
return PropertyTreeNode.CreateObject(name, path, children, displayName);
}
static bool TryBuildInlineVector(
string name, string path, string displayName,
string inner, out PropertyTreeNode node)
{
node = null;
Dictionary<string, float> components = new Dictionary<string, float>(
StringComparer.OrdinalIgnoreCase);
foreach (string part in SplitInlineElements(inner))
{
if (!TrySplitKeyValue(part, out string key, out string val))
return false;
if (!VECTOR_COMPONENT_KEYS.Contains(key.ToLowerInvariant()))
return false;
if (!float.TryParse(
UnquoteValue(val), NumberStyles.Float,
CultureInfo.InvariantCulture, out float parsed))
return false;
components[key.ToLowerInvariant()] = parsed;
}
LeafPropertyData leafData;
if (components.Count == 2 &&
components.ContainsKey("x") &&
components.ContainsKey("y"))
{
Vector2 vec = new Vector2(components["x"], components["y"]);
leafData = new LeafPropertyData
{
PropertyType = SerializedPropertyType.Vector2,
StringValue = vec.ToString(),
Vector2Value = vec
};
}
else if (components.Count == 3 &&
components.ContainsKey("x") &&
components.ContainsKey("y") &&
components.ContainsKey("z"))
{
Vector3 vec = new Vector3(
components["x"], components["y"], components["z"]);
leafData = new LeafPropertyData
{
PropertyType = SerializedPropertyType.Vector3,
StringValue = vec.ToString(),
Vector3Value = vec
};
}
else if (components.Count == 4 &&
components.ContainsKey("x") &&
components.ContainsKey("y") &&
components.ContainsKey("z") &&
components.ContainsKey("w"))
{
Vector4 vec = new Vector4(
components["x"], components["y"],
components["z"], components["w"]);
leafData = new LeafPropertyData
{
PropertyType = SerializedPropertyType.Vector4,
StringValue = vec.ToString(),
Vector4Value = vec
};
}
else
{
return false;
}
node = PropertyTreeNode.CreateLeaf(
name, path, leafData.PropertyType.ToString(),
leafData.StringValue, displayName, leafData);
return true;
}
static bool TryBuildInlineRect(
string name, string path, string displayName,
string inner, out PropertyTreeNode node)
{
node = null;
Dictionary<string, float> components = new Dictionary<string, float>(
StringComparer.OrdinalIgnoreCase);
foreach (string part in SplitInlineElements(inner))
{
if (!TrySplitKeyValue(part, out string key, out string val))
return false;
string lowerKey = key.ToLowerInvariant();
if (!RECT_COMPONENT_KEYS.Contains(lowerKey))
return false;
if (!float.TryParse(
UnquoteValue(val), NumberStyles.Float,
CultureInfo.InvariantCulture, out float parsed))
return false;
components[lowerKey] = parsed;
}
if (components.Count != 4 ||
!components.ContainsKey("x") ||
!components.ContainsKey("y") ||
!components.ContainsKey("width") ||
!components.ContainsKey("height"))
return false;
Rect rect = new Rect(
components["x"], components["y"],
components["width"], components["height"]);
LeafPropertyData leafData = new LeafPropertyData
{
PropertyType = SerializedPropertyType.Rect,
StringValue = rect.ToString(),
RectValue = rect
};
node = PropertyTreeNode.CreateLeaf(
name, path, leafData.PropertyType.ToString(),
leafData.StringValue, displayName, leafData);
return true;
}
static PropertyTreeNode ParseInlineSequence(
string name, string path, string displayName, string text)
{
string inner = text.Substring(1, text.Length - 2).Trim();
if (string.IsNullOrEmpty(inner))
return PropertyTreeNode.CreateArray(
name, path, new List<PropertyTreeNode>(), displayName);
List<PropertyTreeNode> children = new List<PropertyTreeNode>();
int index = 0;
foreach (string element in SplitInlineElements(inner))
{
string itemPath = $"{path}[{index}]";
string itemName = $"[{index}]";
children.Add(CreateTypedLeaf(itemName, itemPath, null, element));
index++;
}
return PropertyTreeNode.CreateArray(name, path, children, displayName);
}
#endregion
#region Type Inference
static PropertyTreeNode CreateTypedLeaf(
string name, string path, string displayName, string rawValue)
{
LeafPropertyData leafData = InferScalarType(name, path, rawValue);
return PropertyTreeNode.CreateLeaf(
name, path, leafData.PropertyType.ToString(),
leafData.StringValue, displayName, leafData);
}
static LeafPropertyData InferScalarType(string key, string path, string rawValue)
{
string raw = (rawValue ?? string.Empty).Trim();
bool wasQuoted = IsQuotedValue(raw);
string display = UnquoteValue(raw);
if (wasQuoted)
return MakeStringLeaf(display);
if (IsBooleanNumericValue(key, raw, out bool boolFromNumeric))
{
return new LeafPropertyData
{
PropertyType = SerializedPropertyType.Boolean,
BoolValue = boolFromNumeric,
StringValue = boolFromNumeric.ToString()
};
}
if (TryParseBooleanLiteral(raw, out bool boolValue))
{
return new LeafPropertyData
{
PropertyType = SerializedPropertyType.Boolean,
BoolValue = boolValue,
StringValue = boolValue.ToString()
};
}
if (int.TryParse(raw, NumberStyles.Integer,
CultureInfo.InvariantCulture, out int intValue))
{
LeafPropertyData intLeaf = new LeafPropertyData
{
PropertyType = SerializedPropertyType.Integer,
IntValue = intValue,
StringValue = intValue.ToString()
};
if (!string.IsNullOrEmpty(path) &&
IntPropertyFormatters.TryFormatPath(path, intValue, out string formatted))
{
intLeaf.StringValue = formatted;
intLeaf.HasFormattedDisplay = true;
}
return intLeaf;
}
if (LooksLikeFloat(raw) &&
float.TryParse(raw, NumberStyles.Float,
CultureInfo.InvariantCulture, out float floatValue))
{
return new LeafPropertyData
{
PropertyType = SerializedPropertyType.Float,
FloatValue = floatValue,
StringValue = floatValue.ToString("G")
};
}
return MakeStringLeaf(display);
}
static LeafPropertyData MakeStringLeaf(string value)
{
return new LeafPropertyData
{
PropertyType = SerializedPropertyType.String,
StringValue = value
};
}
static bool IsBooleanNumericValue(
string key, string value, out bool result)
{
result = false;
if (value != "0" && value != "1")
return false;
if (string.IsNullOrEmpty(key))
return false;
string leafKey = ExtractLeafName(key);
if (BOOLEAN_HINT_KEYS.Contains(leafKey) || LooksLikeBooleanKey(leafKey))
{
result = value == "1";
return true;
}
return false;
}
static bool LooksLikeBooleanKey(string key)
{
return StartsWithAny(key,
"is", "has", "use", "can", "allow",
"enable", "disable", "force", "preload",
"normalize", "loop");
}
static bool StartsWithAny(string text, params string[] prefixes)
{
foreach (string prefix in prefixes)
{
if (text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
static bool TryParseBooleanLiteral(string value, out bool result)
{
if (value.Equals("true", StringComparison.OrdinalIgnoreCase) ||
value.Equals("yes", StringComparison.OrdinalIgnoreCase))
{
result = true;
return true;
}
if (value.Equals("false", StringComparison.OrdinalIgnoreCase) ||
value.Equals("no", StringComparison.OrdinalIgnoreCase))
{
result = false;
return true;
}
result = false;
return false;
}
static bool LooksLikeFloat(string value)
{
return value.IndexOf('.') >= 0 ||
value.IndexOf('e') >= 0 ||
value.IndexOf('E') >= 0;
}
#endregion
#region String Parsing Utilities
static IEnumerable<string> SplitInlineElements(string text)
{
List<string> result = new List<string>();
int start = 0;
int curlyDepth = 0;
int squareDepth = 0;
char quote = '\0';
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
if (quote != '\0')
{
if (c == quote && (i == 0 || text[i - 1] != '\\'))
quote = '\0';
continue;
}
if (c == '"' || c == '\'') { quote = c; continue; }
if (c == '{') { curlyDepth++; continue; }
if (c == '}') { curlyDepth--; continue; }
if (c == '[') { squareDepth++; continue; }
if (c == ']') { squareDepth--; continue; }
if (c == ',' && curlyDepth == 0 && squareDepth == 0)
{
result.Add(text.Substring(start, i - start).Trim());
start = i + 1;
}
}
if (start < text.Length)
result.Add(text.Substring(start).Trim());
return result;
}
static bool TrySplitKeyValue(
string text, out string key, out string value)
{
key = null;
value = null;
int curlyDepth = 0;
int squareDepth = 0;
char quote = '\0';
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
if (quote != '\0')
{
if (c == quote && (i == 0 || text[i - 1] != '\\'))
quote = '\0';
continue;
}
if (c == '"' || c == '\'') { quote = c; continue; }
if (c == '{') { curlyDepth++; continue; }
if (c == '}') { curlyDepth--; continue; }
if (c == '[') { squareDepth++; continue; }
if (c == ']') { squareDepth--; continue; }
if (c == ':' && curlyDepth == 0 && squareDepth == 0)
{
key = text.Substring(0, i).Trim();
value = text.Substring(i + 1).Trim();
return !string.IsNullOrEmpty(key);
}
}
return false;
}
static bool IsQuotedValue(string value)
{
if (string.IsNullOrEmpty(value) || value.Length < 2)
return false;
return (value[0] == '"' && value[value.Length - 1] == '"') ||
(value[0] == '\'' && value[value.Length - 1] == '\'');
}
static string UnquoteValue(string value)
{
return IsQuotedValue(value)
? value.Substring(1, value.Length - 2)
: value;
}
static int CountLeadingSpaces(string line)
{
int count = 0;
while (count < line.Length && line[count] == ' ')
count++;
return count;
}
static bool IsDirectiveLine(string content)
{
return content.StartsWith("%", StringComparison.Ordinal) ||
content.StartsWith("---", StringComparison.Ordinal) ||
content.StartsWith("...", StringComparison.Ordinal);
}
static string AppendPath(string basePath, string key)
{
return string.IsNullOrEmpty(basePath) ? key : $"{basePath}.{key}";
}
static string ExtractLeafName(string key)
{
int lastDot = key.LastIndexOf('.');
string segment = lastDot >= 0 ? key.Substring(lastDot + 1) : key;
int bracket = segment.IndexOf('[');
if (bracket >= 0)
segment = segment.Substring(0, bracket);
return segment;
}
static string TrimLineEnd(string line)
{
return line.TrimEnd('\r');
}
static void SkipBlankAndDirectiveLines(string[] lines, ref int lineIdx)
{
while (lineIdx < lines.Length)
{
string line = TrimLineEnd(lines[lineIdx]);
if (string.IsNullOrWhiteSpace(line))
{
lineIdx++;
continue;
}
int indent = CountLeadingSpaces(line);
string content = line.Substring(indent);
if (IsDirectiveLine(content))
{
lineIdx++;
continue;
}
break;
}
}
#endregion
#region Constants
static readonly HashSet<string> BOOLEAN_HINT_KEYS =
new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"3D",
"ambisonic",
"alphaIsTransparency",
"convertToNormalmap",
"crunchedCompression",
"forceToMono",
"generateCubemap",
"ignorePngGamma",
"isReadable",
"loadInBackground",
"loopable",
"mipMapsPreserveCoverage",
"normalize",
"preloadAudioData",
"streamingMipmaps",
"sRGBTexture"
};
static readonly HashSet<string> VECTOR_COMPONENT_KEYS =
new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{ "x", "y", "z", "w" };
static readonly HashSet<string> RECT_COMPONENT_KEYS =
new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{ "x", "y", "width", "height" };
#endregion
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5bd2166cb8eff417d8c9b840aeaa5709
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using Unity.PlasticSCM.Editor.Diff.Asset.Common.Property;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common.Meta
{
internal static class MetaTreeHelpers
{
internal static PropertyTreeNode FilterIgnoredKeys(PropertyTreeNode root)
{
List<PropertyTreeNode> filteredChildren = new List<PropertyTreeNode>();
foreach (PropertyTreeNode child in root.Children)
{
if (!IGNORED_TOP_LEVEL_KEYS.Contains(child.Name))
filteredChildren.Add(child);
}
return PropertyTreeNode.CreateRoot(filteredChildren);
}
static readonly HashSet<string> IGNORED_TOP_LEVEL_KEYS =
new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"guid",
"timeCreated",
"licenseType"
};
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c7acea46926a4331a5b68771443e3ed0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,19 @@
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common
{
internal static class ObjectExtensions
{
internal static int GetObjectId(this UnityEngine.Object obj)
{
#if UNITY_6000_4_OR_NEWER
return obj.GetEntityId().GetHashCode();
#else
return obj.GetInstanceID();
#endif
}
internal static long GetLocalFileId(this UnityEngine.Object obj)
{
return (long)UnityInternals.UnityEditor.Unsupported.GetFileIDHint(obj);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 209109a5fbc749468a4eb859dc531bd2
timeCreated: 1777362119
@@ -0,0 +1,72 @@
using Unity.PlasticSCM.Editor.Diff.Asset.Content;
using Unity.PlasticSCM.Editor.Diff.Asset.Diff;
using UnityEditor;
using UnityEngine;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common
{
internal static class ObjectIconResolver
{
internal static UnityEngine.Texture GetIcon(ObjectContent objContent)
{
if (objContent.IsMetaFileObject)
return GetMetaIcon(objContent.MetaSectionName);
return GetObjectIcon(objContent.Object);
}
internal static UnityEngine.Texture GetIcon(ObjectDiff objDiff)
{
if (objDiff.IsMetaFileObject)
return GetMetaIcon(objDiff.MetaSectionName);
return GetObjectIcon(objDiff.SrcObject ?? objDiff.DstObject);
}
static UnityEngine.Texture GetObjectIcon(UnityEngine.Object obj)
{
if (obj == null)
return GetFallbackIcon();
GUIContent content = EditorGUIUtility.ObjectContent(obj, obj.GetType());
return content.image != null ? content.image : GetFallbackIcon();
}
// Section names arrive nicified ("Audio Importer"), but our match
// tokens are the unspaced YAML keys ("audioimporter"). Normalise by
// stripping whitespace before the lowercase contains-check.
static UnityEngine.Texture GetMetaIcon(string sectionName)
{
if (string.IsNullOrEmpty(sectionName))
return GetFallbackIcon();
string key = sectionName.Replace(" ", "").ToLowerInvariant();
if (key.Contains("textureimporter"))
return TryGetIcon("Texture Icon");
if (key.Contains("audioimporter"))
return TryGetIcon("AudioClip Icon");
if (key.Contains("modelimporter"))
return TryGetIcon("PrefabModel Icon");
if (key.Contains("sprite"))
return TryGetIcon("Sprite Icon");
if (key.Contains("platformsettings"))
return TryGetIcon("BuildSettings.Editor.Small");
return TryGetIcon("TextAsset Icon");
}
static UnityEngine.Texture TryGetIcon(string iconName)
{
GUIContent content = EditorGUIUtility.IconContent(iconName);
if (content == null || content.image == null)
return GetFallbackIcon();
return content.image;
}
static UnityEngine.Texture GetFallbackIcon()
{
return EditorGUIUtility.IconContent("DefaultAsset Icon").image;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ef733891bfbb64dd2baa2c1668c7021a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d0a9ebc8de8b8428fae0574a3a7abc3f
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,129 @@
using System.Collections.Generic;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common.Property
{
// Replaces the generic "Curve" display name on AnimationClip curve leaves
// with a label derived from the parent struct's `attribute` and `path`
// fields, mirroring Unity's Animation window naming
// (e.g. "Position.x", "Rotation.y (Spine/Head)").
internal static class AnimationClipCurveLabels
{
internal static void TryDecorate(
List<PropertyTreeNode> arrayElements, string arrayPath)
{
if (!IsCurveArray(arrayPath))
return;
string fallback = GetFallbackLabel(arrayPath);
for (int i = 0; i < arrayElements.Count; i++)
{
PropertyTreeNode element = arrayElements[i];
if (element.Kind != NodeKind.Object)
continue;
PropertyTreeNode curveChild = null;
string attribute = null;
string targetPath = null;
foreach (PropertyTreeNode child in element.Children)
{
switch (child.Name)
{
case "curve": curveChild = child; break;
case "attribute": attribute = child.Value; break;
case "path": targetPath = child.Value; break;
}
}
if (curveChild == null || curveChild.Kind != NodeKind.Leaf)
continue;
string label = BuildLabel(attribute, targetPath, fallback);
arrayElements[i] = ReplaceChildDisplayName(element, curveChild, label);
}
}
static bool IsCurveArray(string path)
{
switch (path)
{
case "m_PositionCurves":
case "m_RotationCurves":
case "m_ScaleCurves":
case "m_EulerCurves":
case "m_FloatCurves":
case "m_PPtrCurves":
case "m_EditorCurves":
case "m_EulerEditorCurves":
return true;
default:
return false;
}
}
static string GetFallbackLabel(string arrayPath)
{
switch (arrayPath)
{
case "m_PositionCurves": return "Position";
case "m_RotationCurves": return "Rotation";
case "m_ScaleCurves": return "Scale";
case "m_EulerCurves": return "Rotation (Euler)";
case "m_EulerEditorCurves": return "Rotation (Euler)";
default: return "Curve";
}
}
static string BuildLabel(
string attribute, string targetPath, string fallback)
{
string baseLabel = string.IsNullOrEmpty(attribute)
? fallback
: StripAttributePrefix(attribute);
if (string.IsNullOrEmpty(targetPath))
return baseLabel;
return baseLabel + " (" + targetPath + ")";
}
static string StripAttributePrefix(string attribute)
{
if (attribute.StartsWith("m_Local"))
return attribute.Substring("m_Local".Length);
if (attribute.StartsWith("m_"))
return attribute.Substring(2);
return attribute;
}
static PropertyTreeNode ReplaceChildDisplayName(
PropertyTreeNode parent,
PropertyTreeNode targetChild,
string newDisplayName)
{
List<PropertyTreeNode> newChildren = new List<PropertyTreeNode>(
parent.Children.Count);
foreach (PropertyTreeNode child in parent.Children)
{
if (child == targetChild)
{
newChildren.Add(PropertyTreeNode.CreateLeaf(
child.Name, child.Path, child.TypeTag, child.Value,
newDisplayName, child.Tag));
continue;
}
newChildren.Add(child);
}
return PropertyTreeNode.CreateObject(
parent.Name, parent.Path, newChildren, parent.DisplayName, parent.Tag);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 8c2f1ab3d4e5f64a9b7c0d1e2f3a4b5c
timeCreated: 1763000000
@@ -0,0 +1,47 @@
using UnityEditor;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common.Property
{
internal static class GroupHeaderLabels
{
internal static string ForArray(string displayName, string path)
{
if (string.IsNullOrEmpty(displayName) || displayName.StartsWith("m_"))
return ObjectNames.NicifyVariableName(SafeLastSegment(path));
return displayName;
}
internal static string ForArrayElement(string path)
{
return ELEMENT_PREFIX + (ExtractTrailingElementIndex(path) + 1);
}
static string SafeLastSegment(string path)
{
if (string.IsNullOrEmpty(path))
return string.Empty;
int lastDot = path.LastIndexOf('.');
return lastDot < 0 ? path : path.Substring(lastDot + 1);
}
static int ExtractTrailingElementIndex(string path)
{
if (string.IsNullOrEmpty(path))
return 0;
int closeBracket = path.LastIndexOf(']');
if (closeBracket <= 0)
return 0;
int openBracket = path.LastIndexOf('[', closeBracket - 1);
if (openBracket < 0)
return 0;
string indexText = path.Substring(
openBracket + 1, closeBracket - openBracket - 1);
return int.TryParse(indexText, out int idx) ? idx : 0;
}
const string ELEMENT_PREFIX = "Element ";
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 5efbadbb9912116bb00fdab47698bcf4
timeCreated: 1747000000
@@ -0,0 +1,67 @@
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common.Property
{
internal static class IgnoredProperties
{
internal static bool IsIgnored(string propertyPath)
{
// editor-only flags on every UnityEngine.Object
if (propertyPath == "m_ObjectHideFlags")
return true;
if (propertyPath == "m_EditorHideFlags")
return true;
// internal class-mapping field on MonoBehaviours
if (propertyPath == "m_EditorClassIdentifier")
return true;
// reference to the script asset itself
if (propertyPath == "m_Script" || propertyPath.StartsWith("m_Script."))
return true;
// opaque serialized-reference IDs inside ObjectReference fields
if (propertyPath.Contains(".m_FileID") || propertyPath.Contains(".m_PathID"))
return true;
// prefab system bookkeeping (includes legacy pre-2018.3 names)
if (propertyPath == "m_CorrespondingSourceObject" ||
propertyPath == "m_PrefabInstance" ||
propertyPath == "m_PrefabAsset" ||
propertyPath == "m_PrefabParentObject" ||
propertyPath == "m_PrefabInternal")
return true;
// GameObject's component list — components are diffed individually
if (propertyPath == "m_Component" || propertyPath.StartsWith("m_Component."))
return true;
// back-reference from Component to its owning GameObject
if (propertyPath == "m_GameObject" || propertyPath.StartsWith("m_GameObject."))
return true;
// scene/prefab root list — structural, not property data
if (propertyPath == "m_Roots" || propertyPath.StartsWith("m_Roots."))
return true;
// Transform hierarchy (parent/children/sibling order)
if (propertyPath == "m_Children" || propertyPath.StartsWith("m_Children."))
return true;
if (propertyPath == "m_Father" || propertyPath.StartsWith("m_Father."))
return true;
if (propertyPath == "m_RootOrder")
return true;
// redundant editor hint — the real rotation is m_LocalRotation
if (propertyPath.StartsWith("m_LocalEulerAnglesHint"))
return true;
// editor-only shadow data for animation curves
if (propertyPath == "m_EditorCurves" || propertyPath.StartsWith("m_EditorCurves."))
return true;
if (propertyPath == "m_EulerEditorCurves" || propertyPath.StartsWith("m_EulerEditorCurves."))
return true;
return false;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 1c717ffc06a346f49df5a2fe06338439
timeCreated: 1775035659
@@ -0,0 +1,306 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common.Property
{
internal static class IntPropertyFormatters
{
internal static bool TryFormat(SerializedProperty prop, out string display)
{
display = null;
if (prop.propertyType == SerializedPropertyType.LayerMask)
{
display = FormatLayerMaskBits(prop.intValue);
return true;
}
if (prop.propertyType != SerializedPropertyType.Integer)
return false;
UnityEngine.Object target = prop.serializedObject.targetObject;
int value = prop.intValue;
if (TryFormatFromRegistry(target, prop.propertyPath, value, out display))
return true;
if (TryFormatFromReflectedEnum(target, prop.propertyPath, value, out display))
return true;
return TryFormatFromPathFallback(prop.propertyPath, value, out display);
}
internal static bool TryFormatPath(string path, int value, out string display)
{
return TryFormatFromPathFallback(path, value, out display);
}
internal static string FormatEnum(Type enumType, int value)
{
bool bIsFlags = enumType.IsDefined(typeof(FlagsAttribute), inherit: false);
if (bIsFlags)
{
if (value == 0)
return NOTHING_LABEL;
return NicifyFlagsList(Enum.ToObject(enumType, value).ToString());
}
string name = Enum.GetName(enumType, value);
return name == null ? value.ToString() : ObjectNames.NicifyVariableName(name);
}
static string NicifyFlagsList(string commaJoined)
{
if (string.IsNullOrEmpty(commaJoined))
return commaJoined;
string[] parts = commaJoined.Split(',');
for (int i = 0; i < parts.Length; i++)
parts[i] = ObjectNames.NicifyVariableName(parts[i].Trim());
return string.Join(", ", parts);
}
static bool TryFormatFromRegistry(
UnityEngine.Object target, string path, int value, out string display)
{
display = null;
if (target == null)
return false;
Type type = target.GetType();
for (Type t = type; t != null; t = t.BaseType)
{
Func<int, string> formatter;
if (mRegistry.TryGetValue(BuildKey(t, path), out formatter))
{
display = formatter(value);
return display != null;
}
}
return false;
}
static bool TryFormatFromPathFallback(string path, int value, out string display)
{
display = null;
Func<int, string> fallback;
if (mFallbackByPath.TryGetValue(path, out fallback))
{
display = fallback(value);
return display != null;
}
return false;
}
static bool TryFormatFromReflectedEnum(
UnityEngine.Object target, string path, int value, out string display)
{
display = null;
if (target == null)
return false;
FieldInfo field = ResolveFieldByPath(target.GetType(), path);
if (field == null || !field.FieldType.IsEnum)
return false;
display = FormatEnum(field.FieldType, value);
return true;
}
static FieldInfo ResolveFieldByPath(Type type, string path)
{
const BindingFlags FLAGS =
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
Type current = type;
FieldInfo field = null;
string[] segments = path.Split('.');
for (int i = 0; i < segments.Length; i++)
{
if (current == null)
return null;
string segment = segments[i];
if (segment == "Array" || segment.StartsWith("data["))
return null;
field = current.GetField(segment, FLAGS);
if (field == null)
return null;
current = field.FieldType;
}
return field;
}
static string FormatStaticEditorFlags(int value)
{
if (value == 0)
return NOTHING_LABEL;
if (value == int.MaxValue)
return EVERYTHING_LABEL;
string raw = ((StaticEditorFlags)value).ToString()
.Replace(
"LightmapStatic", // obsolete -> use ContributeGI
nameof(StaticEditorFlags.ContributeGI));
return NicifyFlagsList(raw);
}
static string FormatLayer(int value)
{
string name = LayerMask.LayerToName(value);
return string.IsNullOrEmpty(name) ? value.ToString() : name;
}
static string FormatTargetDisplay(int value)
{
return string.Format("Display {0}", value + 1);
}
static string FormatLayerMaskBits(int value)
{
if (value == 0)
return "Nothing";
uint bits = unchecked((uint)value);
if (bits == uint.MaxValue)
return "Everything";
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 32; i++)
{
if ((bits & (1u << i)) == 0)
continue;
string layerName = LayerMask.LayerToName(i);
if (string.IsNullOrEmpty(layerName))
continue;
if (builder.Length > 0)
builder.Append(", ");
builder.Append(layerName);
}
if (builder.Length == 0)
return string.Format("0x{0:X8}", bits);
return builder.ToString();
}
static string BuildKey(Type type, string path)
{
return string.Concat(type.FullName, "|", path);
}
static Dictionary<string, Func<int, string>> BuildRegistry()
{
Dictionary<string, Func<int, string>> registry =
new Dictionary<string, Func<int, string>>();
Add(registry, typeof(GameObject), "m_StaticEditorFlags", FormatStaticEditorFlags);
Add(registry, typeof(GameObject), "m_Layer", FormatLayer);
Add(registry, typeof(Camera), "m_FOVAxisMode",
value => FormatEnum(typeof(Camera.FieldOfViewAxis), value));
Add(registry, typeof(Camera), "m_GateFitMode",
value => FormatEnum(typeof(Camera.GateFitMode), value));
Add(registry, typeof(Camera), "m_RenderingPath",
value => FormatEnum(typeof(RenderingPath), value));
Add(registry, typeof(Camera), "m_TargetEye",
value => FormatEnum(typeof(StereoTargetEyeMask), value));
Add(registry, typeof(Camera), "m_ClearFlags",
value => FormatEnum(typeof(CameraClearFlags), value));
Add(registry, typeof(Camera), "m_TargetDisplay", FormatTargetDisplay);
Add(registry, typeof(Light), "m_Type",
value => FormatEnum(typeof(LightType), value));
Add(registry, typeof(Light), "m_Lightmapping",
value => FormatEnum(typeof(LightmapBakeType), value));
Add(registry, typeof(Light), "m_Shadows.m_Type",
value => FormatEnum(typeof(LightShadows), value));
Add(registry, typeof(Renderer), "m_LightProbeUsage",
value => FormatEnum(typeof(LightProbeUsage), value));
Add(registry, typeof(Renderer), "m_ReflectionProbeUsage",
value => FormatEnum(typeof(ReflectionProbeUsage), value));
Add(registry, typeof(ReflectionProbe), "m_Mode",
value => FormatEnum(typeof(ReflectionProbeMode), value));
Add(registry, typeof(ReflectionProbe), "m_ClearFlags",
value => FormatEnum(typeof(CameraClearFlags), value));
Add(registry, typeof(Rigidbody), "m_Constraints",
value => FormatEnum(typeof(RigidbodyConstraints), value));
Add(registry, typeof(Rigidbody2D), "m_Constraints",
value => FormatEnum(typeof(RigidbodyConstraints2D), value));
return registry;
}
static Dictionary<string, Func<int, string>> BuildFallbackByPath()
{
// Path-keyed entries used when sRegistry has no match, or when the caller
// has no target type at all (meta-file YAML parsing). Reach for sRegistry
// first; only add here when one of the cases below applies.
Dictionary<string, Func<int, string>> fallback =
new Dictionary<string, Func<int, string>>();
// LayerMask struct fields appear on many unrelated components
// (Camera, Rigidbody, every Collider variant...). Path-keyed avoids
// listing one entry per component type.
fallback["m_CullingMask.m_Bits"] = FormatLayerMaskBits;
fallback["m_IncludeLayers.m_Bits"] = FormatLayerMaskBits;
fallback["m_ExcludeLayers.m_Bits"] = FormatLayerMaskBits;
// Meta-file YAML has no SerializedObject, so MetaPropertyTreeBuilder
// calls TryFormatPath without a target type. The full path includes
// the document type prefix produced by the YAML parser.
fallback["AudioImporter.defaultSettings.loadType"] =
value => FormatEnum(typeof(AudioClipLoadType), value);
fallback["AudioImporter.defaultSettings.compressionFormat"] =
value => FormatEnum(typeof(AudioCompressionFormat), value);
fallback["AudioImporter.defaultSettings.sampleRateSetting"] =
value => FormatEnum(typeof(AudioSampleRateSetting), value);
return fallback;
}
static void Add(
Dictionary<string, Func<int, string>> registry,
Type type,
string path,
Func<int, string> formatter)
{
registry[BuildKey(type, path)] = formatter;
}
const string NOTHING_LABEL = "Nothing";
const string EVERYTHING_LABEL = "Everything";
static readonly Dictionary<string, Func<int, string>> mRegistry = BuildRegistry();
static readonly Dictionary<string, Func<int, string>> mFallbackByPath =
BuildFallbackByPath();
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: b8354167bc3f4fe68167ff2823a4334e
timeCreated: 1778574522
@@ -0,0 +1,180 @@
using UnityEditor;
using UnityEngine;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common.Property
{
internal struct LeafPropertyData
{
internal SerializedPropertyType PropertyType;
internal string StringValue;
internal float FloatValue;
internal int IntValue;
internal bool BoolValue;
internal Vector2 Vector2Value;
internal Vector3 Vector3Value;
internal Vector4 Vector4Value;
internal Vector2Int Vector2IntValue;
internal Vector3Int Vector3IntValue;
internal Color ColorValue;
internal Quaternion QuaternionValue;
internal Rect RectValue;
internal Bounds BoundsValue;
internal AnimationCurve AnimationCurveValue;
internal Gradient GradientValue;
internal RectInt RectIntValue;
internal BoundsInt BoundsIntValue;
internal Hash128 Hash128Value;
internal bool HasFormattedDisplay;
internal static LeafPropertyData FromProperty(SerializedProperty prop)
{
LeafPropertyData data = new LeafPropertyData
{
PropertyType = prop.propertyType,
StringValue = GetStringValue(prop)
};
switch (prop.propertyType)
{
case SerializedPropertyType.Float:
data.FloatValue = prop.floatValue; break;
case SerializedPropertyType.Integer:
data.IntValue = prop.intValue;
string formattedInt;
if (IntPropertyFormatters.TryFormat(prop, out formattedInt))
{
data.StringValue = formattedInt;
data.HasFormattedDisplay = true;
}
break;
case SerializedPropertyType.LayerMask:
data.IntValue = prop.intValue;
string formattedLayerMask;
if (IntPropertyFormatters.TryFormat(prop, out formattedLayerMask))
{
data.StringValue = formattedLayerMask;
data.HasFormattedDisplay = true;
}
break;
case SerializedPropertyType.Character:
data.IntValue = prop.intValue; break;
case SerializedPropertyType.Boolean:
data.BoolValue = prop.boolValue; break;
case SerializedPropertyType.Vector2:
data.Vector2Value = prop.vector2Value; break;
case SerializedPropertyType.Vector3:
data.Vector3Value = prop.vector3Value; break;
case SerializedPropertyType.Vector4:
data.Vector4Value = prop.vector4Value; break;
case SerializedPropertyType.Vector2Int:
data.Vector2IntValue = prop.vector2IntValue; break;
case SerializedPropertyType.Vector3Int:
data.Vector3IntValue = prop.vector3IntValue; break;
case SerializedPropertyType.Color:
data.ColorValue = prop.colorValue; break;
case SerializedPropertyType.Quaternion:
data.QuaternionValue = prop.quaternionValue; break;
case SerializedPropertyType.Rect:
data.RectValue = prop.rectValue; break;
case SerializedPropertyType.Bounds:
data.BoundsValue = prop.boundsValue; break;
case SerializedPropertyType.String:
data.StringValue = prop.stringValue; break;
case SerializedPropertyType.Enum:
data.IntValue = prop.enumValueIndex;
data.StringValue = prop.enumDisplayNames.Length > prop.enumValueIndex
&& prop.enumValueIndex >= 0
? prop.enumDisplayNames[prop.enumValueIndex]
: prop.enumValueIndex.ToString();
break;
case SerializedPropertyType.AnimationCurve:
data.AnimationCurveValue = prop.animationCurveValue; break;
case SerializedPropertyType.Gradient:
data.GradientValue = prop.gradientValue; break;
case SerializedPropertyType.RectInt:
data.RectIntValue = prop.rectIntValue; break;
case SerializedPropertyType.BoundsInt:
data.BoundsIntValue = prop.boundsIntValue; break;
case SerializedPropertyType.Hash128:
data.Hash128Value = prop.hash128Value; break;
}
return data;
}
static string GetStringValue(SerializedProperty prop)
{
switch (prop.propertyType)
{
case SerializedPropertyType.Integer:
string formattedInt;
if (IntPropertyFormatters.TryFormat(prop, out formattedInt))
return formattedInt;
return prop.intValue.ToString();
case SerializedPropertyType.ArraySize:
case SerializedPropertyType.FixedBufferSize:
return prop.intValue.ToString();
case SerializedPropertyType.Boolean:
return prop.boolValue.ToString();
case SerializedPropertyType.Float:
return prop.floatValue.ToString("G");
case SerializedPropertyType.String:
return prop.stringValue;
case SerializedPropertyType.Color:
return prop.colorValue.ToString();
case SerializedPropertyType.ObjectReference:
UnityEngine.Object obj = prop.objectReferenceValue;
return obj == null
? "(None)"
: $"{obj.GetType().Name}: {obj.name}";
case SerializedPropertyType.LayerMask:
string formattedLayerMask;
if (IntPropertyFormatters.TryFormat(prop, out formattedLayerMask))
return formattedLayerMask;
return prop.intValue.ToString();
case SerializedPropertyType.Enum:
return prop.enumDisplayNames.Length > prop.enumValueIndex
&& prop.enumValueIndex >= 0
? prop.enumDisplayNames[prop.enumValueIndex]
: prop.enumValueIndex.ToString();
case SerializedPropertyType.Vector2:
return prop.vector2Value.ToString();
case SerializedPropertyType.Vector3:
return prop.vector3Value.ToString();
case SerializedPropertyType.Vector4:
return prop.vector4Value.ToString();
case SerializedPropertyType.Rect:
return prop.rectValue.ToString();
case SerializedPropertyType.Character:
return ((char)prop.intValue).ToString();
case SerializedPropertyType.AnimationCurve:
AnimationCurve curve = prop.animationCurveValue;
return curve != null
? $"AnimationCurve ({curve.length} keys)"
: "AnimationCurve (empty)";
case SerializedPropertyType.Gradient:
Gradient gradient = prop.gradientValue;
return gradient != null
? $"Gradient ({gradient.colorKeys.Length} color keys, " +
$"{gradient.alphaKeys.Length} alpha keys)"
: "Gradient (empty)";
case SerializedPropertyType.Bounds:
return prop.boundsValue.ToString();
case SerializedPropertyType.Quaternion:
return prop.quaternionValue.eulerAngles.ToString();
case SerializedPropertyType.Vector2Int:
return prop.vector2IntValue.ToString();
case SerializedPropertyType.Vector3Int:
return prop.vector3IntValue.ToString();
case SerializedPropertyType.RectInt:
return prop.rectIntValue.ToString();
case SerializedPropertyType.BoundsInt:
return prop.boundsIntValue.ToString();
case SerializedPropertyType.Hash128:
return prop.hash128Value.ToString();
default:
return $"({prop.propertyType})";
}
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: a3d594c59c4d4cbfb273172a2edb6247
timeCreated: 1774968113
@@ -0,0 +1,272 @@
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common.Property
{
internal static class PropertyTreeBuilder
{
internal static PropertyTreeNode Build(SerializedObject so)
{
List<PropertyTreeNode> children = new List<PropertyTreeNode>();
SerializedProperty prop = so.GetIterator();
if (!prop.Next(true))
return PropertyTreeNode.CreateRoot(children);
do
{
if (IgnoredProperties.IsIgnored(prop.propertyPath))
continue;
children.Add(BuildNode(prop.Copy(), isArrayElement: false));
}
while (prop.Next(false));
return PropertyTreeNode.CreateRoot(children);
}
static PropertyTreeNode BuildNode(
SerializedProperty prop,
bool isArrayElement)
{
string name = ExtractLocalName(prop.propertyPath);
string path = prop.propertyPath;
string displayName = BuildDisplayName(prop);
if (IsLeafProperty(prop))
{
LeafPropertyData leafData = BuildLeafData(prop);
return PropertyTreeNode.CreateLeaf(
name, path, leafData.PropertyType.ToString(),
leafData.StringValue, displayName, leafData);
}
if (isArrayElement)
displayName = GroupHeaderLabels.ForArrayElement(path);
else if (prop.isArray)
displayName = GroupHeaderLabels.ForArray(displayName, path);
if (prop.isArray)
return BuildArrayNode(prop, name, path, displayName);
return BuildObjectNode(prop, name, path, displayName);
}
static LeafPropertyData BuildLeafData(SerializedProperty prop)
{
if (prop.propertyPath == "m_LocalRotation"
&& prop.propertyType == SerializedPropertyType.Quaternion
&& prop.serializedObject.targetObject is Transform transform)
{
Vector3 inspectorEuler = TransformUtils.GetInspectorRotation(transform);
return new LeafPropertyData
{
PropertyType = SerializedPropertyType.Vector3,
Vector3Value = inspectorEuler,
StringValue = inspectorEuler.ToString()
};
}
return LeafPropertyData.FromProperty(prop);
}
static PropertyTreeNode BuildArrayNode(
SerializedProperty prop,
string name,
string path,
string displayName)
{
List<PropertyTreeNode> children = new List<PropertyTreeNode>();
for (int i = 0; i < prop.arraySize; i++)
{
SerializedProperty element = prop.GetArrayElementAtIndex(i);
if (IgnoredProperties.IsIgnored(element.propertyPath))
continue;
children.Add(BuildNode(element.Copy(), isArrayElement: true));
}
AnimationClipCurveLabels.TryDecorate(children, path);
if (IsKeyedArray(prop))
return BuildKeyedArrayAsObject(children, name, path, displayName);
return PropertyTreeNode.CreateArray(name, path, children, displayName);
}
static PropertyTreeNode BuildKeyedArrayAsObject(
List<PropertyTreeNode> rawElements,
string name,
string path,
string displayName)
{
List<PropertyTreeNode> namedChildren = new List<PropertyTreeNode>();
foreach (PropertyTreeNode element in rawElements)
{
string key = null;
PropertyTreeNode valueNode = null;
foreach (PropertyTreeNode child in element.Children)
{
if (child.Name == "first" && child.Kind == NodeKind.Leaf)
key = child.Value;
else if (child.Name == "second")
valueNode = child;
}
if (key != null && valueNode != null)
{
string childPath = path + "." + key;
string childDisplayName = ObjectNames.NicifyVariableName(
key.TrimStart('_'));
if (valueNode.Kind == NodeKind.Leaf)
{
namedChildren.Add(PropertyTreeNode.CreateLeaf(
key, childPath, valueNode.TypeTag,
valueNode.Value, childDisplayName, valueNode.Tag));
}
else
{
List<PropertyTreeNode> rewrappedChildren = new List<PropertyTreeNode>(
valueNode.Children);
namedChildren.Add(PropertyTreeNode.CreateObject(
key, childPath, rewrappedChildren, childDisplayName));
}
}
else
{
namedChildren.Add(element);
}
}
return PropertyTreeNode.CreateObject(name, path, namedChildren, displayName);
}
static PropertyTreeNode BuildObjectNode(
SerializedProperty prop,
string name,
string path,
string displayName)
{
List<PropertyTreeNode> children = new List<PropertyTreeNode>();
int parentDepth = prop.depth;
SerializedProperty iter = prop.Copy();
if (!iter.Next(true) || iter.depth <= parentDepth)
return PropertyTreeNode.CreateObject(name, path, children, displayName);
do
{
if (!IgnoredProperties.IsIgnored(iter.propertyPath))
children.Add(BuildNode(iter.Copy(), isArrayElement: false));
}
while (iter.Next(false) && iter.depth > parentDepth);
return PropertyTreeNode.CreateObject(name, path, children, displayName);
}
static bool IsKeyedArray(SerializedProperty arrayProp)
{
if (arrayProp.arraySize == 0)
return false;
SerializedProperty firstElement = arrayProp.GetArrayElementAtIndex(0);
if (firstElement.propertyType != SerializedPropertyType.Generic)
return false;
int parentDepth = firstElement.depth;
SerializedProperty iter = firstElement.Copy();
if (!iter.Next(true) || iter.depth <= parentDepth)
return false;
bool hasFirst = false;
bool hasSecond = false;
do
{
string localName = ExtractLocalName(iter.propertyPath);
if (localName == "first" && iter.propertyType == SerializedPropertyType.String)
hasFirst = true;
else if (localName == "second")
hasSecond = true;
}
while (iter.Next(false) && iter.depth > parentDepth);
return hasFirst && hasSecond;
}
static bool IsLeafProperty(SerializedProperty prop)
{
switch (prop.propertyType)
{
case SerializedPropertyType.Integer:
case SerializedPropertyType.Boolean:
case SerializedPropertyType.Float:
case SerializedPropertyType.String:
case SerializedPropertyType.Color:
case SerializedPropertyType.ObjectReference:
case SerializedPropertyType.LayerMask:
case SerializedPropertyType.Enum:
case SerializedPropertyType.Vector2:
case SerializedPropertyType.Vector3:
case SerializedPropertyType.Vector4:
case SerializedPropertyType.Rect:
case SerializedPropertyType.Character:
case SerializedPropertyType.AnimationCurve:
case SerializedPropertyType.Bounds:
case SerializedPropertyType.Gradient:
case SerializedPropertyType.Quaternion:
case SerializedPropertyType.Vector2Int:
case SerializedPropertyType.Vector3Int:
case SerializedPropertyType.RectInt:
case SerializedPropertyType.BoundsInt:
case SerializedPropertyType.Hash128:
return true;
case SerializedPropertyType.Generic:
case SerializedPropertyType.ArraySize:
case SerializedPropertyType.FixedBufferSize:
return false;
default:
return !prop.hasChildren;
}
}
static string BuildDisplayName(SerializedProperty prop)
{
string path = prop.propertyPath;
if (path.StartsWith("m_LocalPosition"))
return prop.displayName.Replace("Local ", "");
if (path.StartsWith("m_LocalRotation"))
return prop.displayName.Replace("Local ", "");
if (path.StartsWith("m_LocalScale"))
return prop.displayName.Replace("Local ", "");
return prop.displayName;
}
static string ExtractLocalName(string propertyPath)
{
int lastDot = propertyPath.LastIndexOf('.');
if (lastDot < 0)
return propertyPath;
return propertyPath.Substring(lastDot + 1);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 8bf6e2e635fb45979c87aac695ae7567
timeCreated: 1774968004
@@ -0,0 +1,85 @@
using System.Collections.Generic;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common.Property
{
internal enum NodeKind : byte
{
Leaf,
Object,
Array
}
internal class PropertyTreeNode
{
internal string Name { get; }
internal string Path { get; }
internal string DisplayName { get; }
internal NodeKind Kind { get; }
internal string TypeTag { get; }
internal string Value { get; }
internal IReadOnlyList<PropertyTreeNode> Children => mChildren;
internal object Tag { get; }
internal PropertyTreeNode(
string name,
string path,
string displayName,
NodeKind kind,
string typeTag,
string value,
List<PropertyTreeNode> children,
object tag)
{
Name = name ?? string.Empty;
Path = path ?? string.Empty;
DisplayName = displayName ?? name ?? string.Empty;
Kind = kind;
TypeTag = typeTag ?? string.Empty;
Value = value;
mChildren = children ?? EMPTY_CHILDREN;
Tag = tag;
}
internal static PropertyTreeNode CreateLeaf(
string name,
string path,
string typeTag,
string value,
string displayName = null,
object tag = null)
{
return new PropertyTreeNode(
name, path, displayName, NodeKind.Leaf, typeTag, value, null, tag);
}
internal static PropertyTreeNode CreateObject(
string name,
string path,
List<PropertyTreeNode> children,
string displayName = null,
object tag = null)
{
return new PropertyTreeNode(
name, path, displayName, NodeKind.Object, "Generic", null, children, tag);
}
internal static PropertyTreeNode CreateArray(
string name,
string path,
List<PropertyTreeNode> children,
string displayName = null,
object tag = null)
{
return new PropertyTreeNode(
name, path, displayName, NodeKind.Array, "Array", null, children, tag);
}
internal static PropertyTreeNode CreateRoot(List<PropertyTreeNode> children)
{
return CreateObject(string.Empty, string.Empty, children);
}
static readonly List<PropertyTreeNode> EMPTY_CHILDREN = new List<PropertyTreeNode>();
readonly List<PropertyTreeNode> mChildren;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 54e0e46a04464397b85f0fd0f73f9d33
timeCreated: 1774968610
@@ -0,0 +1,104 @@
using System;
using System.Collections.Generic;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common.Property
{
// Walks a property tree (PropertyTreeNode or PropertyDiffNode) and emits
// rows via caller-supplied callbacks. Replaces the previously duplicated
// AddTreeNode recursion in AssetDiffControl and AssetContentControl with
// a single generic walker, parameterised on the node type via accessors
// (mirroring the HierarchyOrderSorting<T> precedent in this codebase).
internal class PropertyTreeWalker<TNode>
{
internal PropertyTreeWalker(
Func<TNode, NodeKind> getKind,
Func<TNode, IReadOnlyList<TNode>> getChildren)
{
mGetKind = getKind;
mGetChildren = getChildren;
}
// Visits every container in the tree and registers its group key,
// regardless of visibility or expansion state. Run before Walk so
// that CollapseAll can collapse groups that are currently hidden by
// filter / search — otherwise those groups would silently fall out
// of mKnownGroups and re-appear expanded when the filter clears.
internal void CollectGroupKeys(
IReadOnlyList<TNode> roots,
Func<TNode, string> buildGroupKey,
Action<string> registerGroupKey)
{
foreach (TNode node in roots)
CollectGroupKeysFromNode(node, buildGroupKey, registerGroupKey);
}
internal void Walk(
IReadOnlyList<TNode> roots,
int baseIndent,
Func<TNode, bool> isVisible,
Func<TNode, string> buildGroupKey,
Func<string, bool> isExpanded,
Action<TNode, int> emitLeaf,
Action<TNode, int, string> emitContainerHeader)
{
foreach (TNode node in roots)
WalkNode(
node, baseIndent,
isVisible, buildGroupKey, isExpanded,
emitLeaf, emitContainerHeader);
}
void CollectGroupKeysFromNode(
TNode node,
Func<TNode, string> buildGroupKey,
Action<string> registerGroupKey)
{
if (mGetKind(node) == NodeKind.Leaf)
return;
IReadOnlyList<TNode> children = mGetChildren(node);
if (children.Count == 0)
return;
registerGroupKey(buildGroupKey(node));
foreach (TNode child in children)
CollectGroupKeysFromNode(child, buildGroupKey, registerGroupKey);
}
void WalkNode(
TNode node,
int indent,
Func<TNode, bool> isVisible,
Func<TNode, string> buildGroupKey,
Func<string, bool> isExpanded,
Action<TNode, int> emitLeaf,
Action<TNode, int, string> emitContainerHeader)
{
if (!isVisible(node))
return;
if (mGetKind(node) == NodeKind.Leaf)
{
emitLeaf(node, indent);
return;
}
IReadOnlyList<TNode> children = mGetChildren(node);
string fullKey = buildGroupKey(node);
emitContainerHeader(node, indent, fullKey);
if (children.Count == 0 || !isExpanded(fullKey))
return;
foreach (TNode child in children)
WalkNode(
child, indent + 1,
isVisible, buildGroupKey, isExpanded,
emitLeaf, emitContainerHeader);
}
readonly Func<TNode, NodeKind> mGetKind;
readonly Func<TNode, IReadOnlyList<TNode>> mGetChildren;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: d26996aad4c14674bb5bc7a9b6704930
timeCreated: 1779062400
@@ -0,0 +1,71 @@
using UnityEditor;
using UnityEngine.UIElements;
using Unity.PlasticSCM.Editor.Diff.Asset.Common.Property;
using Unity.PlasticSCM.Editor.UI;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common
{
internal static class PropertyRow
{
internal const float BASE_PADDING_LEFT = 20f;
internal const float INDENT_PX = 16f;
internal const float LABEL_WIDTH = 180f;
internal const float LABEL_MIN_WIDTH = 60f;
internal static bool IsTallProperty(object tag)
{
if (!(tag is LeafPropertyData leaf))
return false;
switch (leaf.PropertyType)
{
case SerializedPropertyType.Rect:
case SerializedPropertyType.RectInt:
case SerializedPropertyType.Bounds:
case SerializedPropertyType.BoundsInt:
return true;
default:
return false;
}
}
internal static VisualElement BuildPanel(out Label nameLabel)
{
VisualElement panel = new VisualElement();
panel.style.flexGrow = 1;
panel.style.flexBasis = 0;
panel.style.flexDirection = FlexDirection.Row;
panel.style.alignItems = Align.FlexStart;
panel.style.paddingLeft = BASE_PADDING_LEFT;
panel.style.paddingRight = 4;
panel.style.paddingTop = 3;
panel.style.paddingBottom = 1;
nameLabel = new Label();
nameLabel.style.width = LABEL_WIDTH;
nameLabel.style.minWidth = LABEL_MIN_WIDTH;
nameLabel.style.fontSize = 12;
nameLabel.style.overflow = Overflow.Hidden;
nameLabel.style.textOverflow = TextOverflow.Ellipsis;
nameLabel.style.color = UnityStyles.Colors.DefaultText;
panel.Add(nameLabel);
return panel;
}
internal static void ConfigureNameLabel(
Label label,
bool hasContent,
bool hasSearch,
string displayLabel,
string tooltipPath)
{
label.enableRichText = hasSearch;
label.text = hasContent ? displayLabel : string.Empty;
label.tooltip = hasContent ? tooltipPath : string.Empty;
label.style.display = hasContent
? DisplayStyle.Flex : DisplayStyle.None;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: fc66293009c443c68b1a22dc6b931e6f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,57 @@
using System;
using System.Text;
using Unity.PlasticSCM.Editor.UI;
using UnityEngine;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common
{
internal static class SearchHighlight
{
internal static string Apply(string text, string searchTerm)
{
if (string.IsNullOrEmpty(searchTerm) || string.IsNullOrEmpty(text))
return text;
int firstIdx = text.IndexOf(
searchTerm, StringComparison.OrdinalIgnoreCase);
if (firstIdx < 0)
return text;
string openTag = GetOpenTag();
int searchLen = searchTerm.Length;
StringBuilder sb = new StringBuilder(
text.Length + openTag.Length + CLOSE_TAG.Length);
int startIdx = 0;
while (startIdx < text.Length)
{
int idx = text.IndexOf(
searchTerm, startIdx, StringComparison.OrdinalIgnoreCase);
if (idx < 0)
{
sb.Append(text, startIdx, text.Length - startIdx);
break;
}
sb.Append(text, startIdx, idx - startIdx);
sb.Append(openTag);
sb.Append(text, idx, searchLen);
sb.Append(CLOSE_TAG);
startIdx = idx + searchLen;
}
return sb.ToString();
}
static string GetOpenTag()
{
string bgHex = ColorUtility.ToHtmlStringRGBA(
UnityStyles.Colors.Diff.AssetDiff.SearchHighlightBackground);
return $"<mark=#{bgHex}>";
}
const string CLOSE_TAG = "</mark>";
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7c604fb7bc9da45fca4bb28b110301ef
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,15 @@
using System;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common
{
internal static class SearchMatcher
{
internal static bool Contains(string text, string search)
{
if (string.IsNullOrEmpty(text))
return false;
return text.IndexOf(
search, StringComparison.OrdinalIgnoreCase) >= 0;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 80c6d1e65404944acb1fa3405e5b9a34
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 4230d3b9af6f940719414ab4bd67a08e
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,134 @@
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common.UnityObject
{
// Sorts top-level items by their natural scene/prefab hierarchy order
// (DFS over scene roots and their children). Without this pass, items
// come out in the unspecified order LoadSerializedFileAndForget returns
// objects in, not the order the user sees in the Unity Hierarchy panel.
// Items whose object is not part of the hierarchy (settings, etc.) land
// at the end, preserving their relative input order.
internal static class HierarchyOrderSorting
{
internal static void SortByHierarchyOrder<T>(
List<T> items,
Func<T, UnityEngine.Object> objectSelector,
params UnityEngine.Object[][] objectArrays)
{
if (items.Count <= 1)
return;
Dictionary<long, int> orderByFileId = BuildHierarchyOrder(objectArrays);
int trailingOrder = orderByFileId.Count;
int n = items.Count;
int[] sortKeys = new int[n];
int[] indices = new int[n];
for (int i = 0; i < n; i++)
{
sortKeys[i] = ResolveSortKey(
objectSelector(items[i]), orderByFileId, trailingOrder);
indices[i] = i;
}
System.Array.Sort(indices, (a, b) =>
{
int cmp = sortKeys[a].CompareTo(sortKeys[b]);
if (cmp != 0)
return cmp;
return a.CompareTo(b);
});
T[] reordered = new T[n];
for (int i = 0; i < n; i++)
reordered[i] = items[indices[i]];
items.Clear();
items.AddRange(reordered);
}
static int ResolveSortKey(
UnityEngine.Object obj,
Dictionary<long, int> orderByFileId,
int trailingOrder)
{
if (obj == null)
return trailingOrder;
long fileId = obj.GetLocalFileId();
if (fileId == 0)
return trailingOrder;
return orderByFileId.TryGetValue(fileId, out int order)
? order
: trailingOrder;
}
static Dictionary<long, int> BuildHierarchyOrder(
UnityEngine.Object[][] objectArrays)
{
Dictionary<long, int> result = new Dictionary<long, int>();
int counter = 0;
foreach (UnityEngine.Object[] objects in objectArrays)
{
foreach (GameObject root in CollectRootGameObjects(objects))
VisitGameObjectDfs(root, result, ref counter);
}
return result;
}
static void VisitGameObjectDfs(
GameObject go,
Dictionary<long, int> result,
ref int counter)
{
if (go == null)
return;
long fileId = go.GetLocalFileId();
if (fileId != 0 && !result.ContainsKey(fileId))
result[fileId] = counter++;
Transform transform = go.transform;
if (transform == null)
return;
int childCount = transform.childCount;
for (int i = 0; i < childCount; i++)
{
Transform child = transform.GetChild(i);
if (child != null)
VisitGameObjectDfs(child.gameObject, result, ref counter);
}
}
static List<GameObject> CollectRootGameObjects(UnityEngine.Object[] objects)
{
UnityEngine.Object sceneRoots = SceneRootsReader.Find(objects);
if (sceneRoots != null)
return SceneRootsReader.ReadRootGameObjects(sceneRoots);
// Prefab (no SceneRoots) — fall back to Transforms with no parent.
List<GameObject> roots = new List<GameObject>();
foreach (UnityEngine.Object obj in objects)
{
if (!(obj is Transform t))
continue;
if (t.parent != null)
continue;
if (t.gameObject == null)
continue;
roots.Add(t.gameObject);
}
return roots;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7e76dfb34c2145fbb3b128aa04febf80
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,59 @@
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common.UnityObject
{
// SceneRoots is an internal Unity type without a public managed wrapper,
// so we identify it structurally by the presence of an `m_Roots` array
// property of object references. Prefabs have no SceneRoots.
internal static class SceneRootsReader
{
internal static UnityEngine.Object Find(UnityEngine.Object[] objects)
{
foreach (UnityEngine.Object obj in objects)
{
if (obj == null)
continue;
if (obj is GameObject || obj is Component)
continue;
using (SerializedObject so = new SerializedObject(obj))
{
SerializedProperty roots = so.FindProperty("m_Roots");
if (roots != null && roots.isArray)
return obj;
}
}
return null;
}
internal static List<GameObject> ReadRootGameObjects(
UnityEngine.Object sceneRootsObj)
{
List<GameObject> result = new List<GameObject>();
using (SerializedObject so = new SerializedObject(sceneRootsObj))
{
SerializedProperty roots = so.FindProperty("m_Roots");
if (roots == null || !roots.isArray)
return result;
for (int i = 0; i < roots.arraySize; i++)
{
SerializedProperty element = roots.GetArrayElementAtIndex(i);
if (element.objectReferenceValue is Transform t
&& t.gameObject != null)
{
result.Add(t.gameObject);
}
}
}
return result;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 36c9ccdf0df04c64a5a41ffbb2a66e8e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: