From 676e98dcb5f1bb7dc2e9b8d6f079d876c6cec4fb Mon Sep 17 00:00:00 2001 From: anatawa12 Date: Thu, 28 Dec 2023 03:20:53 +0900 Subject: [PATCH 01/10] chore: initial integration with NDMF ErrorReprting API --- Editor/APIInternal/ComponentInfos.VRCSDK.cs | 30 +- Editor/AnimatorParsers/AnimationParser.cs | 10 +- Editor/AnimatorParsers/AnimatorParser.cs | 30 +- .../ModificationsContainers.cs | 1 + Editor/AvatarGlobalComponentEditorBase.cs | 6 +- Editor/MergePhysBoneEditor.cs | 29 +- Editor/MergeSkinnedMeshEditor.cs | 7 +- Editor/ObjectMapping/ObjectMappingContext.cs | 68 ++-- Editor/OptimizerPlugin.cs | 91 +++--- .../ClearEndpointPositionProcessor.cs | 6 +- .../EditSkinnedMeshComponentProcessor.cs | 2 +- Editor/Processors/MakeChildrenProcessor.cs | 13 +- Editor/Processors/MergeBoneProcessor.cs | 28 +- Editor/Processors/MergePhysBoneProcessor.cs | 11 +- .../FreezeBlendShapeProcessor.cs | 5 +- .../MergeSkinnedMeshProcessor.cs | 30 +- Editor/Processors/SkinnedMeshes/MeshInfo2.cs | 20 +- .../ComponentDependencyCollector.cs | 4 +- .../TraceAndOptimize/OptimizePhysBone.cs | 24 +- ...usedBonesByReferencesToolEarlyProcessor.cs | 4 +- Internal/ErrorReporter/Editor/BuildReport.cs | 282 +++-------------- .../Editor/BuildReportContext.cs | 45 --- .../Editor/BuildReportContext.cs.meta | 11 - .../Editor/ComponentValidation.cs | 25 +- Internal/ErrorReporter/Editor/ErrorElement.cs | 102 ------ .../ErrorReporter/Editor/ErrorElement.cs.meta | 3 - Internal/ErrorReporter/Editor/ErrorLog.cs | 266 ---------------- .../ErrorReporter/Editor/ErrorLog.cs.meta | 3 - .../ErrorReporter/Editor/ErrorReportUI.cs | 295 ------------------ .../Editor/ErrorReportUI.cs.meta | 3 - .../ErrorReporter/Editor/SelectionButton.cs | 32 -- .../Editor/SelectionButton.cs.meta | 3 - Internal/ErrorReporter/Editor/Utils.cs | 61 ---- Internal/ErrorReporter/Editor/Utils.cs.meta | 3 - .../Runtime/ErrorReporterRuntime.cs | 14 - .../Runtime/ErrorReporterRuntime.cs.meta | 3 - Localization/en.po | 4 +- Localization/ja.po | 4 +- Runtime/AvatarTagComponent.cs | 10 - package.json | 2 +- 40 files changed, 274 insertions(+), 1316 deletions(-) delete mode 100644 Internal/ErrorReporter/Editor/BuildReportContext.cs delete mode 100644 Internal/ErrorReporter/Editor/BuildReportContext.cs.meta delete mode 100644 Internal/ErrorReporter/Editor/ErrorElement.cs delete mode 100644 Internal/ErrorReporter/Editor/ErrorElement.cs.meta delete mode 100644 Internal/ErrorReporter/Editor/ErrorLog.cs delete mode 100644 Internal/ErrorReporter/Editor/ErrorLog.cs.meta delete mode 100644 Internal/ErrorReporter/Editor/ErrorReportUI.cs delete mode 100644 Internal/ErrorReporter/Editor/ErrorReportUI.cs.meta delete mode 100644 Internal/ErrorReporter/Editor/SelectionButton.cs delete mode 100644 Internal/ErrorReporter/Editor/SelectionButton.cs.meta delete mode 100644 Internal/ErrorReporter/Editor/Utils.cs delete mode 100644 Internal/ErrorReporter/Editor/Utils.cs.meta delete mode 100644 Internal/ErrorReporter/Runtime/ErrorReporterRuntime.cs delete mode 100644 Internal/ErrorReporter/Runtime/ErrorReporterRuntime.cs.meta diff --git a/Editor/APIInternal/ComponentInfos.VRCSDK.cs b/Editor/APIInternal/ComponentInfos.VRCSDK.cs index 370d8c0c5..f0218ae10 100644 --- a/Editor/APIInternal/ComponentInfos.VRCSDK.cs +++ b/Editor/APIInternal/ComponentInfos.VRCSDK.cs @@ -62,8 +62,7 @@ protected override void CollectMutations(T component, ComponentMutationsCollecto collector.ModifyProperties(component.VisemeSkinnedMesh, $"blendShape.{component.MouthOpenBlendShapeName}"); } else { - BuildReport.LogWarning("ComponentInfos:VRCAvatarDescriptor:warning:NoVisemeSkinnedMesh") - ?.WithContext(component); + BuildReport.LogWarning("ComponentInfos:VRCAvatarDescriptor:warning:NoVisemeSkinnedMesh", component); } break; } @@ -74,8 +73,7 @@ protected override void CollectMutations(T component, ComponentMutationsCollecto collector.ModifyProperties(component.VisemeSkinnedMesh, component.VisemeBlendShapes.Select(blendShape => $"blendShape.{blendShape}")); } else { - BuildReport.LogWarning("ComponentInfos:VRCAvatarDescriptor:warning:NoVisemeSkinnedMesh") - ?.WithContext(component); + BuildReport.LogWarning("ComponentInfos:VRCAvatarDescriptor:warning:NoVisemeSkinnedMesh", component); } break; } @@ -84,8 +82,8 @@ protected override void CollectMutations(T component, ComponentMutationsCollecto break; default: BuildReport.LogWarning("ComponentInfos:VRCAvatarDescriptor:warning:UnknownLipSyncStyle", - component.lipSync.ToString()) - ?.WithContext(component); + component.lipSync.ToString(), + component); break; } } @@ -130,7 +128,7 @@ protected override void ApplySpecialMapping(T component, MappingSource mappingSo removed = true; } if (removed) - BuildReport.LogFatal("ApplyObjectMapping:VRCAvatarDescriptor:viseme BlendShape Removed"); + BuildReport.LogError("ApplyObjectMapping:VRCAvatarDescriptor:viseme BlendShape Removed"); break; } case VRC_AvatarDescriptor.LipSyncStyle.VisemeParameterOnly: @@ -183,8 +181,8 @@ void AddCollider(VRCAvatarDescriptor.ColliderConfig collider, string where) break; default: BuildReport.LogWarning("ComponentInfos:VRCAvatarDescriptor:warning:UnknownColliderState", - collider.ToString(), where) - ?.WithContext(component); + collider.ToString(), where, + component); break; } } @@ -234,21 +232,21 @@ from index in component.customEyeLookSettings.eyelidsBlendshapes } else { - BuildReport.LogWarning("ComponentInfos:VRCAvatarDescriptor:warning:NoMeshInEyelidsSkinnedMesh") - ?.WithContext(component); + BuildReport.LogWarning("ComponentInfos:VRCAvatarDescriptor:warning:NoMeshInEyelidsSkinnedMesh", + component); } } else { - BuildReport.LogWarning("ComponentInfos:VRCAvatarDescriptor:warning:NoEyelidsSkinnedMesh") - ?.WithContext(component); + BuildReport.LogWarning("ComponentInfos:VRCAvatarDescriptor:warning:NoEyelidsSkinnedMesh", + component); } } break; default: BuildReport.LogWarning("ComponentInfos:VRCAvatarDescriptor:warning:UnknownEyelidType", - component.customEyeLookSettings.eyelidType.ToString()) - ?.WithContext(component); + component.customEyeLookSettings.eyelidType.ToString(), + component); break; } } @@ -282,7 +280,7 @@ protected override void ApplySpecialMapping(VRCAvatarDescriptor component, Mappi } if (removed) - BuildReport.LogFatal("ApplyObjectMapping:VRCAvatarDescriptor:eyelids BlendShape Removed"); + BuildReport.LogError("ApplyObjectMapping:VRCAvatarDescriptor:eyelids BlendShape Removed"); } break; default: diff --git a/Editor/AnimatorParsers/AnimationParser.cs b/Editor/AnimatorParsers/AnimationParser.cs index 6487cbbc1..c3c02da42 100644 --- a/Editor/AnimatorParsers/AnimationParser.cs +++ b/Editor/AnimatorParsers/AnimationParser.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; +using nadena.dev.ndmf; using UnityEditor; using UnityEditor.Animations; using UnityEngine; @@ -12,8 +13,11 @@ namespace Anatawa12.AvatarOptimizer.AnimatorParsers class AnimationParser { internal IModificationsContainer ParseMotion(GameObject root, Motion motion, - IReadOnlyDictionary mapping) => - ReportingObject(motion, () => ParseMotionInner(root, motion, mapping)); + IReadOnlyDictionary mapping) + { + using (ErrorReport.WithContextObject(motion)) + return ParseMotionInner(root, motion, mapping); + } private IModificationsContainer ParseMotionInner(GameObject root, Motion motion, IReadOnlyDictionary mapping) @@ -27,7 +31,7 @@ private IModificationsContainer ParseMotionInner(GameObject root, Motion motion, case BlendTree blendTree: return ParseBlendTree(root, blendTree, mapping); default: - LogFatal("Unknown Motion Type: {0} in motion {1}", motion.GetType().Name, motion.name); + LogError("Unknown Motion Type: {0} in motion {1}", motion.GetType().Name, motion.name); return ImmutableModificationsContainer.Empty; } } diff --git a/Editor/AnimatorParsers/AnimatorParser.cs b/Editor/AnimatorParsers/AnimatorParser.cs index ffd778f20..5b55d1490 100644 --- a/Editor/AnimatorParsers/AnimatorParser.cs +++ b/Editor/AnimatorParsers/AnimatorParser.cs @@ -150,12 +150,16 @@ public override void ModifyProperties(Component component, IEnumerable p private static void OtherMutateComponents(ModificationsContainer mod, BuildContext context) { var collector = new Collector(mod); - ReportingObjects(context.GetComponents(), component => + foreach (var component in context.GetComponents()) { - collector.Modifier = new ComponentAnimationSource(component); - if (ComponentInfoRegistry.TryGetInformation(component.GetType(), out var info)) - info.CollectMutationsInternal(component, collector); - }); + using (ErrorReport.WithContextObject(component)) + { + collector.Modifier = new ComponentAnimationSource(component); + if (ComponentInfoRegistry.TryGetInformation(component.GetType(), out var info)) + info.CollectMutationsInternal(component, collector); + + } + } } #endregion @@ -273,7 +277,7 @@ private void CollectWeightChangesInController(RuntimeAnimatorController runtimeC AnimatorLayerMap playableWeightChanged, AnimatorLayerMap> animatorLayerWeightChanged) { - ReportingObject(runtimeController, () => + using (ErrorReport.WithContextObject(runtimeController)) { var (controller, _) = GetControllerAndOverrides(runtimeController); @@ -287,7 +291,7 @@ private void CollectWeightChangesInController(RuntimeAnimatorController runtimeC .stateMachine)) CollectWeightChangesInBehaviors(layer.GetOverrideBehaviours(state)); } - }); + } return; @@ -316,8 +320,8 @@ void CollectWeightChangesInBehaviors(StateMachineBehaviour[] stateBehaviours) break; default: LogWarning("AnimatorParser:PlayableLayerControl:UnknownBlendablePlayableLayer", - $"{playableLayerControl.layer}") - ?.WithContext(stateMachineBehaviour); + $"{playableLayerControl.layer}", + stateMachineBehaviour); continue; } @@ -345,8 +349,8 @@ void CollectWeightChangesInBehaviors(StateMachineBehaviour[] stateBehaviours) break; default: LogWarning("AnimatorParser:AnimatorLayerControl:UnknownBlendablePlayableLayer", - $"{animatorLayerControl.layer}") - ?.WithContext(stateMachineBehaviour); + $"{animatorLayerControl.layer}", + stateMachineBehaviour); continue; } @@ -439,12 +443,12 @@ private IModificationsContainer AddHumanoidModifications(IModificationsContainer public IModificationsContainer ParseAnimatorController(GameObject root, RuntimeAnimatorController controller, [CanBeNull] AnimatorLayerWeightMap externallyWeightChanged = null) { - return ReportingObject(controller, () => + using (ErrorReport.WithContextObject(controller)) { var (animatorController, mapping) = GetControllerAndOverrides(controller); return AdvancedParseAnimatorController(root, animatorController, mapping, externallyWeightChanged); - }); + } } internal IModificationsContainer AdvancedParseAnimatorController(GameObject root, AnimatorController controller, diff --git a/Editor/AnimatorParsers/ModificationsContainers.cs b/Editor/AnimatorParsers/ModificationsContainers.cs index 1b00ab3df..826d7c367 100644 --- a/Editor/AnimatorParsers/ModificationsContainers.cs +++ b/Editor/AnimatorParsers/ModificationsContainers.cs @@ -308,6 +308,7 @@ public bool IsConst private readonly IModificationSource[] _sources; public ReadOnlySpan Sources => _sources ?? Array.Empty(); + public IEnumerable SourcesEnum => _sources ?? Array.Empty(); private AnimationFloatProperty(PropertyState state, float constValue, params IModificationSource[] modifiers) => (State, _constValue, _sources) = (state, constValue, modifiers); diff --git a/Editor/AvatarGlobalComponentEditorBase.cs b/Editor/AvatarGlobalComponentEditorBase.cs index 75208ca58..9698c91fb 100644 --- a/Editor/AvatarGlobalComponentEditorBase.cs +++ b/Editor/AvatarGlobalComponentEditorBase.cs @@ -4,6 +4,7 @@ using UnityEngine; #if AAO_VRCSDK3_AVATARS +using nadena.dev.ndmf; using VRC.Core; using VRC.SDK3.Avatars.Components; #endif @@ -18,12 +19,11 @@ static AvatarGlobalComponentEditorBase() { #if AAO_VRCSDK3_AVATARS if (!component.GetComponent()) - return new[] { ErrorLog.Validation("AvatarGlobalComponent:NotOnAvatarDescriptor") }; + BuildReport.LogError("AvatarGlobalComponent:NotOnAvatarDescriptor"); #else if (!nadena.dev.ndmf.runtime.RuntimeUtil.IsAvatarRoot(component.transform)) - return new[] { ErrorLog.Validation("AvatarGlobalComponent:NotOnAvatarRoot") }; + BuildReport.LogError("AvatarGlobalComponent:NotOnAvatarDescriptor"); #endif - return null; }); } protected override void OnInspectorGUIInner() diff --git a/Editor/MergePhysBoneEditor.cs b/Editor/MergePhysBoneEditor.cs index 7c03e833a..82709f30c 100644 --- a/Editor/MergePhysBoneEditor.cs +++ b/Editor/MergePhysBoneEditor.cs @@ -549,7 +549,6 @@ private static int PopupNoIndent(Rect position, int selectedIndex, string[] disp [InitializeOnLoad] sealed class MergePhysBoneValidator : MergePhysBoneEditorModificationUtils { - private readonly List _errorLogs; private readonly List _differProps = new List(); private readonly MergePhysBone _mergePhysBone; @@ -558,23 +557,16 @@ static MergePhysBoneValidator() ComponentValidation.RegisterValidator(Validate); } - private static List Validate(MergePhysBone mergePhysBone) + private static void Validate(MergePhysBone mergePhysBone) { - var list = new List(); if (mergePhysBone.makeParent && mergePhysBone.transform.childCount != 0) - list.Add(ErrorLog.Validation("MergePhysBone:error:makeParentWithChildren").WithContext(mergePhysBone)); + BuildReport.LogError("MergePhysBone:error:makeParentWithChildren", mergePhysBone); - new MergePhysBoneValidator(list, mergePhysBone).DoProcess(); - - return list; + new MergePhysBoneValidator(mergePhysBone).DoProcess(); } - public MergePhysBoneValidator(List errorLogs, MergePhysBone mergePhysBone) - : base(new SerializedObject(mergePhysBone)) - { - _errorLogs = errorLogs; + public MergePhysBoneValidator(MergePhysBone mergePhysBone) : base(new SerializedObject(mergePhysBone)) => _mergePhysBone = mergePhysBone; - } private static void Void() { @@ -586,13 +578,11 @@ private static void Void() protected override void EndPbConfig() { if (_differProps.Count != 0) { - _errorLogs.Add(ErrorLog.Validation("MergePhysBone:error:differValues", - string.Join(", ", _differProps))); + BuildReport.LogError("MergePhysBone:error:differValues", string.Join(", ", _differProps)); } } - protected override void NoSource() => - _errorLogs.Add(ErrorLog.Validation("MergePhysBone:error:noSources")); + protected override void NoSource() => BuildReport.LogError("MergePhysBone:error:noSources"); protected override void TransformSection() { @@ -603,7 +593,7 @@ protected override void TransformSection() .ZipWithNext() .Any(x => x.Item1 != x.Item2); if (differ) - _errorLogs.Add(ErrorLog.Validation("MergePhysBone:error:parentDiffer")); + BuildReport.LogError("MergePhysBone:error:parentDiffer"); } if (EndpointPosition.OverrideProperty.enumValueIndex == @@ -615,14 +605,13 @@ protected override void TransformSection() var multiChildType = GetSourceProperty(nameof(VRCPhysBoneBase.multiChildType)); if (multiChildType.enumValueIndex != 0 || multiChildType.hasMultipleDifferentValues) - _errorLogs.Add(ErrorLog.Validation("MergePhysBone:error:multiChildType")); + BuildReport.LogError("MergePhysBone:error:multiChildType"); } protected override void OptionParameter() => Void(); protected override void OptionIsAnimated() => Void(); - protected override void UnsupportedPbVersion() => - _errorLogs.Add(ErrorLog.Validation("MergePhysBone:error:unsupportedPbVersion")); + protected override void UnsupportedPbVersion() => BuildReport.LogError("MergePhysBone:error:unsupportedPbVersion"); protected override void PbVersionProp(string label, ValueConfigProp prop, bool forceOverride = false) => PbProp(label, prop, forceOverride); diff --git a/Editor/MergeSkinnedMeshEditor.cs b/Editor/MergeSkinnedMeshEditor.cs index 975278e54..b60aea0c9 100644 --- a/Editor/MergeSkinnedMeshEditor.cs +++ b/Editor/MergeSkinnedMeshEditor.cs @@ -30,15 +30,12 @@ static MergeSkinnedMeshEditor() { ComponentValidation.RegisterValidator(component => { - var err = new ErrorLog[2]; var smr = component.GetComponent(); if (smr.sharedMesh) - err[0] = ErrorLog.Warning("MergeSkinnedMesh:warning:MeshIsNotNone"); + BuildReport.LogWarning("MergeSkinnedMesh:warning:MeshIsNotNone"); if (component.renderersSet.GetAsSet().Contains(smr)) - err[1] = ErrorLog.Validation("MergeSkinnedMesh:validation:self-recursive"); - - return err; + BuildReport.LogError("MergeSkinnedMesh:validation:self-recursive"); }); } diff --git a/Editor/ObjectMapping/ObjectMappingContext.cs b/Editor/ObjectMapping/ObjectMappingContext.cs index 89f809b2e..75b516ffe 100644 --- a/Editor/ObjectMapping/ObjectMappingContext.cs +++ b/Editor/ObjectMapping/ObjectMappingContext.cs @@ -28,46 +28,49 @@ public void OnDeactivate(BuildContext context) var mappingSource = new MappingSourceImpl(mapping); // replace all objects - BuildReport.ReportingObjects(context.GetComponents(), component => + foreach (var component in context.GetComponents()) { - if (component is Transform) return; - - // apply special mapping - if (ComponentInfoRegistry.TryGetInformation(component.GetType(), out var info)) - info.ApplySpecialMappingInternal(component, mappingSource); + using (ErrorReport.WithContextObject(component)) + { + if (component is Transform) return; - var serialized = new SerializedObject(component); - AnimatorControllerMapper mapper = null; + // apply special mapping + if (ComponentInfoRegistry.TryGetInformation(component.GetType(), out var info)) + info.ApplySpecialMappingInternal(component, mappingSource); - foreach (var p in serialized.ObjectReferenceProperties()) - { - if (mapping.MapComponentInstance(p.objectReferenceInstanceIDValue, out var mappedComponent)) - p.objectReferenceValue = mappedComponent; + var serialized = new SerializedObject(component); + AnimatorControllerMapper mapper = null; - var objectReferenceValue = p.objectReferenceValue; - switch (objectReferenceValue) + foreach (var p in serialized.ObjectReferenceProperties()) { - case RuntimeAnimatorController _: + if (mapping.MapComponentInstance(p.objectReferenceInstanceIDValue, out var mappedComponent)) + p.objectReferenceValue = mappedComponent; + + var objectReferenceValue = p.objectReferenceValue; + switch (objectReferenceValue) + { + case RuntimeAnimatorController _: #if AAO_VRM0 - case VRM.BlendShapeAvatar _: + case VRM.BlendShapeAvatar _: #endif #if AAO_VRM1 - case UniVRM10.VRM10Object _: + case UniVRM10.VRM10Object _: #endif - if (mapper == null) - mapper = new AnimatorControllerMapper(mapping.CreateAnimationMapper(component.gameObject)); - - // ReSharper disable once AccessToModifiedClosure - var mapped = BuildReport.ReportingObject(objectReferenceValue, - () => mapper.MapObject(objectReferenceValue)); - if (mapped != objectReferenceValue) - p.objectReferenceValue = mapped; - break; + if (mapper == null) + mapper = new AnimatorControllerMapper( + mapping.CreateAnimationMapper(component.gameObject)); + + // ReSharper disable once AccessToModifiedClosure + var mapped = mapper.MapObject(objectReferenceValue); + if (mapped != objectReferenceValue) + p.objectReferenceValue = mapped; + break; + } } - } - serialized.ApplyModifiedPropertiesWithoutUndo(); - }); + serialized.ApplyModifiedPropertiesWithoutUndo(); + } + } } } @@ -148,8 +151,11 @@ public AnimatorControllerMapper(AnimationObjectMapper mapping) public T MapAnimatorController(T controller) where T : RuntimeAnimatorController => DeepClone(controller, CustomClone); - public T MapObject(T obj) where T : Object => - DeepClone(obj, CustomClone); + public T MapObject(T obj) where T : Object + { + using (ErrorReport.WithContextObject(obj)) + return DeepClone(obj, CustomClone); + } // https://github.com/bdunderscore/modular-avatar/blob/db49e2e210bc070671af963ff89df853ae4514a5/Packages/nadena.dev.modular-avatar/Editor/AnimatorMerger.cs#L199-L241 // Originally under MIT License diff --git a/Editor/OptimizerPlugin.cs b/Editor/OptimizerPlugin.cs index 5f7ea9d03..08897e740 100644 --- a/Editor/OptimizerPlugin.cs +++ b/Editor/OptimizerPlugin.cs @@ -10,7 +10,7 @@ namespace Anatawa12.AvatarOptimizer.ndmf { internal class OptimizerPlugin : Plugin { - public override string DisplayName => "Anatawa12's Avatar Optimizer"; + public override string DisplayName => "Avatar Optimizer"; public override string QualifiedName => "com.anatawa12.avatar-optimizer"; @@ -18,70 +18,63 @@ protected override void Configure() { // Run early steps before EditorOnly objects are purged InPhase(BuildPhase.Resolving) - .WithRequiredExtensions(new [] {typeof(BuildReportContext)}, seq => + .Run("Info if AAO is Out of Date", ctx => { - seq.Run("Info if AAO is Out of Date", ctx => - { - // we skip check for update - var components = ctx.AvatarRootObject.GetComponentInChildren(true); - if (components && CheckForUpdate.OutOfDate) - BuildReport.LogInfo("CheckForUpdate:out-of-date", - CheckForUpdate.LatestVersionName, CheckForUpdate.CurrentVersionName); - }) - .Then.Run(Processors.UnusedBonesByReferencesToolEarlyProcessor.Instance) - .Then.Run("Early: MakeChildren", - ctx => new Processors.MakeChildrenProcessor(early: true).Process(ctx) - ) - .BeforePass(RemoveEditorOnlyPass.Instance); - }); - InPhase(BuildPhase.Resolving) - .WithRequiredExtensions(new [] {typeof(BuildReportContext)}, seq => - { - seq.Run(Processors.FetchOriginalStatePass.Instance); - }); + // we skip check for update + var components = ctx.AvatarRootObject.GetComponentInChildren(true); + if (components && CheckForUpdate.OutOfDate) + BuildReport.LogInfo("CheckForUpdate:out-of-date", + CheckForUpdate.LatestVersionName, CheckForUpdate.CurrentVersionName); + }) + .Then.Run(Processors.UnusedBonesByReferencesToolEarlyProcessor.Instance) + .Then.Run("Early: MakeChildren", + ctx => new Processors.MakeChildrenProcessor(early: true).Process(ctx) + ) + .BeforePass(RemoveEditorOnlyPass.Instance); + + InPhase(BuildPhase.Resolving).Run(Processors.FetchOriginalStatePass.Instance); + ; // Run everything else in the optimize phase InPhase(BuildPhase.Optimizing) - .WithRequiredExtension(typeof(BuildReportContext), seq => + .WithRequiredExtensions(new[] { - seq.Run("EmptyPass for Context Ordering", _ => {}); - seq.WithRequiredExtensions(new[] - { - typeof(Processors.MeshInfo2Context), - typeof(ObjectMappingContext), - }, _ => - { - seq.Run("Check if AAO is active", ctx => + typeof(Processors.MeshInfo2Context), + typeof(ObjectMappingContext), + }, seq => + { + seq.Run("Check if AAO is active", + ctx => { - ctx.GetState().Enabled = ctx.AvatarRootObject.GetComponent(); + ctx.GetState().Enabled = + ctx.AvatarRootObject.GetComponent(); }) - .Then.Run(Processors.TraceAndOptimizes.LoadTraceAndOptimizeConfiguration.Instance) - .Then.Run(Processors.ParseAnimator.Instance) - .Then.Run(Processors.TraceAndOptimizes.AutoFreezeBlendShape.Instance) + .Then.Run("Validation", (ctx) => ComponentValidation.ValidateAll(ctx.AvatarRootObject)) + .Then.Run(Processors.TraceAndOptimizes.LoadTraceAndOptimizeConfiguration.Instance) + .Then.Run(Processors.ParseAnimator.Instance) + .Then.Run(Processors.TraceAndOptimizes.AutoFreezeBlendShape.Instance) #if AAO_VRCSDK3_AVATARS - .Then.Run(Processors.ClearEndpointPositionProcessor.Instance) - .Then.Run(Processors.MergePhysBoneProcessor.Instance) + .Then.Run(Processors.ClearEndpointPositionProcessor.Instance) + .Then.Run(Processors.MergePhysBoneProcessor.Instance) #endif - .Then.Run(Processors.EditSkinnedMeshComponentProcessor.Instance) - .Then.Run("MakeChildrenProcessor", - ctx => new Processors.MakeChildrenProcessor(early: false).Process(ctx) - ) + .Then.Run(Processors.EditSkinnedMeshComponentProcessor.Instance) + .Then.Run("MakeChildrenProcessor", + ctx => new Processors.MakeChildrenProcessor(early: false).Process(ctx) + ) #if AAO_VRCSDK3_AVATARS - .Then.Run(Processors.TraceAndOptimizes.OptimizePhysBone.Instance) + .Then.Run(Processors.TraceAndOptimizes.OptimizePhysBone.Instance) #endif - .Then.Run(Processors.TraceAndOptimizes.FindUnusedObjects.Instance) - .Then.Run(Processors.TraceAndOptimizes.ConfigureRemoveZeroSizedPolygon.Instance) - .Then.Run(Processors.MergeBoneProcessor.Instance) - .Then.Run(Processors.RemoveZeroSizedPolygonProcessor.Instance) - ; - }); - seq.Run("EmptyPass for Context Ordering", _ => {}); + .Then.Run(Processors.TraceAndOptimizes.FindUnusedObjects.Instance) + .Then.Run(Processors.TraceAndOptimizes.ConfigureRemoveZeroSizedPolygon.Instance) + .Then.Run(Processors.MergeBoneProcessor.Instance) + .Then.Run(Processors.RemoveZeroSizedPolygonProcessor.Instance) + ; }); } protected override void OnUnhandledException(Exception e) { - BuildReport.ReportInternalError(e); + ErrorReport.ReportException(e); } } diff --git a/Editor/Processors/ClearEndpointPositionProcessor.cs b/Editor/Processors/ClearEndpointPositionProcessor.cs index a4c150095..d7872a1b1 100644 --- a/Editor/Processors/ClearEndpointPositionProcessor.cs +++ b/Editor/Processors/ClearEndpointPositionProcessor.cs @@ -15,8 +15,10 @@ internal class ClearEndpointPositionProcessor : Pass(), - component => BuildReport.ReportingObjects(component.GetComponents(), Process)); + foreach (var component in context.GetComponents()) + foreach (var vrcPhysBoneBase in component.GetComponents()) + using (ErrorReport.WithContextObject(vrcPhysBoneBase)) + Process(vrcPhysBoneBase); } public static void Process(VRCPhysBoneBase pb) diff --git a/Editor/Processors/EditSkinnedMeshComponentProcessor.cs b/Editor/Processors/EditSkinnedMeshComponentProcessor.cs index 18cc3626b..903af198c 100644 --- a/Editor/Processors/EditSkinnedMeshComponentProcessor.cs +++ b/Editor/Processors/EditSkinnedMeshComponentProcessor.cs @@ -28,7 +28,7 @@ protected override void Execute(BuildContext context) foreach (var processor in processors.GetSorted()) { Profiler.BeginSample($"{processor.GetType().Name}: {processors.Target.name}"); - BuildReport.ReportingObject(processor.Component, () => processor.Process(context, target)); + using (ErrorReport.WithContextObject(processor.Component)) processor.Process(context, target); target.AssertInvariantContract( $"after {processor.GetType().Name} " + $"for {processor.Target.gameObject.name}"); diff --git a/Editor/Processors/MakeChildrenProcessor.cs b/Editor/Processors/MakeChildrenProcessor.cs index 349eed6b1..c0405afb2 100644 --- a/Editor/Processors/MakeChildrenProcessor.cs +++ b/Editor/Processors/MakeChildrenProcessor.cs @@ -16,15 +16,16 @@ public MakeChildrenProcessor(bool early) public void Process(BuildContext context) { - BuildReport.ReportingObjects(context.GetComponents(), makeChildren => + foreach (var makeChildren in context.GetComponents()) { - if (makeChildren.executeEarly != _early) return; - foreach (var makeChildrenChild in makeChildren.children.GetAsSet().Where(x => x)) + using (ErrorReport.WithContextObject(makeChildren)) { - makeChildrenChild.parent = makeChildren.transform; + if (makeChildren.executeEarly != _early) continue; + foreach (var makeChildrenChild in makeChildren.children.GetAsSet().Where(x => x)) + makeChildrenChild.parent = makeChildren.transform; + Object.DestroyImmediate(makeChildren); } - Object.DestroyImmediate(makeChildren); - }); + } } } } diff --git a/Editor/Processors/MergeBoneProcessor.cs b/Editor/Processors/MergeBoneProcessor.cs index 5d307974e..8dbca4f5c 100644 --- a/Editor/Processors/MergeBoneProcessor.cs +++ b/Editor/Processors/MergeBoneProcessor.cs @@ -20,27 +20,22 @@ private static void RegisterValidator() { ComponentValidation.RegisterValidator(mergeBone => { - var errors = new ErrorLog[2]; - // TODO: use AvatarRoot API if (mergeBone.GetComponent()) { - errors[0] = ErrorLog.Validation("MergeBone:validation:onAvatarRoot"); - return errors; + BuildReport.LogError("MergeBone:validation:onAvatarRoot"); } if (mergeBone.GetComponents().Except(new Component[] { mergeBone, mergeBone.transform }) .Any()) - errors[0] = ErrorLog.Warning("MergeBone:validation:thereAreComponent"); + BuildReport.LogWarning("MergeBone:validation:thereAreComponent"); if (AnyNotMergedBone(mergeBone.transform)) { // if the bone has non-merged bones, uneven scaling is not supported. if (!ScaledEvenly(mergeBone.transform.localScale)) - errors[1] = ErrorLog.Warning("MergeBone:validation:unevenScaling"); + BuildReport.LogWarning("MergeBone:validation:unevenScaling"); } - - return errors; }); bool AnyNotMergedBone(Transform bone) @@ -78,14 +73,19 @@ protected override void Execute(BuildContext context) if (mergeMapping.Count == 0) return; - BuildReport.ReportingObjects(context.GetComponents(), MapIgnoreTransforms); + foreach (var physBone in context.GetComponents()) + using (ErrorReport.WithContextObject(physBone)) + MapIgnoreTransforms(physBone); - BuildReport.ReportingObjects(context.GetComponents(), renderer => + foreach (var renderer in context.GetComponents()) { - var meshInfo2 = context.GetMeshInfoFor(renderer); - if (meshInfo2.Bones.Any(x => x.Transform && mergeMapping.ContainsKey(x.Transform))) - DoBoneMap2(meshInfo2, mergeMapping); - }); + using (ErrorReport.WithContextObject(renderer)) + { + var meshInfo2 = context.GetMeshInfoFor(renderer); + if (meshInfo2.Bones.Any(x => x.Transform && mergeMapping.ContainsKey(x.Transform))) + DoBoneMap2(meshInfo2, mergeMapping); + } + } var counter = 0; diff --git a/Editor/Processors/MergePhysBoneProcessor.cs b/Editor/Processors/MergePhysBoneProcessor.cs index 1b8c74157..c71afb646 100644 --- a/Editor/Processors/MergePhysBoneProcessor.cs +++ b/Editor/Processors/MergePhysBoneProcessor.cs @@ -19,11 +19,14 @@ internal class MergePhysBoneProcessor : Pass protected override void Execute(BuildContext context) { - BuildReport.ReportingObjects(context.GetComponents(), mergePhysBone => + foreach (var mergePhysBone in context.GetComponents()) { - DoMerge(mergePhysBone); - Object.DestroyImmediate(mergePhysBone); - }); + using (ErrorReport.WithContextObject(mergePhysBone)) + { + DoMerge(mergePhysBone); + Object.DestroyImmediate(mergePhysBone); + } + } } private static bool SetEq(IEnumerable a, IEnumerable b) => diff --git a/Editor/Processors/SkinnedMeshes/FreezeBlendShapeProcessor.cs b/Editor/Processors/SkinnedMeshes/FreezeBlendShapeProcessor.cs index 552bcd9de..a3d7adc59 100644 --- a/Editor/Processors/SkinnedMeshes/FreezeBlendShapeProcessor.cs +++ b/Editor/Processors/SkinnedMeshes/FreezeBlendShapeProcessor.cs @@ -54,9 +54,8 @@ public static void FreezeBlendShapes( if (modified.Count != 0) { // ReSharper disable once CoVariantArrayConversion - BuildReport.LogWarning("FreezeBlendShape:warning:animation", string.Join(", ", modified)) - ?.WithContext(targetSMR) - ?.WithContext(sources); + BuildReport.LogWarning("FreezeBlendShape:warning:animation", string.Join(", ", modified), + targetSMR, sources); } } diff --git a/Editor/Processors/SkinnedMeshes/MergeSkinnedMeshProcessor.cs b/Editor/Processors/SkinnedMeshes/MergeSkinnedMeshProcessor.cs index 1896efa2d..313df6a3e 100644 --- a/Editor/Processors/SkinnedMeshes/MergeSkinnedMeshProcessor.cs +++ b/Editor/Processors/SkinnedMeshes/MergeSkinnedMeshProcessor.cs @@ -92,12 +92,10 @@ bool RendererEnabled(Renderer x) { // collect (skinned) mesh renderers who doesn't have normal // to show the list on the error reporting - BuildReport.LogFatal("MergeSkinnedMesh:error:mix-normal-existence") - ?.WithContext(( - from meshInfo2 in meshInfos - where meshInfo2.Vertices.Count != 0 && !meshInfo2.HasNormals - select (object)meshInfo2.SourceRenderer - ).ToArray()); + BuildReport.LogError("MergeSkinnedMesh:error:mix-normal-existence", + from meshInfo2 in meshInfos + where meshInfo2.Vertices.Count != 0 && !meshInfo2.HasNormals + select meshInfo2.SourceRenderer); } Profiler.EndSample(); @@ -237,8 +235,7 @@ TexCoordStatus TexCoordStatusMax(TexCoordStatus x, TexCoordStatus y) => var toDestroy = renderer.GetComponent(); if (toDestroy) { - BuildReport.LogWarning("MergeSkinnedMesh:warning:removeZeroSizedPolygonOnSources") - ?.WithContext(toDestroy); + BuildReport.LogWarning("MergeSkinnedMesh:warning:removeZeroSizedPolygonOnSources", toDestroy); Object.DestroyImmediate(toDestroy); } Object.DestroyImmediate(renderer); @@ -285,15 +282,14 @@ TexCoordStatus TexCoordStatusMax(TexCoordStatus x, TexCoordStatus y) => private void ActivenessAnimationWarning(Renderer renderer, BuildContext context, HashSet parents) { - ErrorLog log = null; + var sources = new List(); // Warn if the source mesh can be hidden differently than merged by animation. { if (context.GetAnimationComponent(renderer).TryGetFloat("m_Enabled", out var p)) { - log = log ?? BuildReport.LogWarning("MergeSkinnedMesh:warning:animation-mesh-hide") - ?.WithContext(renderer); - log?.WithContext(p.Sources); + sources.Add(renderer); + sources.Add(p.SourcesEnum); } } foreach (var transform in renderer.transform.ParentEnumerable(context.AvatarRootTransform, includeMe: true)) @@ -301,12 +297,14 @@ private void ActivenessAnimationWarning(Renderer renderer, BuildContext context, if (parents.Contains(transform)) break; if (context.GetAnimationComponent(transform.gameObject).TryGetFloat("m_IsActive", out var p)) { - log = log ?? BuildReport.LogWarning("MergeSkinnedMesh:warning:animation-mesh-hide") - ?.WithContext(renderer); - log?.WithContext(transform.gameObject); - log?.WithContext(p.Sources); + sources.Add(renderer); + sources.Add(transform.gameObject); + sources.Add(p.SourcesEnum); } } + + if (sources.Count != 0) + BuildReport.LogWarning("MergeSkinnedMesh:warning:animation-mesh-hide", sources); } private (int[][] mapping, List<(MeshTopology topology, Material material)> materials) diff --git a/Editor/Processors/SkinnedMeshes/MeshInfo2.cs b/Editor/Processors/SkinnedMeshes/MeshInfo2.cs index 2a4700f91..a8cd9eafd 100644 --- a/Editor/Processors/SkinnedMeshes/MeshInfo2.cs +++ b/Editor/Processors/SkinnedMeshes/MeshInfo2.cs @@ -5,6 +5,7 @@ using System.Linq; using Anatawa12.AvatarOptimizer.ErrorReporting; using JetBrains.Annotations; +using nadena.dev.ndmf; using Unity.Burst; using Unity.Collections; using Unity.Jobs; @@ -42,7 +43,7 @@ public MeshInfo2(SkinnedMeshRenderer renderer) SourceRenderer = renderer; var mesh = renderer.sharedMesh; - BuildReport.ReportingObject(renderer, true, () => + using (ErrorReport.WithContextObject(renderer)) { if (mesh) ReadSkinnedMesh(mesh); @@ -64,13 +65,13 @@ public MeshInfo2(SkinnedMeshRenderer renderer) RemoveUnusedBones(); AssertInvariantContract("SkinnedMeshRenderer"); - }); + } } public MeshInfo2(MeshRenderer renderer) { SourceRenderer = renderer; - BuildReport.ReportingObject(renderer, true, () => + using (ErrorReport.WithContextObject(renderer)) { var meshFilter = renderer.GetComponent(); var mesh = meshFilter ? meshFilter.sharedMesh : null; @@ -84,7 +85,7 @@ public MeshInfo2(MeshRenderer renderer) SetMaterials(renderer); AssertInvariantContract("MeshRenderer"); - }); + } } private void SetMaterials(Renderer renderer) @@ -419,8 +420,7 @@ public void FlattenMultiPassRendering(string reasonComponent) { if (SubMeshes.All(x => x.SharedMaterials.Length == 1)) return; - BuildReport.LogWarning("MeshInfo2:warning:multiPassRendering", reasonComponent) - ?.WithContext(SourceRenderer); + BuildReport.LogWarning("MeshInfo2:warning:multiPassRendering", reasonComponent, SourceRenderer); // flatten SubMeshes var subMeshes = SubMeshes.ToArray(); @@ -648,7 +648,7 @@ public void WriteToMesh(Mesh destMesh) public void WriteToSkinnedMeshRenderer(SkinnedMeshRenderer targetRenderer) { - BuildReport.ReportingObject(targetRenderer, () => + using (ErrorReport.WithContextObject(targetRenderer)) { var mesh = new Mesh { name = $"AAOGeneratedMesh{targetRenderer.name}" }; @@ -670,19 +670,19 @@ public void WriteToSkinnedMeshRenderer(SkinnedMeshRenderer targetRenderer) if (Bounds != default) targetRenderer.localBounds = Bounds; targetRenderer.updateWhenOffscreen = offscreen; - }); + } } public void WriteToMeshRenderer(MeshRenderer targetRenderer) { - BuildReport.ReportingObject(targetRenderer, () => + using (ErrorReport.WithContextObject(targetRenderer)) { var mesh = new Mesh { name = $"AAOGeneratedMesh{targetRenderer.name}" }; var meshFilter = targetRenderer.GetComponent(); WriteToMesh(mesh); meshFilter.sharedMesh = mesh; targetRenderer.sharedMaterials = SubMeshes.SelectMany(x => x.SharedMaterials).ToArray(); - }); + } } } diff --git a/Editor/Processors/TraceAndOptimize/ComponentDependencyCollector.cs b/Editor/Processors/TraceAndOptimize/ComponentDependencyCollector.cs index c28e72925..46d5db567 100644 --- a/Editor/Processors/TraceAndOptimize/ComponentDependencyCollector.cs +++ b/Editor/Processors/TraceAndOptimize/ComponentDependencyCollector.cs @@ -34,7 +34,7 @@ public void CollectAllUsages() foreach (var componentInfo in _componentInfos.AllInformation) { var component = componentInfo.Component; - BuildReport.ReportingObject(component, () => + using (ErrorReport.WithContextObject(component)) { // component requires GameObject. collector.Init(componentInfo); @@ -50,7 +50,7 @@ public void CollectAllUsages() } collector.FinalizeForComponent(); - }); + } } } diff --git a/Editor/Processors/TraceAndOptimize/OptimizePhysBone.cs b/Editor/Processors/TraceAndOptimize/OptimizePhysBone.cs index 1b357197b..a6fcc9b52 100644 --- a/Editor/Processors/TraceAndOptimize/OptimizePhysBone.cs +++ b/Editor/Processors/TraceAndOptimize/OptimizePhysBone.cs @@ -107,8 +107,7 @@ bool IsAnimated() }); break; default: - BuildReport.LogWarning("TraceAndOptimize:OptimizePhysBone:UnknownPhysBoneColliderShape", shapeType.ToString()) - ?.WithContext(colliders); + BuildReport.LogWarning("TraceAndOptimize:OptimizePhysBone:UnknownPhysBoneColliderShape", shapeType.ToString(), colliders); break; } } @@ -150,18 +149,21 @@ private float PhysBoneScale(Transform transform) private void IsAnimatedOptimization(BuildContext context) { - BuildReport.ReportingObjects(context.GetComponents(), physBone => + foreach (var physBone in context.GetComponents()) { - var isAnimated = physBone.GetAffectedTransforms() - .Select(transform => context.GetAnimationComponent(transform)) - .Any(animation => IsAnimatedExternally(physBone, animation)); - if (physBone.isAnimated && !isAnimated) + using (ErrorReport.WithContextObject(physBone)) { - physBone.isAnimated = false; - Debug.Log($"Optimized IsAnimated for {physBone.name}", physBone); + var isAnimated = physBone.GetAffectedTransforms() + .Select(transform => context.GetAnimationComponent(transform)) + .Any(animation => IsAnimatedExternally(physBone, animation)); + if (physBone.isAnimated && !isAnimated) + { + physBone.isAnimated = false; + Debug.Log($"Optimized IsAnimated for {physBone.name}", physBone); + } + // TODO: add warning if physBone.isAnimated is false and isAnimated is true? } - // TODO: add warning if physBone.isAnimated is false and isAnimated is true? - }); + } } private static bool IsAnimatedExternally(VRCPhysBoneBase physBone, AnimationComponentInfo animation) diff --git a/Editor/Processors/UnusedBonesByReferencesToolEarlyProcessor.cs b/Editor/Processors/UnusedBonesByReferencesToolEarlyProcessor.cs index 3460fd617..ce38d9687 100644 --- a/Editor/Processors/UnusedBonesByReferencesToolEarlyProcessor.cs +++ b/Editor/Processors/UnusedBonesByReferencesToolEarlyProcessor.cs @@ -17,12 +17,12 @@ protected override void Execute(BuildContext context) var configuration = context.AvatarRootObject.GetComponent(); if (!configuration) return; - BuildReport.ReportingObject(configuration, () => + using (ErrorReport.WithContextObject(configuration)) { UnusedBonesByReferences.Make(BoneReference.Make(configuration.transform, configuration.detectExtraChild), configuration.preserveEndBone) .SetEditorOnlyToBones(); - }); + } } #region UnusedBonesByReferencesTool diff --git a/Internal/ErrorReporter/Editor/BuildReport.cs b/Internal/ErrorReporter/Editor/BuildReport.cs index 1a90c1ebe..31d3299b3 100644 --- a/Internal/ErrorReporter/Editor/BuildReport.cs +++ b/Internal/ErrorReporter/Editor/BuildReport.cs @@ -1,258 +1,80 @@ using System; +using System.Collections; using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Text; -using JetBrains.Annotations; +using nadena.dev.ndmf; +using nadena.dev.ndmf.localization; using UnityEditor; using UnityEngine; using Object = UnityEngine.Object; namespace Anatawa12.AvatarOptimizer.ErrorReporting { - [Serializable] - internal class AvatarReport + public static class BuildReport { - [SerializeField] internal ObjectRef objectRef; - [SerializeField] internal bool successful; - [SerializeField] internal List logs = new List(); - } - - [InitializeOnLoad] - [Serializable] - public class BuildReport - { - private const string Path = "Library/com.anatawa12.error-reporting.json"; - - private static BuildReport _report; - private Stack _references = new Stack(); - - [SerializeField] internal List avatars = new List(); - - internal ConditionalWeakTable AvatarsByObject = - new ConditionalWeakTable(); - internal AvatarReport CurrentAvatar { get; set; } - - internal static BuildReport CurrentReport - { - get - { - if (_report == null) _report = LoadReport() ?? new BuildReport(); - return _report; - } - } - - static BuildReport() - { - EditorApplication.playModeStateChanged += change => - { - switch (change) - { - case PlayModeStateChange.ExitingEditMode: - // TODO - skip if we're doing a VRCSDK build - _report = new BuildReport(); - break; - } - }; - } - - private static BuildReport LoadReport() - { - try - { - var data = File.ReadAllText(Path); - return JsonUtility.FromJson(data); - } - catch (Exception) - { - return null; - } - } - - internal static void SaveReport() - { - var report = CurrentReport; - var json = JsonUtility.ToJson(report); - - File.WriteAllText(Path, json); - - ErrorReportUI.ReloadErrorReport(); - } - - internal AvatarReport Initialize([NotNull] GameObject avatarGameObject) - { - if (avatarGameObject == null) throw new ArgumentNullException(nameof(avatarGameObject)); - - AvatarReport report = new AvatarReport(); - report.objectRef = new ObjectRef(avatarGameObject); - avatars.Add(report); - report.successful = true; - - report.logs.AddRange(ComponentValidation.ValidateAll(avatarGameObject)); - - AvatarsByObject.Add(avatarGameObject, report); - return report; - } - - [CanBeNull] - internal static ErrorLog Log(ReportLevel level, string code, string[] strings, Assembly assembly) - { - for (var i = 0; i < strings.Length; i++) - strings[i] = strings[i] ?? ""; - var errorLog = new ErrorLog(level, code, strings, assembly); + public static void LogInfo(string code, params object[] args) => + ErrorReport.ReportError(new InlineError(ErrorSeverity.Information, code, args)); - var builder = new StringBuilder("BuildReport: "); - builder.Append(code); - foreach (var s in strings) - builder.Append(", '").Append(s).Append("'"); - switch (level) - { - case ReportLevel.Validation: - case ReportLevel.Error: - case ReportLevel.InternalError: - Debug.LogError(builder.ToString()); - break; - case ReportLevel.Info: - Debug.Log(builder.ToString()); - break; - case ReportLevel.Warning: - Debug.LogWarning(builder.ToString()); - break; - default: - throw new ArgumentOutOfRangeException(nameof(level), level, null); - } + public static void LogWarning(string code, params object[] args) => + ErrorReport.ReportError(new InlineError(ErrorSeverity.NonFatal, code, args)); - var avatarReport = CurrentReport.CurrentAvatar; - if (avatarReport == null) - { - Debug.LogWarning("Error logged when not processing an avatar: " + errorLog); - return null; - } - - avatarReport.logs.Add(errorLog); - return errorLog; - } - - [CanBeNull] - public static ErrorLog LogInfo(string code, params string[] strings) => Log(ReportLevel.Info, code, - strings: strings, assembly: Assembly.GetCallingAssembly()); - - [CanBeNull] - public static ErrorLog LogWarning(string code, params string[] strings) => Log(ReportLevel.Warning, code, - strings: strings, assembly: Assembly.GetCallingAssembly()); - - [CanBeNull] - public static ErrorLog LogFatal(string code, params string[] strings) - { - var log = Log(ReportLevel.Error, code, strings: strings, assembly: Assembly.GetCallingAssembly()); - if (CurrentReport.CurrentAvatar != null) - { - CurrentReport.CurrentAvatar.successful = false; - } - else - { - throw new Exception("Fatal error without error reporting scope"); - } - return log; - } - - internal static void LogException(Exception e, string additionalStackTrace = "") - { - var avatarReport = CurrentReport.CurrentAvatar; - if (avatarReport == null) - { - Debug.LogException(e); - return; - } - else - { - avatarReport.logs.Add(new ErrorLog(e, additionalStackTrace)); - } - } - - public static T ReportingObject(Object obj, Func action) => ReportingObject(obj, false, action); - - public static T ReportingObject(Object obj, bool needThrow, Func action) - { - if (obj != null) CurrentReport._references.Push(obj); - try - { - return action(); - } - catch (ReportedException) - { - throw; // rethrow only - } - catch (Exception e) - { - // just rethrow if BuildReport is not in progress - if (CurrentReport.CurrentAvatar == null && needThrow) throw; - ReportInternalError(e, 2); - if (needThrow) throw new ReportedException(); - return default; - } - finally - { - if (obj != null) CurrentReport._references.Pop(); - } - } - - public static void ReportInternalError(Exception exception) => ReportInternalError(exception, 2); + public static void LogError(string code, params object[] args) => + ErrorReport.ReportError(new InlineError(ErrorSeverity.Error, code, args)); + } - private static void ReportInternalError(Exception exception, int strips) + internal class InlineError : SimpleError, IError + { + private static Localizer _localizer = new Localizer("en-US", () => new List() { - if (exception is ReportedException) return; // reported exception is known internal error - var additionalStackTrace = string.Join("\n", - Environment.StackTrace.Split('\n').Skip(strips)) + "\n"; - LogException(exception, additionalStackTrace); - } + // en.po + AssetDatabase.LoadAssetAtPath( + AssetDatabase.GUIDToAssetPath("f9d382355a0a485980e8e7271bca53d7")), + // ja.po + AssetDatabase.LoadAssetAtPath( + AssetDatabase.GUIDToAssetPath("feed5ac7cc024b9e92e46f7e2dbdbe82")), + }); - public static void ReportingObject(Object obj, Action action) => ReportingObject(obj, false, action); + private readonly string _key; - public static void ReportingObject(Object obj, bool needThrow, Action action) + public InlineError(ErrorSeverity errorSeverity, string key, params object[] args) { - ReportingObject(obj, needThrow, () => - { - action(); - return true; - }); - } + Localizer = _localizer; + Severity = errorSeverity; + // https://github.com/bdunderscore/ndmf/issues/99 + // https://github.com/bdunderscore/ndmf/issues/98 + _key = key; - public static void ReportingObjects(IEnumerable objs, Action action) where T : Object - { - foreach (var obj in objs) - ReportingObject(obj, () => action(obj)); + DetailsSubst = Array.ConvertAll(args, o => o?.ToString()); + Flatten(args, _references); } - internal IEnumerable GetActiveReferences() - { - return _references.Select(o => new ObjectRef(o)); - } + protected override string DetailsKey => _key; - public static void Clear() + private static void Flatten(object arg, List list) { - _report = new BuildReport(); + // https://github.com/bdunderscore/ndmf/issues/95 + // https://github.com/bdunderscore/ndmf/issues/96 + if (arg is ObjectReference or) + list.Add(or); + else if (arg is Object uo) + list.Add(ObjectRegistry.GetReference(uo)); + else if (arg is IContextProvider provider) + Flatten(provider.ProvideContext(), list); + else if (arg is IEnumerable enumerable) + foreach (var value in enumerable) + Flatten(value, list); } - public static void RemapPaths(string original, string cloned) - { - foreach (var av in CurrentReport.avatars) - { - av.objectRef = av.objectRef.Remap(original, cloned); + protected override Localizer Localizer { get; } + public override ErrorSeverity Severity { get; } + protected override string TitleKey { get; } - foreach (var log in av.logs) - { - log.referencedObjects = log.referencedObjects.Select(o => o.Remap(original, cloned)).ToList(); - } - } + protected override string[] DetailsSubst { get; } - ErrorReportUI.ReloadErrorReport(); - } + protected override string[] HintSubst => DetailsSubst; + } - private class ReportedException : Exception - { - } + public interface IContextProvider + { + object ProvideContext(); } } diff --git a/Internal/ErrorReporter/Editor/BuildReportContext.cs b/Internal/ErrorReporter/Editor/BuildReportContext.cs deleted file mode 100644 index d2d8ee340..000000000 --- a/Internal/ErrorReporter/Editor/BuildReportContext.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System; -using System.Linq; -using JetBrains.Annotations; -using nadena.dev.ndmf; -using UnityEditor; -using UnityEngine; - -namespace Anatawa12.AvatarOptimizer.ErrorReporting -{ - internal class BuildReportSharedState - { - [CanBeNull] public AvatarReport Report; - } - - public class BuildReportContext : IExtensionContext - { - public void OnActivate(BuildContext context) - { - var state = context.GetState(); - var avatarGameObject = context.AvatarRootObject; - if (avatarGameObject == null) throw new Exception(); - var report = state.Report; - if (state.Report == null) - { - // If it's in unity editor, I assume building avatar. - if (!EditorApplication.isPlayingOrWillChangePlaymode) - BuildReport.Clear(); - state.Report = report = BuildReport.CurrentReport.Initialize(avatarGameObject); - } - - BuildReport.CurrentReport.CurrentAvatar = report; - } - - public void OnDeactivate(BuildContext context) - { - var avatar = BuildReport.CurrentReport.CurrentAvatar; - BuildReport.CurrentReport.CurrentAvatar = null; - var successful = avatar.successful; - BuildReport.SaveReport(); - if (avatar.logs.Any()) - ErrorReportUI.OpenErrorReportUIFor(avatar); - if (!successful) throw new Exception("Avatar processing failed"); - } - } -} diff --git a/Internal/ErrorReporter/Editor/BuildReportContext.cs.meta b/Internal/ErrorReporter/Editor/BuildReportContext.cs.meta deleted file mode 100644 index 8af806e12..000000000 --- a/Internal/ErrorReporter/Editor/BuildReportContext.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 0d038758921ac4077984acf150bd7974 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Internal/ErrorReporter/Editor/ComponentValidation.cs b/Internal/ErrorReporter/Editor/ComponentValidation.cs index f9c686f95..13158d6a2 100644 --- a/Internal/ErrorReporter/Editor/ComponentValidation.cs +++ b/Internal/ErrorReporter/Editor/ComponentValidation.cs @@ -1,33 +1,26 @@ using System; -using System.Collections.Generic; -using System.Linq; using System.Runtime.CompilerServices; using JetBrains.Annotations; +using nadena.dev.ndmf; using UnityEngine; using Object = UnityEngine.Object; namespace Anatawa12.AvatarOptimizer.ErrorReporting { - using Validator = Func>; + using Validator = Action; public static class ComponentValidation { private static readonly ConditionalWeakTable Validators = new ConditionalWeakTable(); - internal static List ValidateAll(GameObject root) + // TODO: make internal + public static void ValidateAll(GameObject root) { - return root.GetComponentsInChildren(true) - .SelectMany(Validate) - .ToList(); + foreach (var component in root.GetComponentsInChildren(true)) + using (ErrorReport.WithContextObject((Object)component)) + GetValidator(component.GetType())?.Invoke(component); } - private static IEnumerable Validate(IStaticValidated component) => - GetValidator(component.GetType()) - ?.Invoke(component) - ?.Where(x => x != null) - ?.OnEach(x => x.referencedObjects.Add(new ObjectRef((Object)component))) - ?? Array.Empty(); - private static Validator GetValidator(Type type) { // fast path: registered @@ -48,7 +41,7 @@ private static Validator GetValidator(Type type) { // if not found, make warning and set empty validator Debug.LogWarning($"The StaticValidator for {type} not found. This must be a bug of {type.Assembly}"); - validator = _ => null; + validator = _ => { }; } Validators.Add(type, validator); @@ -68,7 +61,7 @@ private static Validator GetValidator(Type type) ///
  • The type implements ISelfStaticValidated
  • /// /// - public static void RegisterValidator(Func> validator) + public static void RegisterValidator(Action validator) where T : IStaticValidated { RegisterValidator(typeof(T), x => validator((T)x)); diff --git a/Internal/ErrorReporter/Editor/ErrorElement.cs b/Internal/ErrorReporter/Editor/ErrorElement.cs deleted file mode 100644 index 0b560b123..000000000 --- a/Internal/ErrorReporter/Editor/ErrorElement.cs +++ /dev/null @@ -1,102 +0,0 @@ -using System; -using System.Linq; -using CustomLocalization4EditorExtension; -using UnityEditor; -using UnityEngine; -using UnityEngine.SceneManagement; -using UnityEngine.UIElements; - -namespace Anatawa12.AvatarOptimizer.ErrorReporting -{ - internal class ErrorElement : Box - { - private readonly ErrorLog log; - - Texture2D GetIcon() - { - switch (log.reportLevel) - { - case ReportLevel.Info: - return EditorGUIUtility.FindTexture("d_console.infoicon"); - case ReportLevel.Warning: - return EditorGUIUtility.FindTexture("d_console.warnicon"); - default: - return EditorGUIUtility.FindTexture("d_console.erroricon"); - } - } - - public ErrorElement(ErrorLog log, ObjectRefLookupCache cache) - { - this.log = log; - - AddToClassList("ErrorElement"); - var tex = GetIcon(); - if (tex != null) - { - var image = new Image(); - image.image = tex; - Add(image); - } - - var inner = new Box(); - Add(inner); - - var label = new Label(GetLabelText()); - inner.Add(label); - - foreach (var obj in log.referencedObjects) - { - var referenced = obj.Lookup(cache); - if (referenced != null) - { - inner.Add(new SelectionButton(obj.typeName, referenced)); - } - } - - if (!string.IsNullOrWhiteSpace(log.stacktrace)) - { - var foldout = new Foldout(); - foldout.text = CL4EE.Tr("ErrorReporting:error.stack_trace"); - var field = new TextField(); - field.value = log.stacktrace; - field.isReadOnly = true; - field.multiline = true; - foldout.Add(field); - foldout.value = false; - inner.Add(foldout); - } - } - - private static GameObject FindObject(string path) - { - var scene = SceneManager.GetActiveScene(); - foreach (var root in scene.GetRootGameObjects()) - { - if (root.name == path) return root; - if (path.StartsWith(root.name + "/")) - { - return root.transform.Find(path.Substring(root.name.Length + 1))?.gameObject; - } - } - - return null; - } - - private string GetLabelText() - { - try - { - var assembly = log.MessageAssembly; - var localization = assembly != null ? CL4EE.GetLocalization(assembly) : null; - var formatKey = localization != null ? localization.Tr(log.messageCode) : log.messageCode; - return string.Format(formatKey, log.substitutions.ToArray()); - } - catch (FormatException e) - { - Debug.LogError("Error formatting message code: " + log.messageCode); - Debug.LogException(e); - return log.messageCode + "\n" + string.Join("\n", log.substitutions); - } - } - } -} diff --git a/Internal/ErrorReporter/Editor/ErrorElement.cs.meta b/Internal/ErrorReporter/Editor/ErrorElement.cs.meta deleted file mode 100644 index c264581f9..000000000 --- a/Internal/ErrorReporter/Editor/ErrorElement.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: fdf6fd69b5e34039b10619c37ac3b3f3 -timeCreated: 1682840642 diff --git a/Internal/ErrorReporter/Editor/ErrorLog.cs b/Internal/ErrorReporter/Editor/ErrorLog.cs deleted file mode 100644 index 265cc7185..000000000 --- a/Internal/ErrorReporter/Editor/ErrorLog.cs +++ /dev/null @@ -1,266 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using JetBrains.Annotations; -//using Newtonsoft.Json; -using UnityEngine; -using UnityEditor; -using UnityEngine.SceneManagement; -using Object = UnityEngine.Object; - -namespace Anatawa12.AvatarOptimizer.ErrorReporting -{ - internal class ObjectRefLookupCache - { - private readonly Dictionary<(string, long), Object> _cache = new Dictionary<(string, long), Object>(); - - internal Object FindByGuidAndLocalId(string guid, long localId) - { - if (!_cache.TryGetValue((guid, localId), out var obj)) - { - // 1: Imported Asset - // 3: Source Asset - foreach (var type in new [] { 1, 3 }) - { - if (GlobalObjectId.TryParse($"GlobalObjectId_V1-{type}-{guid}-{localId}-{0}", out var goid)) - { - obj = GlobalObjectId.GlobalObjectIdentifierToObjectSlow(goid); - if (obj) _cache[(guid, localId)] = obj; - } - } - } - - return obj; - } - } - - [Serializable] - internal struct ObjectRef - { - [SerializeField] internal string guid; - // 0 is null. - [SerializeField] internal long localId; - [SerializeField] internal string path, name; - [SerializeField] internal string typeName; - - internal ObjectRef(Object obj) - { - if (obj == null) - { - this = default; - } - else - { - var name = string.IsNullOrWhiteSpace(obj.name) ? "" : obj.name; - if (obj is Component c) - { - this = new ObjectRef( - path: Utils.RelativePath(null, c.gameObject), - name: name, - typeName: obj.GetType().Name); - } - else if (obj is GameObject go) - { - this = new ObjectRef( - path: Utils.RelativePath(null, go), - name: name, - typeName: obj.GetType().Name); - } - else if (AssetDatabase.TryGetGUIDAndLocalFileIdentifier(obj, out var guid, out long id)) - { - this = new ObjectRef(guid, id, name, obj.GetType().Name); - } - else - { - this = default; // fallback - } - } - } - - private ObjectRef([NotNull] string path, [NotNull] string name, [NotNull] string typeName) - { - guid = null; - localId = 0; - this.path = path ?? throw new ArgumentNullException(nameof(path)); - this.name = name ?? throw new ArgumentNullException(nameof(name)); - this.typeName = typeName ?? throw new ArgumentNullException(nameof(typeName)); - } - - private ObjectRef([NotNull] string guid, long localId, [NotNull] string name, [NotNull] string typeName) - { - this.guid = guid ?? throw new ArgumentNullException(nameof(guid)); - if (localId == 0) throw new ArgumentOutOfRangeException(nameof(guid), "guid must not be zero"); - this.localId = localId; - path = null; - this.name = name ?? throw new ArgumentNullException(nameof(name)); - this.typeName = typeName ?? throw new ArgumentNullException(nameof(typeName)); - } - - internal Object Lookup(ObjectRefLookupCache cache) - { - if (path != null) - return FindObject(path); - if (guid != null && localId != 0) - return cache.FindByGuidAndLocalId(guid, localId); - return null; - } - - private static GameObject FindObject(string path) - { - var scene = SceneManager.GetActiveScene(); - foreach (var root in scene.GetRootGameObjects()) - { - if (root.name == path) return root; - if (path.StartsWith(root.name + "/", StringComparison.Ordinal)) - { - return root.transform.Find(path.Substring(root.name.Length + 1))?.gameObject; - } - } - - return null; - } - - public ObjectRef Remap(string original, string cloned) - { - if (path == cloned) - { - return new ObjectRef( - path: original, - name: path.Substring(path.LastIndexOf('/') + 1), - typeName: typeName); - } - if (path != null && path.StartsWith(cloned + "/", StringComparison.Ordinal)) - { - return new ObjectRef( - path: original + path.Substring(cloned.Length), - name: path.Substring(path.LastIndexOf('/') + 1), - typeName: typeName); - } - - return this; - } - } - - public enum ReportLevel - { - Validation, - Info, - Warning, - Error, - InternalError, - } - - [Serializable] - public class ErrorLog - { - [SerializeField] internal List referencedObjects; - [SerializeField] internal ReportLevel reportLevel; - [SerializeField] internal string messageAssemblyName; - [SerializeField] internal string messageCode; - [SerializeField] internal string[] substitutions; - [SerializeField] internal string stacktrace; - - [CanBeNull] private Assembly _messageAssembly; - [CanBeNull] - internal Assembly MessageAssembly - { - get - { - if (_messageAssembly == null) - { - try - { - _messageAssembly = Assembly.Load(messageAssemblyName); - } - catch - { - // ignored - } - } - - return _messageAssembly; - } - } - - public ErrorLog(ReportLevel level, string code, string[] strings, Assembly callerAssembly) - { - reportLevel = level; - _messageAssembly = callerAssembly; - messageAssemblyName = _messageAssembly.GetName().Name; - - substitutions = strings.Select(s => $"{s}").ToArray(); - - referencedObjects = BuildReport.CurrentReport.GetActiveReferences().ToList(); - - messageCode = code; - stacktrace = null; - } - - public ErrorLog(ReportLevel level, string code, string[] strings) - : this(level, code, strings, Assembly.GetCallingAssembly()) - { - } - - public ErrorLog WithContext(params object[] args) - { - AddContext(args); - return this; - } - - public ErrorLog WithContext(ReadOnlySpan args) - { - foreach (var arg in args) AddContext(arg); - return this; - } - - private void AddContext(object value) - { - switch (value) - { - case Object o: - referencedObjects.Add(new ObjectRef(o)); - break; - case IContextProvider provider: - AddContext(provider.ProvideContext()); - break; - case IEnumerable enumerable: - foreach (var element in enumerable) - AddContext(element); - break; - } - } - - internal ErrorLog(Exception e, string additionalStackTrace = "") - : this(ReportLevel.InternalError, - "ErrorReporter:error.internal_error", - new[] { e.Message, e.TargetSite?.Name }, - typeof(ErrorLog).Assembly) - { - stacktrace = e.ToString() + additionalStackTrace; - } - - public override string ToString() - { - return "[" + reportLevel + "] " + messageCode + " " + "subst: " + string.Join(", ", substitutions); - } - - public static ErrorLog Validation(string code, params string[] strings) - => new ErrorLog(ReportLevel.Validation, code, strings, Assembly.GetCallingAssembly()); - - public static ErrorLog Info(string code, params string[] strings) - => new ErrorLog(ReportLevel.Info, code, strings, Assembly.GetCallingAssembly()); - - public static ErrorLog Warning(string code, params string[] strings) - => new ErrorLog(ReportLevel.Warning, code, strings, Assembly.GetCallingAssembly()); - - public static ErrorLog Error(string code, params string[] strings) - => new ErrorLog(ReportLevel.Error, code, strings, Assembly.GetCallingAssembly()); - } - - public interface IContextProvider - { - object ProvideContext(); - } -} diff --git a/Internal/ErrorReporter/Editor/ErrorLog.cs.meta b/Internal/ErrorReporter/Editor/ErrorLog.cs.meta deleted file mode 100644 index 620ce84fb..000000000 --- a/Internal/ErrorReporter/Editor/ErrorLog.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: b4087c2d2b42442884386c60e0f2036d -timeCreated: 1682840642 diff --git a/Internal/ErrorReporter/Editor/ErrorReportUI.cs b/Internal/ErrorReporter/Editor/ErrorReportUI.cs deleted file mode 100644 index 856556147..000000000 --- a/Internal/ErrorReporter/Editor/ErrorReportUI.cs +++ /dev/null @@ -1,295 +0,0 @@ -using System; -using System.Diagnostics; -using System.Linq; -using System.Threading.Tasks; -using JetBrains.Annotations; -using UnityEditor; -using UnityEditor.UIElements; -using UnityEngine; -using UnityEngine.UIElements; -using Debug = System.Diagnostics.Debug; - -namespace Anatawa12.AvatarOptimizer.ErrorReporting -{ - internal class ErrorReportUI : EditorWindow - { - internal static void ReloadErrorReport() => ReloadErrorReportEvent?.Invoke(); - private static event Action ReloadErrorReportEvent; - - [MenuItem("Tools/Avatar Optimizer/Show error report", false, 100)] - public static void OpenErrorReportUI() - { - GetWindow().Show(); - } - - public static void OpenErrorReportUIFor(AvatarReport avatar) - { - var window = GetWindow(); - window.Show(); - if (window._header != null) - window._header.Value = avatar; - } - - public static void MaybeOpenErrorReportUI() - { - if (BuildReport.CurrentReport.avatars.Any(av => av.logs.Count > 0)) - { - OpenErrorReportUI(); - } - } - - private void OnEnable() - { - titleContent = new GUIContent("Error Report"); - - rootVisualElement.styleSheets.Add(Resources.Load("com.anatawa12.avatar-optimizer.error-report")); - - ReloadErrorReportEvent += RenderContent; - - Selection.selectionChanged += ScheduleRender; - EditorApplication.playModeStateChanged += PlayModeStateChanged; - EditorApplication.hierarchyChanged += ScheduleRender; - ErrorReporterRuntime.OnChangeAction += ScheduleRender; - //Localization.OnLangChange += RenderContent; - } - - private void OnDisable() - { - ReloadErrorReportEvent -= RenderContent; - Selection.selectionChanged -= ScheduleRender; - EditorApplication.hierarchyChanged -= ScheduleRender; - ErrorReporterRuntime.OnChangeAction -= ScheduleRender; - //Localization.OnLangChange -= RenderContent; - } - - private const int RefreshDelayTime = 500; - [CanBeNull] private Stopwatch _delayTimer; - [CanBeNull] private HeaderBox _header; - [CanBeNull] private GameObject _defaultAvatarObject; - - private void PlayModeStateChanged(PlayModeStateChange obj) - { - switch (obj) - { - case PlayModeStateChange.EnteredEditMode: - _header?.RedrawList(); - break; - case PlayModeStateChange.ExitingEditMode: - case PlayModeStateChange.EnteredPlayMode: - case PlayModeStateChange.ExitingPlayMode: - default: - break; - } - } - - private void ScheduleRender() - { - if (_delayTimer == null) - { - _delayTimer = Stopwatch.StartNew(); - EditorApplication.delayCall += StartRenderTimer; - } - else - { - _delayTimer.Restart(); - } - } - - private async void StartRenderTimer() - { - Debug.Assert(_delayTimer != null, nameof(_delayTimer) + " != null"); - while (_delayTimer.ElapsedMilliseconds < RefreshDelayTime) - { - long remaining = RefreshDelayTime - _delayTimer.ElapsedMilliseconds; - if (remaining > 0) - { - await Task.Delay((int) remaining); - } - } - - _delayTimer = null; - RenderContent(); - Repaint(); - } - - private void CreateGUI() - { - var root = new Box(); - root.Clear(); - root.name = "Root"; - rootVisualElement.Add(root); - - var (activeAvatar, activeAvatarObject) = GetDefaultAvatar(); - _defaultAvatarObject = activeAvatarObject; - - _header = new HeaderBox(activeAvatar); - root.Add(_header); - - var box = new ScrollView(); - root.Add(box); - if (_header.Value != null) - UpdateErrorList(box, _header.Value); - _header.SelectionChanged += x => UpdateErrorList(box, x); - } - - private (AvatarReport activeAvatar, GameObject activeAvatarObject) GetDefaultAvatar() - { - AvatarReport activeAvatar = null; - GameObject activeAvatarObject = null; - - if (Selection.gameObjects.Length == 1) - { - activeAvatarObject = Utils.FindAvatarTransformInParents(Selection.activeGameObject.transform)?.gameObject; - if (activeAvatarObject != null) - { - var foundAvatarPath = Utils.RelativePath(null, activeAvatarObject); - activeAvatar = BuildReport.CurrentReport.avatars - .FirstOrDefault(av => av.objectRef.path == foundAvatarPath); - } - - if (activeAvatarObject != null && activeAvatar == null) - { - activeAvatar = new AvatarReport(); - activeAvatar.objectRef = new ObjectRef(activeAvatarObject); - } - } - - return (activeAvatar, activeAvatarObject); - } - - private void UpdateErrorList(VisualElement box, [NotNull] AvatarReport activeAvatar) - { - Debug.Assert(_header != null, nameof(_header) + " != null"); - var activeAvatarObject = activeAvatar == _header.DefaultValue ? _defaultAvatarObject : null; - var lookupCache = new ObjectRefLookupCache(); - var avBox = new Box(); - avBox.AddToClassList("avatarBox"); - - var errorLogs = activeAvatar.logs.ToList(); - - if (activeAvatarObject != null) - { - errorLogs.RemoveAll(l => l.reportLevel == ReportLevel.Validation); - - activeAvatar.logs = errorLogs; - - activeAvatar.logs.AddRange(ComponentValidation.ValidateAll(activeAvatarObject)); - } - - activeAvatar.logs.Sort((a, b) => a.reportLevel.CompareTo(b.reportLevel)); - - if (activeAvatar.logs.Count == 0) - { - var container = new Box(); - container.name = "no-errors"; - container.Add(new Label("Nothing to report!")); - avBox.Add(container); - } - else - { - foreach (var ev in activeAvatar.logs) - { - avBox.Add(new ErrorElement(ev, lookupCache)); - } - } - - box.Clear(); - box.Add(avBox); - } - - private void RenderContent() - { - var (activeAvatar, activeAvatarObject) = GetDefaultAvatar(); - _defaultAvatarObject = activeAvatarObject; - if (_header != null) - _header.DefaultValue = activeAvatar; - } - } - - class HeaderBox : Box - { - [CanBeNull] private PopupField _field; - [CanBeNull] private AvatarReport _defaultValue; - - [CanBeNull] - public AvatarReport DefaultValue - { - get => _defaultValue; - set - { - var oldDefaultValue = _defaultValue; - _defaultValue = value; - UpdateList(oldDefaultValue: oldDefaultValue); - } - } - - [CanBeNull] public AvatarReport Value - { - get => _field?.value; - set => UpdateList(value); - } - - public event Action SelectionChanged; - - public void RedrawList() - { - if (_field != null) - { - SelectionChanged?.Invoke(_field.value); - } - } - - public HeaderBox(AvatarReport defaultValue) - { - AddToClassList("avatarHeader"); - _defaultValue = defaultValue; - UpdateList(); - } - - public void UpdateList( - AvatarReport setValue = null, - AvatarReport oldDefaultValue = null - ) - { - var list = BuildReport.CurrentReport.avatars.ToList(); - if (DefaultValue != null && !list.Contains(DefaultValue)) - list.Add(DefaultValue); - list.Reverse(); - - if (list.Count == 0) - { - Clear(); - Add(new Label("No avatars for Error Report")); - _field = null; - } - else - { - AvatarReport oldValue = _field?.value; - AvatarReport value; - if (setValue != null) - value = setValue; - else if (DefaultValue != null && oldDefaultValue == _field?.value) - value = DefaultValue; - else if (_field != null && list.Contains(_field.value)) - value = _field.value; - else if (DefaultValue != null) - value = DefaultValue; - else - value = list.First(); - - _field = new PopupField(list, value, - x => x.objectRef.name, - x => x.objectRef.name); - - _field.RegisterValueChangedCallback(e => { SelectionChanged?.Invoke(e.newValue); }); - - Clear(); - Add(new Label("Error report for ")); - Add(_field); - - if (oldValue != value || setValue != null) SelectionChanged?.Invoke(value); - } - MarkDirtyRepaint(); - } - } -} diff --git a/Internal/ErrorReporter/Editor/ErrorReportUI.cs.meta b/Internal/ErrorReporter/Editor/ErrorReportUI.cs.meta deleted file mode 100644 index 90a8000f0..000000000 --- a/Internal/ErrorReporter/Editor/ErrorReportUI.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 1158876c188a473e8e2720f7f83063b3 -timeCreated: 1682840642 diff --git a/Internal/ErrorReporter/Editor/SelectionButton.cs b/Internal/ErrorReporter/Editor/SelectionButton.cs deleted file mode 100644 index a4e9bdd39..000000000 --- a/Internal/ErrorReporter/Editor/SelectionButton.cs +++ /dev/null @@ -1,32 +0,0 @@ -using UnityEditor; -using UnityEngine; -using UnityEngine.UIElements; - -namespace Anatawa12.AvatarOptimizer.ErrorReporting -{ - internal class SelectionButton : Box - { - private UnityEngine.Object target; - - internal SelectionButton(string typeName, UnityEngine.Object target) - { - this.target = target; - - AddToClassList("selection-button"); - - var tex = EditorGUIUtility.FindTexture("d_Search Icon"); - var icon = new Image {image = tex}; - Add(icon); - - var button = new Button(() => - { - Selection.activeObject = target; - EditorGUIUtility.PingObject(target); - }); - - //button.Add(new Label("[" + typeName + "] " + target.name)); - button.text = "[" + typeName + "] " + target.name; - Add(button); - } - } -} diff --git a/Internal/ErrorReporter/Editor/SelectionButton.cs.meta b/Internal/ErrorReporter/Editor/SelectionButton.cs.meta deleted file mode 100644 index 269ae139a..000000000 --- a/Internal/ErrorReporter/Editor/SelectionButton.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 4a38947c154a43af9690706b59340d2f -timeCreated: 1682840642 diff --git a/Internal/ErrorReporter/Editor/Utils.cs b/Internal/ErrorReporter/Editor/Utils.cs deleted file mode 100644 index ea4e8bcca..000000000 --- a/Internal/ErrorReporter/Editor/Utils.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System; -using System.Collections.Generic; -using JetBrains.Annotations; -using nadena.dev.ndmf.runtime; -using UnityEngine; - -namespace Anatawa12.AvatarOptimizer.ErrorReporting -{ - internal static class Utils - { - [CanBeNull] - public static Transform FindAvatarTransformInParents([CanBeNull] Transform transform) - { - return RuntimeUtil.FindAvatarInParents(transform); - } - - /// - /// - /// - /// - /// - /// relative path to child. null if parent is not parent of child - /// - [CanBeNull] - [ContractAnnotation("parent:null, child:notnull => notnull")] - public static string RelativePath([CanBeNull] GameObject parent, [NotNull] GameObject child) - { - if (child == null) throw new ArgumentNullException(nameof(child)); - - // fast path: parent is child - if (parent == child) - return ""; - - var components = new List(); - - var parentTransform = parent != null ? parent.transform : null; - var transform = child.transform; - for (;;) - { - if (transform == parentTransform) break; - if (transform == null) return null; - components.Add(transform.name); - transform = transform.parent; - } - - components.Reverse(); - - return string.Join("/", components); - } - - internal static IEnumerable OnEach(this IEnumerable self, Action action) - { - if (self == null) throw new ArgumentNullException(nameof(self)); - foreach (var value in self) - { - action(value); - yield return value; - } - } - } -} diff --git a/Internal/ErrorReporter/Editor/Utils.cs.meta b/Internal/ErrorReporter/Editor/Utils.cs.meta deleted file mode 100644 index bb885abb4..000000000 --- a/Internal/ErrorReporter/Editor/Utils.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 91b39cf11bf74b1295b47853fa8b6521 -timeCreated: 1682854428 \ No newline at end of file diff --git a/Internal/ErrorReporter/Runtime/ErrorReporterRuntime.cs b/Internal/ErrorReporter/Runtime/ErrorReporterRuntime.cs deleted file mode 100644 index 840f28704..000000000 --- a/Internal/ErrorReporter/Runtime/ErrorReporterRuntime.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; - -namespace Anatawa12.AvatarOptimizer.ErrorReporting -{ - public static class ErrorReporterRuntime - { - internal static event Action OnChangeAction; - - public static void TriggerChange() - { - OnChangeAction?.Invoke(); - } - } -} diff --git a/Internal/ErrorReporter/Runtime/ErrorReporterRuntime.cs.meta b/Internal/ErrorReporter/Runtime/ErrorReporterRuntime.cs.meta deleted file mode 100644 index d87528620..000000000 --- a/Internal/ErrorReporter/Runtime/ErrorReporterRuntime.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: def90495536a4cda83d61f020cdef0e5 -timeCreated: 1682948531 \ No newline at end of file diff --git a/Localization/en.po b/Localization/en.po index 2821a224d..e41ffc75b 100644 --- a/Localization/en.po +++ b/Localization/en.po @@ -381,10 +381,10 @@ msgstr "Removes polygons whose area are zero" # region AvatarGlobalComponent -msgid "DeleteEditorOnlyGameObjects:NotOnAvatarDescriptor" +msgid "AvatarGlobalComponent:NotOnAvatarDescriptor" msgstr "This component must be set on root of Avatar (GameObject with AvatarDescriptor)" -msgid "DeleteEditorOnlyGameObjects:NotOnAvatarRoot" +msgid "AvatarGlobalComponent:NotOnAvatarRoot" msgstr "This component must be set on root of Avatar (For VRChat avatars, GameObject with AvatarDescriptor)" # endregion diff --git a/Localization/ja.po b/Localization/ja.po index fe60b8fb4..5448f54d3 100644 --- a/Localization/ja.po +++ b/Localization/ja.po @@ -313,10 +313,10 @@ msgstr "面積がゼロのポリゴンを削除します。" # region AvatarGlobalComponent -msgid "DeleteEditorOnlyGameObjects:NotOnAvatarDescriptor" +msgid "AvatarGlobalComponent:NotOnAvatarDescriptor" msgstr "このコンポーネントはアバターの最上位に付ける必要があります。(AvatarDescriptorのあるGameObject)" -msgid "DeleteEditorOnlyGameObjects:NotOnAvatarRoot" +msgid "AvatarGlobalComponent:NotOnAvatarRoot" msgstr "このコンポーネントはアバターの最上位に付ける必要があります。(VRChatのアバターでは、AvatarDescriptorのあるGameObject)" # endregion diff --git a/Runtime/AvatarTagComponent.cs b/Runtime/AvatarTagComponent.cs index 75056544f..f359a328f 100644 --- a/Runtime/AvatarTagComponent.cs +++ b/Runtime/AvatarTagComponent.cs @@ -17,15 +17,5 @@ internal abstract class AvatarTagComponent : MonoBehaviour , VRC.SDKBase.IEditorOnly #endif { - private void OnValidate() - { - if (RuntimeUtil.IsPlaying) return; - ErrorReporterRuntime.TriggerChange(); - } - - private void OnDestroy() - { - ErrorReporterRuntime.TriggerChange(); - } } } \ No newline at end of file diff --git a/package.json b/package.json index e1748013c..54a076b06 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,7 @@ "repo": "https://vpm.anatawa12.com/vpm.json", "vpmDependencies": { "com.anatawa12.custom-localization-for-editor-extension": "^1.0.0", - "nadena.dev.ndmf": "^1.0.0", + "nadena.dev.ndmf": "^1.3.0-rc.0", "com.vrchat.avatars": ">=3.2.0-beta.1 <3.6.0" } } From 0d8065e4c28996140de0ffd2b90f20a605180cdb Mon Sep 17 00:00:00 2001 From: anatawa12 Date: Thu, 28 Dec 2023 03:25:23 +0900 Subject: [PATCH 02/10] chore: move everything about error reporting to main assembly and remove ErrorReporter assembly --- Editor/ErrorReporting.meta | 3 + .../ErrorReporting}/BuildReport.cs | 0 .../ErrorReporting}/BuildReport.cs.meta | 0 .../ErrorReporting}/ComponentValidation.cs | 0 .../ComponentValidation.cs.meta | 0 ...m.anatawa12.avatar-optimizer.editor.asmdef | 2 - Internal/ErrorReporter.meta | 3 - Internal/ErrorReporter/Editor.meta | 3 - Internal/ErrorReporter/Editor/README.txt | 27 ------ Internal/ErrorReporter/Editor/README.txt.meta | 3 - Internal/ErrorReporter/Editor/Resources.meta | 3 - ...natawa12.avatar-optimizer.error-report.uss | 90 ------------------- ...a12.avatar-optimizer.error-report.uss.meta | 11 --- .../ErrorReporter/Editor/asssembly-info.cs | 4 - .../Editor/asssembly-info.cs.meta | 3 - ...izer.internal.error-reporter.editor.asmdef | 26 ------ ...internal.error-reporter.editor.asmdef.meta | 3 - Internal/ErrorReporter/Runtime.meta | 3 - .../ErrorReporter/Runtime/asssembly-info.cs | 5 -- .../Runtime/asssembly-info.cs.meta | 3 - ...zer.internal.error-reporter.runtime.asmdef | 18 ---- ...nternal.error-reporter.runtime.asmdef.meta | 3 - .../Runtime => Runtime}/IStaticValidated.cs | 1 + .../IStaticValidated.cs.meta | 0 ....anatawa12.avatar-optimizer.runtime.asmdef | 1 - ...com.anatawa12.avatar-optimizer.test.asmdef | 1 - 26 files changed, 4 insertions(+), 212 deletions(-) create mode 100644 Editor/ErrorReporting.meta rename {Internal/ErrorReporter/Editor => Editor/ErrorReporting}/BuildReport.cs (100%) rename {Internal/ErrorReporter/Editor => Editor/ErrorReporting}/BuildReport.cs.meta (100%) rename {Internal/ErrorReporter/Editor => Editor/ErrorReporting}/ComponentValidation.cs (100%) rename {Internal/ErrorReporter/Editor => Editor/ErrorReporting}/ComponentValidation.cs.meta (100%) delete mode 100644 Internal/ErrorReporter.meta delete mode 100644 Internal/ErrorReporter/Editor.meta delete mode 100644 Internal/ErrorReporter/Editor/README.txt delete mode 100644 Internal/ErrorReporter/Editor/README.txt.meta delete mode 100644 Internal/ErrorReporter/Editor/Resources.meta delete mode 100644 Internal/ErrorReporter/Editor/Resources/com.anatawa12.avatar-optimizer.error-report.uss delete mode 100644 Internal/ErrorReporter/Editor/Resources/com.anatawa12.avatar-optimizer.error-report.uss.meta delete mode 100644 Internal/ErrorReporter/Editor/asssembly-info.cs delete mode 100644 Internal/ErrorReporter/Editor/asssembly-info.cs.meta delete mode 100644 Internal/ErrorReporter/Editor/com.anatawa12.avatar-optimizer.internal.error-reporter.editor.asmdef delete mode 100644 Internal/ErrorReporter/Editor/com.anatawa12.avatar-optimizer.internal.error-reporter.editor.asmdef.meta delete mode 100644 Internal/ErrorReporter/Runtime.meta delete mode 100644 Internal/ErrorReporter/Runtime/asssembly-info.cs delete mode 100644 Internal/ErrorReporter/Runtime/asssembly-info.cs.meta delete mode 100644 Internal/ErrorReporter/Runtime/com.anatawa12.avatar-optimizer.internal.error-reporter.runtime.asmdef delete mode 100644 Internal/ErrorReporter/Runtime/com.anatawa12.avatar-optimizer.internal.error-reporter.runtime.asmdef.meta rename {Internal/ErrorReporter/Runtime => Runtime}/IStaticValidated.cs (87%) rename {Internal/ErrorReporter/Runtime => Runtime}/IStaticValidated.cs.meta (100%) diff --git a/Editor/ErrorReporting.meta b/Editor/ErrorReporting.meta new file mode 100644 index 000000000..f9c19c155 --- /dev/null +++ b/Editor/ErrorReporting.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 1b10606d90a949c8aee9446bc6087162 +timeCreated: 1703701376 \ No newline at end of file diff --git a/Internal/ErrorReporter/Editor/BuildReport.cs b/Editor/ErrorReporting/BuildReport.cs similarity index 100% rename from Internal/ErrorReporter/Editor/BuildReport.cs rename to Editor/ErrorReporting/BuildReport.cs diff --git a/Internal/ErrorReporter/Editor/BuildReport.cs.meta b/Editor/ErrorReporting/BuildReport.cs.meta similarity index 100% rename from Internal/ErrorReporter/Editor/BuildReport.cs.meta rename to Editor/ErrorReporting/BuildReport.cs.meta diff --git a/Internal/ErrorReporter/Editor/ComponentValidation.cs b/Editor/ErrorReporting/ComponentValidation.cs similarity index 100% rename from Internal/ErrorReporter/Editor/ComponentValidation.cs rename to Editor/ErrorReporting/ComponentValidation.cs diff --git a/Internal/ErrorReporter/Editor/ComponentValidation.cs.meta b/Editor/ErrorReporting/ComponentValidation.cs.meta similarity index 100% rename from Internal/ErrorReporter/Editor/ComponentValidation.cs.meta rename to Editor/ErrorReporting/ComponentValidation.cs.meta diff --git a/Editor/com.anatawa12.avatar-optimizer.editor.asmdef b/Editor/com.anatawa12.avatar-optimizer.editor.asmdef index ec6ab5c67..c13a49f02 100644 --- a/Editor/com.anatawa12.avatar-optimizer.editor.asmdef +++ b/Editor/com.anatawa12.avatar-optimizer.editor.asmdef @@ -1,8 +1,6 @@ { "name": "com.anatawa12.avatar-optimizer.editor", "references": [ - "com.anatawa12.avatar-optimizer.internal.error-reporter.runtime", - "com.anatawa12.avatar-optimizer.internal.error-reporter.editor", "com.anatawa12.custom-localization-for-editor-extension", "com.anatawa12.custom-localization-for-editor-extension.runtime", "com.anatawa12.avatar-optimizer.runtime", diff --git a/Internal/ErrorReporter.meta b/Internal/ErrorReporter.meta deleted file mode 100644 index 0bf0afc5d..000000000 --- a/Internal/ErrorReporter.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 5b6a11b6cf8b4cb19d98e8b9133516b2 -timeCreated: 1682837060 diff --git a/Internal/ErrorReporter/Editor.meta b/Internal/ErrorReporter/Editor.meta deleted file mode 100644 index 41a972661..000000000 --- a/Internal/ErrorReporter/Editor.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 950e3fae7aac4e6594cb4e0854338f8f -timeCreated: 1682838469 diff --git a/Internal/ErrorReporter/Editor/README.txt b/Internal/ErrorReporter/Editor/README.txt deleted file mode 100644 index 2024e5e52..000000000 --- a/Internal/ErrorReporter/Editor/README.txt +++ /dev/null @@ -1,27 +0,0 @@ -This folder contains ErrorReporting system which initially copied from modula-avatar. - -Original copyright & license notice is shown below. - ----- - -MIT License - -Copyright (c) 2022 bd_ - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/Internal/ErrorReporter/Editor/README.txt.meta b/Internal/ErrorReporter/Editor/README.txt.meta deleted file mode 100644 index 341650bd6..000000000 --- a/Internal/ErrorReporter/Editor/README.txt.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 4e81c5d9d5614b41bb910d762071c48a -timeCreated: 1682846503 \ No newline at end of file diff --git a/Internal/ErrorReporter/Editor/Resources.meta b/Internal/ErrorReporter/Editor/Resources.meta deleted file mode 100644 index 775df0e06..000000000 --- a/Internal/ErrorReporter/Editor/Resources.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 80b43a33caa6402395fa66ad6d2bbaec -timeCreated: 1682840642 diff --git a/Internal/ErrorReporter/Editor/Resources/com.anatawa12.avatar-optimizer.error-report.uss b/Internal/ErrorReporter/Editor/Resources/com.anatawa12.avatar-optimizer.error-report.uss deleted file mode 100644 index e7ff2c31a..000000000 --- a/Internal/ErrorReporter/Editor/Resources/com.anatawa12.avatar-optimizer.error-report.uss +++ /dev/null @@ -1,90 +0,0 @@ -VisualElement { - -} - -.avatarHeader { - display: flex; - flex-direction: row; - justify-content: center; - font-size: 200%; - margin-top: 10px; - margin-bottom: 10px; - border-left-width: 0; - border-right-width: 0; - border-top-width: 0; - border-bottom-width: 0; -} - -.ErrorElement { - display: flex; - flex-direction: row; - justify-content: flex-start; - align-items: center; - padding: 2px; - margin: 2px; -} - -.ErrorElement > Image { - width: 32px; - height: 32px; -} - -.ErrorElement Box { - flex: 1 auto; - flex-direction: column; - justify-content: flex-start; - align-items: flex-start; - padding: 2px; - margin: 2px; - border-width: 0 0 0 0; -} - -#logo { - width: 100%; - align-items: center; - flex-direction: column; - flex-shrink: 0; - padding-top: 10px; - padding-bottom: 10px; - border-width: 0; - border-bottom-width: 1px; -} - - -.ErrorElement Box Label { - white-space: normal; /* word wrap??? */ -} - -.selection-button { - display: flex; - flex-direction: row; - justify-content: flex-start; - align-items: center; - border-width: 0 0 0 0; -} - -.selection-button > Image { - width: 16px; - height: 16px; -} - -#no-errors { - flex-grow: 1; - align-content: center; - justify-content: center; - border-width: 0; -} - -#no-errors Label { - align-self: center; -} - -.avatarBox { - border-width: 0; -} - -#Root { - border-width: 0; - width: 100%; - height: 100%; -} diff --git a/Internal/ErrorReporter/Editor/Resources/com.anatawa12.avatar-optimizer.error-report.uss.meta b/Internal/ErrorReporter/Editor/Resources/com.anatawa12.avatar-optimizer.error-report.uss.meta deleted file mode 100644 index 80e5da525..000000000 --- a/Internal/ErrorReporter/Editor/Resources/com.anatawa12.avatar-optimizer.error-report.uss.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 7422dad9176054aa0a9be71c9d9a07b4 -ScriptedImporter: - internalIDToNameTable: [] - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 12385, guid: 0000000000000000e000000000000000, type: 0} - disableValidation: 0 diff --git a/Internal/ErrorReporter/Editor/asssembly-info.cs b/Internal/ErrorReporter/Editor/asssembly-info.cs deleted file mode 100644 index 62161a66f..000000000 --- a/Internal/ErrorReporter/Editor/asssembly-info.cs +++ /dev/null @@ -1,4 +0,0 @@ -using CustomLocalization4EditorExtension; - -// TODO: currently uses com.anatawa12.avatar-optimizer.editor but we need to migrate to own CL4EE instance later. -[assembly:RedirectCL4EEInstance("com.anatawa12.avatar-optimizer.editor")] diff --git a/Internal/ErrorReporter/Editor/asssembly-info.cs.meta b/Internal/ErrorReporter/Editor/asssembly-info.cs.meta deleted file mode 100644 index ddd7b08ca..000000000 --- a/Internal/ErrorReporter/Editor/asssembly-info.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: f619c11a62934a2dbd8dd078aea252d1 -timeCreated: 1682859435 \ No newline at end of file diff --git a/Internal/ErrorReporter/Editor/com.anatawa12.avatar-optimizer.internal.error-reporter.editor.asmdef b/Internal/ErrorReporter/Editor/com.anatawa12.avatar-optimizer.internal.error-reporter.editor.asmdef deleted file mode 100644 index 4ebbd7970..000000000 --- a/Internal/ErrorReporter/Editor/com.anatawa12.avatar-optimizer.internal.error-reporter.editor.asmdef +++ /dev/null @@ -1,26 +0,0 @@ -{ - "name": "com.anatawa12.avatar-optimizer.internal.error-reporter.editor", - "references": [ - "com.anatawa12.custom-localization-for-editor-extension", - "com.anatawa12.custom-localization-for-editor-extension.runtime", - "com.anatawa12.avatar-optimizer.internal.error-reporter.runtime", - "nadena.dev.ndmf", - "nadena.dev.ndmf.runtime" - ], - "includePlatforms": [ - "Editor" - ], - "excludePlatforms": [], - "allowUnsafeCode": false, - "overrideReferences": true, - "precompiledReferences": [ - "System.Memory.dll", - "VRCSDK3A.dll", - "VRCSDKBase.dll", - "VRCSDKBase-Editor.dll" - ], - "autoReferenced": false, - "defineConstraints": [], - "versionDefines": [], - "noEngineReferences": false -} \ No newline at end of file diff --git a/Internal/ErrorReporter/Editor/com.anatawa12.avatar-optimizer.internal.error-reporter.editor.asmdef.meta b/Internal/ErrorReporter/Editor/com.anatawa12.avatar-optimizer.internal.error-reporter.editor.asmdef.meta deleted file mode 100644 index 1ac522653..000000000 --- a/Internal/ErrorReporter/Editor/com.anatawa12.avatar-optimizer.internal.error-reporter.editor.asmdef.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: c03011c168164e1a954438f640cbd728 -timeCreated: 1682838475 diff --git a/Internal/ErrorReporter/Runtime.meta b/Internal/ErrorReporter/Runtime.meta deleted file mode 100644 index cea24437b..000000000 --- a/Internal/ErrorReporter/Runtime.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 059b29a8529c4d178b37665342b6cc3b -timeCreated: 1682928183 \ No newline at end of file diff --git a/Internal/ErrorReporter/Runtime/asssembly-info.cs b/Internal/ErrorReporter/Runtime/asssembly-info.cs deleted file mode 100644 index 5d0190772..000000000 --- a/Internal/ErrorReporter/Runtime/asssembly-info.cs +++ /dev/null @@ -1,5 +0,0 @@ -using System.Runtime.CompilerServices; -using CustomLocalization4EditorExtension; - -[assembly:InternalsVisibleTo("com.anatawa12.avatar-optimizer.internal.error-reporter.editor")] -[assembly:RedirectCL4EEInstance("com.anatawa12.avatar-optimizer.internal.error-reporter.editor")] diff --git a/Internal/ErrorReporter/Runtime/asssembly-info.cs.meta b/Internal/ErrorReporter/Runtime/asssembly-info.cs.meta deleted file mode 100644 index 5b697b47c..000000000 --- a/Internal/ErrorReporter/Runtime/asssembly-info.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 92a6c31b6bb343178d648e396b41d493 -timeCreated: 1682929884 \ No newline at end of file diff --git a/Internal/ErrorReporter/Runtime/com.anatawa12.avatar-optimizer.internal.error-reporter.runtime.asmdef b/Internal/ErrorReporter/Runtime/com.anatawa12.avatar-optimizer.internal.error-reporter.runtime.asmdef deleted file mode 100644 index 4bd879898..000000000 --- a/Internal/ErrorReporter/Runtime/com.anatawa12.avatar-optimizer.internal.error-reporter.runtime.asmdef +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "com.anatawa12.avatar-optimizer.internal.error-reporter.runtime", - "references": [ - "com.anatawa12.custom-localization-for-editor-extension.runtime" - ], - "includePlatforms": [], - "excludePlatforms": [], - "allowUnsafeCode": false, - "overrideReferences": true, - "precompiledReferences": [ - "VRCSDK3A.dll", - "VRCSDKBase.dll" - ], - "autoReferenced": false, - "defineConstraints": [], - "versionDefines": [], - "noEngineReferences": false -} \ No newline at end of file diff --git a/Internal/ErrorReporter/Runtime/com.anatawa12.avatar-optimizer.internal.error-reporter.runtime.asmdef.meta b/Internal/ErrorReporter/Runtime/com.anatawa12.avatar-optimizer.internal.error-reporter.runtime.asmdef.meta deleted file mode 100644 index fa3992bd5..000000000 --- a/Internal/ErrorReporter/Runtime/com.anatawa12.avatar-optimizer.internal.error-reporter.runtime.asmdef.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: b23bdfe8d18741a29e869995d47026d0 -timeCreated: 1682928193 \ No newline at end of file diff --git a/Internal/ErrorReporter/Runtime/IStaticValidated.cs b/Runtime/IStaticValidated.cs similarity index 87% rename from Internal/ErrorReporter/Runtime/IStaticValidated.cs rename to Runtime/IStaticValidated.cs index a39b48caf..019cdec7b 100644 --- a/Internal/ErrorReporter/Runtime/IStaticValidated.cs +++ b/Runtime/IStaticValidated.cs @@ -6,5 +6,6 @@ namespace Anatawa12.AvatarOptimizer.ErrorReporting /// public interface IStaticValidated { + // TODO: remove this interface } } diff --git a/Internal/ErrorReporter/Runtime/IStaticValidated.cs.meta b/Runtime/IStaticValidated.cs.meta similarity index 100% rename from Internal/ErrorReporter/Runtime/IStaticValidated.cs.meta rename to Runtime/IStaticValidated.cs.meta diff --git a/Runtime/com.anatawa12.avatar-optimizer.runtime.asmdef b/Runtime/com.anatawa12.avatar-optimizer.runtime.asmdef index c3414c1f5..6b6ed4092 100644 --- a/Runtime/com.anatawa12.avatar-optimizer.runtime.asmdef +++ b/Runtime/com.anatawa12.avatar-optimizer.runtime.asmdef @@ -1,7 +1,6 @@ { "name": "com.anatawa12.avatar-optimizer.runtime", "references": [ - "com.anatawa12.avatar-optimizer.internal.error-reporter.runtime", "com.anatawa12.custom-localization-for-editor-extension.runtime", "com.anatawa12.avatar-optimizer.internal.prefab-safe-set", "Unity.Burst", diff --git a/Test~/com.anatawa12.avatar-optimizer.test.asmdef b/Test~/com.anatawa12.avatar-optimizer.test.asmdef index d7cd7f36a..37084740c 100644 --- a/Test~/com.anatawa12.avatar-optimizer.test.asmdef +++ b/Test~/com.anatawa12.avatar-optimizer.test.asmdef @@ -8,7 +8,6 @@ "com.anatawa12.avatar-optimizer.runtime", "com.anatawa12.avatar-optimizer.internal.prefab-safe-set", "com.anatawa12.avatar-optimizer.internal.prefab-safe-set.editor", - "com.anatawa12.avatar-optimizer.internal.error-reporter.editor", "com.anatawa12.avatar-optimizer.api.editor", "UnityEngine.TestRunner", "UnityEditor.TestRunner", From 306881cacc52d3041d15f648018b0b23b4046338 Mon Sep 17 00:00:00 2001 From: anatawa12 Date: Thu, 28 Dec 2023 03:32:47 +0900 Subject: [PATCH 03/10] chore: make internal --- Editor/ErrorReporting/BuildReport.cs | 4 ++-- Editor/ErrorReporting/ComponentValidation.cs | 2 +- Runtime/IStaticValidated.cs | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Editor/ErrorReporting/BuildReport.cs b/Editor/ErrorReporting/BuildReport.cs index 31d3299b3..f1e0f8520 100644 --- a/Editor/ErrorReporting/BuildReport.cs +++ b/Editor/ErrorReporting/BuildReport.cs @@ -9,7 +9,7 @@ namespace Anatawa12.AvatarOptimizer.ErrorReporting { - public static class BuildReport + internal static class BuildReport { public static void LogInfo(string code, params object[] args) => ErrorReport.ReportError(new InlineError(ErrorSeverity.Information, code, args)); @@ -73,7 +73,7 @@ private static void Flatten(object arg, List list) protected override string[] HintSubst => DetailsSubst; } - public interface IContextProvider + internal interface IContextProvider { object ProvideContext(); } diff --git a/Editor/ErrorReporting/ComponentValidation.cs b/Editor/ErrorReporting/ComponentValidation.cs index 13158d6a2..f840198fd 100644 --- a/Editor/ErrorReporting/ComponentValidation.cs +++ b/Editor/ErrorReporting/ComponentValidation.cs @@ -9,7 +9,7 @@ namespace Anatawa12.AvatarOptimizer.ErrorReporting { using Validator = Action; - public static class ComponentValidation + internal static class ComponentValidation { private static readonly ConditionalWeakTable Validators = new ConditionalWeakTable(); diff --git a/Runtime/IStaticValidated.cs b/Runtime/IStaticValidated.cs index 019cdec7b..240a48af6 100644 --- a/Runtime/IStaticValidated.cs +++ b/Runtime/IStaticValidated.cs @@ -4,7 +4,7 @@ namespace Anatawa12.AvatarOptimizer.ErrorReporting /// The marker interface for components to be validated. /// You must register validator to ComponentValidation. /// - public interface IStaticValidated + internal interface IStaticValidated { // TODO: remove this interface } From 7bf38b8bdb25b47c0c1aca6270ee021db0c55487 Mon Sep 17 00:00:00 2001 From: anatawa12 Date: Thu, 28 Dec 2023 03:47:20 +0900 Subject: [PATCH 04/10] chore: rewrite validation --- Editor/AvatarGlobalComponentEditorBase.cs | 17 +-- Editor/ErrorReporting/ComponentValidation.cs | 120 ++++++------------- Editor/MergePhysBoneEditor.cs | 8 +- Editor/MergeSkinnedMeshEditor.cs | 15 --- Editor/Processors/MergeBoneProcessor.cs | 34 +++--- Runtime/AvatarGlobalComponent.cs | 4 +- Runtime/AvatarTagComponent.cs | 1 - Runtime/IStaticValidated.cs | 11 -- Runtime/IStaticValidated.cs.meta | 3 - Runtime/MergeBone.cs | 3 +- Runtime/MergePhysBone.cs | 3 +- Runtime/MergeSkinnedMesh.cs | 3 +- 12 files changed, 55 insertions(+), 167 deletions(-) delete mode 100644 Runtime/IStaticValidated.cs delete mode 100644 Runtime/IStaticValidated.cs.meta diff --git a/Editor/AvatarGlobalComponentEditorBase.cs b/Editor/AvatarGlobalComponentEditorBase.cs index 9698c91fb..226928bb2 100644 --- a/Editor/AvatarGlobalComponentEditorBase.cs +++ b/Editor/AvatarGlobalComponentEditorBase.cs @@ -1,31 +1,16 @@ -using Anatawa12.AvatarOptimizer.ErrorReporting; using CustomLocalization4EditorExtension; using UnityEditor; using UnityEngine; #if AAO_VRCSDK3_AVATARS -using nadena.dev.ndmf; -using VRC.Core; using VRC.SDK3.Avatars.Components; #endif namespace Anatawa12.AvatarOptimizer { + [InitializeOnLoad] abstract class AvatarGlobalComponentEditorBase : AvatarTagComponentEditorBase { - static AvatarGlobalComponentEditorBase() - { - ComponentValidation.RegisterValidator(component => - { -#if AAO_VRCSDK3_AVATARS - if (!component.GetComponent()) - BuildReport.LogError("AvatarGlobalComponent:NotOnAvatarDescriptor"); -#else - if (!nadena.dev.ndmf.runtime.RuntimeUtil.IsAvatarRoot(component.transform)) - BuildReport.LogError("AvatarGlobalComponent:NotOnAvatarDescriptor"); -#endif - }); - } protected override void OnInspectorGUIInner() { #if AAO_VRCSDK3_AVATARS diff --git a/Editor/ErrorReporting/ComponentValidation.cs b/Editor/ErrorReporting/ComponentValidation.cs index f840198fd..c5fece566 100644 --- a/Editor/ErrorReporting/ComponentValidation.cs +++ b/Editor/ErrorReporting/ComponentValidation.cs @@ -1,98 +1,48 @@ -using System; -using System.Runtime.CompilerServices; -using JetBrains.Annotations; -using nadena.dev.ndmf; +using Anatawa12.AvatarOptimizer.Processors; using UnityEngine; -using Object = UnityEngine.Object; namespace Anatawa12.AvatarOptimizer.ErrorReporting { - using Validator = Action; - internal static class ComponentValidation { - private static readonly ConditionalWeakTable Validators = new ConditionalWeakTable(); - - // TODO: make internal public static void ValidateAll(GameObject root) { - foreach (var component in root.GetComponentsInChildren(true)) - using (ErrorReport.WithContextObject((Object)component)) - GetValidator(component.GetType())?.Invoke(component); - } - - private static Validator GetValidator(Type type) - { - // fast path: registered - if (Validators.TryGetValue(type, out var validator)) - return validator; - - // find validators - var finding = type; - while (finding != null && typeof(IStaticValidated).IsAssignableFrom(finding)) - { - if (Validators.TryGetValue(finding, out validator)) - break; - - finding = finding.BaseType; - } - - if (validator == null) + foreach (var component in root.GetComponentsInChildren(true)) { - // if not found, make warning and set empty validator - Debug.LogWarning($"The StaticValidator for {type} not found. This must be a bug of {type.Assembly}"); - validator = _ => { }; + switch (component) + { + case MergePhysBone mergePhysBone: + { + MergePhysBoneValidator.Validate(mergePhysBone); + break; + } + case MergeSkinnedMesh mergeSkinnedMesh: + { + var smr = mergeSkinnedMesh.GetComponent(); + if (smr.sharedMesh) + BuildReport.LogWarning("MergeSkinnedMesh:warning:MeshIsNotNone"); + + if (mergeSkinnedMesh.renderersSet.GetAsSet().Contains(smr)) + BuildReport.LogError("MergeSkinnedMesh:validation:self-recursive"); + break; + } + case MergeBone mergeBone: + { + MergeBoneProcessor.Validate(mergeBone, root); + break; + } + case AvatarGlobalComponent _: + { + if (component.transform != root.transform) +#if AAO_VRCSDK3_AVATARS + BuildReport.LogError("AvatarGlobalComponent:NotOnAvatarDescriptor"); +#else + BuildReport.LogError("AvatarGlobalComponent:NotOnAvatarRoot"); +#endif + break; + } + } } - - Validators.Add(type, validator); - return validator; - } - - /// - /// Registers validator. - /// - /// The validator to be registered. - /// - /// If the type is invalid. The type is invalid if - ///
      - ///
    • The type is interface
    • - ///
    • The type is static class
    • - ///
    • The type does not implements IStaticValidated, or
    • - ///
    • The type implements ISelfStaticValidated
    • - ///
    - ///
    - public static void RegisterValidator(Action validator) - where T : IStaticValidated - { - RegisterValidator(typeof(T), x => validator((T)x)); - } - - /// - /// Registers validator for the specified type. - /// - /// The type validator is for. - /// The validator to be registered. - /// - /// If the type is invalid. The type is invalid if - ///
      - ///
    • The type is interface
    • - ///
    • The type is static class
    • - ///
    • The type does not implements IStaticValidated, or
    • - ///
    - ///
    - public static void RegisterValidator([NotNull] Type type, [NotNull] Validator validator) - { - if (type == null) throw new ArgumentNullException(nameof(type)); - if (validator == null) throw new ArgumentNullException(nameof(validator)); - if (type.IsInterface) - throw new ArgumentException("You cannot register Validator for interfaces."); - if (type.IsSealed && type.IsAbstract) - throw new ArgumentException("You cannot register Validator for static class."); - if (!typeof(IStaticValidated).IsAssignableFrom(type)) - throw new ArgumentException( - "You cannot register Validator for class does not implements IStaticValidated."); - - Validators.Add(type, validator); } } } diff --git a/Editor/MergePhysBoneEditor.cs b/Editor/MergePhysBoneEditor.cs index 82709f30c..3bfd96783 100644 --- a/Editor/MergePhysBoneEditor.cs +++ b/Editor/MergePhysBoneEditor.cs @@ -546,18 +546,12 @@ private static int PopupNoIndent(Rect position, int selectedIndex, string[] disp } } - [InitializeOnLoad] sealed class MergePhysBoneValidator : MergePhysBoneEditorModificationUtils { private readonly List _differProps = new List(); private readonly MergePhysBone _mergePhysBone; - static MergePhysBoneValidator() - { - ComponentValidation.RegisterValidator(Validate); - } - - private static void Validate(MergePhysBone mergePhysBone) + internal static void Validate(MergePhysBone mergePhysBone) { if (mergePhysBone.makeParent && mergePhysBone.transform.childCount != 0) BuildReport.LogError("MergePhysBone:error:makeParentWithChildren", mergePhysBone); diff --git a/Editor/MergeSkinnedMeshEditor.cs b/Editor/MergeSkinnedMeshEditor.cs index b60aea0c9..64f97764e 100644 --- a/Editor/MergeSkinnedMeshEditor.cs +++ b/Editor/MergeSkinnedMeshEditor.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using System.Linq; -using Anatawa12.AvatarOptimizer.ErrorReporting; using CustomLocalization4EditorExtension; using UnityEditor; using UnityEngine; @@ -8,7 +7,6 @@ namespace Anatawa12.AvatarOptimizer { [CustomEditor(typeof(MergeSkinnedMesh))] - [InitializeOnLoad] internal class MergeSkinnedMeshEditor : AvatarTagComponentEditorBase { private static class Style @@ -26,19 +24,6 @@ private static class Style }; } - static MergeSkinnedMeshEditor() - { - ComponentValidation.RegisterValidator(component => - { - var smr = component.GetComponent(); - if (smr.sharedMesh) - BuildReport.LogWarning("MergeSkinnedMesh:warning:MeshIsNotNone"); - - if (component.renderersSet.GetAsSet().Contains(smr)) - BuildReport.LogError("MergeSkinnedMesh:validation:self-recursive"); - }); - } - SerializedProperty _renderersSetProp; SerializedProperty _staticRenderersSetProp; SerializedProperty _removeEmptyRendererObjectProp; diff --git a/Editor/Processors/MergeBoneProcessor.cs b/Editor/Processors/MergeBoneProcessor.cs index 8dbca4f5c..0846c178e 100644 --- a/Editor/Processors/MergeBoneProcessor.cs +++ b/Editor/Processors/MergeBoneProcessor.cs @@ -5,38 +5,32 @@ using Anatawa12.AvatarOptimizer.Processors.SkinnedMeshes; using JetBrains.Annotations; using nadena.dev.ndmf; -using UnityEditor; using UnityEngine; using VRC.Dynamics; -using VRC.SDKBase; using Object = UnityEngine.Object; namespace Anatawa12.AvatarOptimizer.Processors { internal class MergeBoneProcessor : Pass { - [InitializeOnLoadMethod] - private static void RegisterValidator() + public static void Validate(MergeBone mergeBone, GameObject root) { - ComponentValidation.RegisterValidator(mergeBone => + // TODO: use AvatarRoot API + if (mergeBone.transform == root.transform) { - // TODO: use AvatarRoot API - if (mergeBone.GetComponent()) - { - BuildReport.LogError("MergeBone:validation:onAvatarRoot"); - } + BuildReport.LogError("MergeBone:validation:onAvatarRoot"); + } - if (mergeBone.GetComponents().Except(new Component[] { mergeBone, mergeBone.transform }) - .Any()) - BuildReport.LogWarning("MergeBone:validation:thereAreComponent"); + if (mergeBone.GetComponents().Except(new Component[] { mergeBone, mergeBone.transform }) + .Any()) + BuildReport.LogWarning("MergeBone:validation:thereAreComponent"); - if (AnyNotMergedBone(mergeBone.transform)) - { - // if the bone has non-merged bones, uneven scaling is not supported. - if (!ScaledEvenly(mergeBone.transform.localScale)) - BuildReport.LogWarning("MergeBone:validation:unevenScaling"); - } - }); + if (AnyNotMergedBone(mergeBone.transform)) + { + // if the bone has non-merged bones, uneven scaling is not supported. + if (!ScaledEvenly(mergeBone.transform.localScale)) + BuildReport.LogWarning("MergeBone:validation:unevenScaling"); + } bool AnyNotMergedBone(Transform bone) { diff --git a/Runtime/AvatarGlobalComponent.cs b/Runtime/AvatarGlobalComponent.cs index 4dbf08b31..564c47e4a 100644 --- a/Runtime/AvatarGlobalComponent.cs +++ b/Runtime/AvatarGlobalComponent.cs @@ -1,12 +1,10 @@ -using Anatawa12.AvatarOptimizer.ErrorReporting; - namespace Anatawa12.AvatarOptimizer { /// /// Base class for Avatar-Global configurations /// /// - abstract class AvatarGlobalComponent : AvatarTagComponent, IStaticValidated + abstract class AvatarGlobalComponent : AvatarTagComponent { } } diff --git a/Runtime/AvatarTagComponent.cs b/Runtime/AvatarTagComponent.cs index f359a328f..dd2406a82 100644 --- a/Runtime/AvatarTagComponent.cs +++ b/Runtime/AvatarTagComponent.cs @@ -1,4 +1,3 @@ -using Anatawa12.AvatarOptimizer.ErrorReporting; using nadena.dev.ndmf.runtime; using UnityEngine; diff --git a/Runtime/IStaticValidated.cs b/Runtime/IStaticValidated.cs deleted file mode 100644 index 240a48af6..000000000 --- a/Runtime/IStaticValidated.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace Anatawa12.AvatarOptimizer.ErrorReporting -{ - /// - /// The marker interface for components to be validated. - /// You must register validator to ComponentValidation. - /// - internal interface IStaticValidated - { - // TODO: remove this interface - } -} diff --git a/Runtime/IStaticValidated.cs.meta b/Runtime/IStaticValidated.cs.meta deleted file mode 100644 index 4b952e59c..000000000 --- a/Runtime/IStaticValidated.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: e076f25aaf2347d9a6e4f5daa829da92 -timeCreated: 1682932807 \ No newline at end of file diff --git a/Runtime/MergeBone.cs b/Runtime/MergeBone.cs index 1541413eb..16e95162f 100644 --- a/Runtime/MergeBone.cs +++ b/Runtime/MergeBone.cs @@ -1,4 +1,3 @@ -using Anatawa12.AvatarOptimizer.ErrorReporting; using CustomLocalization4EditorExtension; using UnityEngine; using UnityEngine.Animations; @@ -8,7 +7,7 @@ namespace Anatawa12.AvatarOptimizer [AddComponentMenu("Avatar Optimizer/AAO Merge Bone")] [DisallowMultipleComponent] [HelpURL("https://vpm.anatawa12.com/avatar-optimizer/ja/docs/reference/merge-bone/")] - internal class MergeBone : AvatarTagComponent, IStaticValidated + internal class MergeBone : AvatarTagComponent { [NotKeyable, CL4EELocalized("MergeBone:prop:avoidNameConflict", "MergeBone:tooltip:avoidNameConflict")] [ToggleLeft] diff --git a/Runtime/MergePhysBone.cs b/Runtime/MergePhysBone.cs index 2fce4eb19..f433f5995 100644 --- a/Runtime/MergePhysBone.cs +++ b/Runtime/MergePhysBone.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; -using Anatawa12.AvatarOptimizer.ErrorReporting; using CustomLocalization4EditorExtension; using JetBrains.Annotations; using UnityEngine; @@ -15,7 +14,7 @@ namespace Anatawa12.AvatarOptimizer [DisallowMultipleComponent] [ExecuteAlways] [HelpURL("https://vpm.anatawa12.com/avatar-optimizer/ja/docs/reference/merge-physbone/")] - internal class MergePhysBone : AvatarTagComponent, IStaticValidated + internal class MergePhysBone : AvatarTagComponent { [NotKeyable] [CL4EELocalized("MergePhysBone:prop:makeParent", "MergePhysBone:tooltip:makeParent")] diff --git a/Runtime/MergeSkinnedMesh.cs b/Runtime/MergeSkinnedMesh.cs index 843ef3c8a..b3e119fdc 100644 --- a/Runtime/MergeSkinnedMesh.cs +++ b/Runtime/MergeSkinnedMesh.cs @@ -1,4 +1,3 @@ -using Anatawa12.AvatarOptimizer.ErrorReporting; using CustomLocalization4EditorExtension; using UnityEngine; using UnityEngine.Animations; @@ -9,7 +8,7 @@ namespace Anatawa12.AvatarOptimizer [RequireComponent(typeof(SkinnedMeshRenderer))] [DisallowMultipleComponent] [HelpURL("https://vpm.anatawa12.com/avatar-optimizer/ja/docs/reference/merge-skinned-mesh/")] - internal class MergeSkinnedMesh : EditSkinnedMeshComponent, IStaticValidated + internal class MergeSkinnedMesh : EditSkinnedMeshComponent { [CL4EELocalized("MergeSkinnedMesh:prop:renderers")] public PrefabSafeSet.SkinnedMeshRendererSet renderersSet; From a57a960eccce89e22855a738ae063761ab07fea7 Mon Sep 17 00:00:00 2001 From: anatawa12 Date: Thu, 28 Dec 2023 04:06:08 +0900 Subject: [PATCH 05/10] chore: BuildReport -> BuildLog --- Editor/APIInternal/ComponentInfos.VRCSDK.cs | 18 +++++++++--------- Editor/APIInternal/ComponentInfos.VRM0.cs | 2 +- Editor/AnimatorParsers/AnimationParser.cs | 4 ++-- Editor/AnimatorParsers/AnimatorParser.cs | 8 ++------ .../{BuildReport.cs => BuildLog.cs} | 2 +- .../{BuildReport.cs.meta => BuildLog.cs.meta} | 0 Editor/ErrorReporting/ComponentValidation.cs | 6 +++--- Editor/MergePhysBoneEditor.cs | 12 ++++++------ Editor/ObjectMapping/ObjectMappingContext.cs | 2 +- Editor/OptimizerPlugin.cs | 2 +- Editor/Processors/MergeBoneProcessor.cs | 6 +++--- .../SkinnedMeshes/FreezeBlendShapeProcessor.cs | 2 +- .../SkinnedMeshes/MergeSkinnedMeshProcessor.cs | 8 ++++---- Editor/Processors/SkinnedMeshes/MeshInfo2.cs | 4 ++-- .../ComponentDependencyCollector.cs | 2 +- .../TraceAndOptimize/OptimizePhysBone.cs | 2 +- 16 files changed, 38 insertions(+), 42 deletions(-) rename Editor/ErrorReporting/{BuildReport.cs => BuildLog.cs} (98%) rename Editor/ErrorReporting/{BuildReport.cs.meta => BuildLog.cs.meta} (100%) diff --git a/Editor/APIInternal/ComponentInfos.VRCSDK.cs b/Editor/APIInternal/ComponentInfos.VRCSDK.cs index f0218ae10..348495ab9 100644 --- a/Editor/APIInternal/ComponentInfos.VRCSDK.cs +++ b/Editor/APIInternal/ComponentInfos.VRCSDK.cs @@ -62,7 +62,7 @@ protected override void CollectMutations(T component, ComponentMutationsCollecto collector.ModifyProperties(component.VisemeSkinnedMesh, $"blendShape.{component.MouthOpenBlendShapeName}"); } else { - BuildReport.LogWarning("ComponentInfos:VRCAvatarDescriptor:warning:NoVisemeSkinnedMesh", component); + BuildLog.LogWarning("ComponentInfos:VRCAvatarDescriptor:warning:NoVisemeSkinnedMesh", component); } break; } @@ -73,7 +73,7 @@ protected override void CollectMutations(T component, ComponentMutationsCollecto collector.ModifyProperties(component.VisemeSkinnedMesh, component.VisemeBlendShapes.Select(blendShape => $"blendShape.{blendShape}")); } else { - BuildReport.LogWarning("ComponentInfos:VRCAvatarDescriptor:warning:NoVisemeSkinnedMesh", component); + BuildLog.LogWarning("ComponentInfos:VRCAvatarDescriptor:warning:NoVisemeSkinnedMesh", component); } break; } @@ -81,7 +81,7 @@ protected override void CollectMutations(T component, ComponentMutationsCollecto // NOP break; default: - BuildReport.LogWarning("ComponentInfos:VRCAvatarDescriptor:warning:UnknownLipSyncStyle", + BuildLog.LogWarning("ComponentInfos:VRCAvatarDescriptor:warning:UnknownLipSyncStyle", component.lipSync.ToString(), component); break; @@ -128,7 +128,7 @@ protected override void ApplySpecialMapping(T component, MappingSource mappingSo removed = true; } if (removed) - BuildReport.LogError("ApplyObjectMapping:VRCAvatarDescriptor:viseme BlendShape Removed"); + BuildLog.LogError("ApplyObjectMapping:VRCAvatarDescriptor:viseme BlendShape Removed"); break; } case VRC_AvatarDescriptor.LipSyncStyle.VisemeParameterOnly: @@ -180,7 +180,7 @@ void AddCollider(VRCAvatarDescriptor.ColliderConfig collider, string where) case VRCAvatarDescriptor.ColliderConfig.State.Disabled: break; default: - BuildReport.LogWarning("ComponentInfos:VRCAvatarDescriptor:warning:UnknownColliderState", + BuildLog.LogWarning("ComponentInfos:VRCAvatarDescriptor:warning:UnknownColliderState", collider.ToString(), where, component); break; @@ -232,19 +232,19 @@ from index in component.customEyeLookSettings.eyelidsBlendshapes } else { - BuildReport.LogWarning("ComponentInfos:VRCAvatarDescriptor:warning:NoMeshInEyelidsSkinnedMesh", + BuildLog.LogWarning("ComponentInfos:VRCAvatarDescriptor:warning:NoMeshInEyelidsSkinnedMesh", component); } } else { - BuildReport.LogWarning("ComponentInfos:VRCAvatarDescriptor:warning:NoEyelidsSkinnedMesh", + BuildLog.LogWarning("ComponentInfos:VRCAvatarDescriptor:warning:NoEyelidsSkinnedMesh", component); } } break; default: - BuildReport.LogWarning("ComponentInfos:VRCAvatarDescriptor:warning:UnknownEyelidType", + BuildLog.LogWarning("ComponentInfos:VRCAvatarDescriptor:warning:UnknownEyelidType", component.customEyeLookSettings.eyelidType.ToString(), component); break; @@ -280,7 +280,7 @@ protected override void ApplySpecialMapping(VRCAvatarDescriptor component, Mappi } if (removed) - BuildReport.LogError("ApplyObjectMapping:VRCAvatarDescriptor:eyelids BlendShape Removed"); + BuildLog.LogError("ApplyObjectMapping:VRCAvatarDescriptor:eyelids BlendShape Removed"); } break; default: diff --git a/Editor/APIInternal/ComponentInfos.VRM0.cs b/Editor/APIInternal/ComponentInfos.VRM0.cs index 753614b32..8fddc5d2b 100644 --- a/Editor/APIInternal/ComponentInfos.VRM0.cs +++ b/Editor/APIInternal/ComponentInfos.VRM0.cs @@ -152,7 +152,7 @@ protected override void ApplySpecialMapping(VRMFirstPerson component, MappingSou else { mergedFirstPersonFlag = firstPersonFlags.Contains(FirstPersonFlag.Both) ? FirstPersonFlag.Both : FirstPersonFlag.Auto; - BuildReport.LogWarning("MergeSkinnedMesh:warning:VRM:FirstPersonFlagsMismatch", mergedFirstPersonFlag.ToString()); + BuildLog.LogWarning("MergeSkinnedMesh:warning:VRM:FirstPersonFlagsMismatch", mergedFirstPersonFlag.ToString()); } return new VRMFirstPerson.RendererFirstPersonFlags diff --git a/Editor/AnimatorParsers/AnimationParser.cs b/Editor/AnimatorParsers/AnimationParser.cs index c3c02da42..7a403a759 100644 --- a/Editor/AnimatorParsers/AnimationParser.cs +++ b/Editor/AnimatorParsers/AnimationParser.cs @@ -6,7 +6,7 @@ using UnityEditor; using UnityEditor.Animations; using UnityEngine; -using static Anatawa12.AvatarOptimizer.ErrorReporting.BuildReport; +using Anatawa12.AvatarOptimizer.ErrorReporting; namespace Anatawa12.AvatarOptimizer.AnimatorParsers { @@ -31,7 +31,7 @@ private IModificationsContainer ParseMotionInner(GameObject root, Motion motion, case BlendTree blendTree: return ParseBlendTree(root, blendTree, mapping); default: - LogError("Unknown Motion Type: {0} in motion {1}", motion.GetType().Name, motion.name); + BuildLog.LogError("Unknown Motion Type: {0} in motion {1}", motion.GetType().Name, motion.name); return ImmutableModificationsContainer.Empty; } } diff --git a/Editor/AnimatorParsers/AnimatorParser.cs b/Editor/AnimatorParsers/AnimatorParser.cs index 5b55d1490..70fb25973 100644 --- a/Editor/AnimatorParsers/AnimatorParser.cs +++ b/Editor/AnimatorParsers/AnimatorParser.cs @@ -4,16 +4,12 @@ using Anatawa12.AvatarOptimizer.API; using Anatawa12.AvatarOptimizer.APIInternal; using Anatawa12.AvatarOptimizer.ErrorReporting; -using static Anatawa12.AvatarOptimizer.ErrorReporting.BuildReport; using JetBrains.Annotations; using nadena.dev.ndmf; using UnityEditor.Animations; using UnityEngine; -using UnityEngine.Animations; -using Object = UnityEngine.Object; #if AAO_VRCSDK3_AVATARS -using VRC.Dynamics; using VRC.SDK3.Avatars.Components; using VRC.SDKBase; #endif @@ -319,7 +315,7 @@ void CollectWeightChangesInBehaviors(StateMachineBehaviour[] stateBehaviours) layer = VRCAvatarDescriptor.AnimLayerType.Additive; break; default: - LogWarning("AnimatorParser:PlayableLayerControl:UnknownBlendablePlayableLayer", + BuildLog.LogWarning("AnimatorParser:PlayableLayerControl:UnknownBlendablePlayableLayer", $"{playableLayerControl.layer}", stateMachineBehaviour); continue; @@ -348,7 +344,7 @@ void CollectWeightChangesInBehaviors(StateMachineBehaviour[] stateBehaviours) layer = VRCAvatarDescriptor.AnimLayerType.Additive; break; default: - LogWarning("AnimatorParser:AnimatorLayerControl:UnknownBlendablePlayableLayer", + BuildLog.LogWarning("AnimatorParser:AnimatorLayerControl:UnknownBlendablePlayableLayer", $"{animatorLayerControl.layer}", stateMachineBehaviour); continue; diff --git a/Editor/ErrorReporting/BuildReport.cs b/Editor/ErrorReporting/BuildLog.cs similarity index 98% rename from Editor/ErrorReporting/BuildReport.cs rename to Editor/ErrorReporting/BuildLog.cs index f1e0f8520..798da5acf 100644 --- a/Editor/ErrorReporting/BuildReport.cs +++ b/Editor/ErrorReporting/BuildLog.cs @@ -9,7 +9,7 @@ namespace Anatawa12.AvatarOptimizer.ErrorReporting { - internal static class BuildReport + internal static class BuildLog { public static void LogInfo(string code, params object[] args) => ErrorReport.ReportError(new InlineError(ErrorSeverity.Information, code, args)); diff --git a/Editor/ErrorReporting/BuildReport.cs.meta b/Editor/ErrorReporting/BuildLog.cs.meta similarity index 100% rename from Editor/ErrorReporting/BuildReport.cs.meta rename to Editor/ErrorReporting/BuildLog.cs.meta diff --git a/Editor/ErrorReporting/ComponentValidation.cs b/Editor/ErrorReporting/ComponentValidation.cs index c5fece566..633c5ae99 100644 --- a/Editor/ErrorReporting/ComponentValidation.cs +++ b/Editor/ErrorReporting/ComponentValidation.cs @@ -20,10 +20,10 @@ public static void ValidateAll(GameObject root) { var smr = mergeSkinnedMesh.GetComponent(); if (smr.sharedMesh) - BuildReport.LogWarning("MergeSkinnedMesh:warning:MeshIsNotNone"); + BuildLog.LogWarning("MergeSkinnedMesh:warning:MeshIsNotNone"); if (mergeSkinnedMesh.renderersSet.GetAsSet().Contains(smr)) - BuildReport.LogError("MergeSkinnedMesh:validation:self-recursive"); + BuildLog.LogError("MergeSkinnedMesh:validation:self-recursive"); break; } case MergeBone mergeBone: @@ -35,7 +35,7 @@ public static void ValidateAll(GameObject root) { if (component.transform != root.transform) #if AAO_VRCSDK3_AVATARS - BuildReport.LogError("AvatarGlobalComponent:NotOnAvatarDescriptor"); + BuildLog.LogError("AvatarGlobalComponent:NotOnAvatarDescriptor"); #else BuildReport.LogError("AvatarGlobalComponent:NotOnAvatarRoot"); #endif diff --git a/Editor/MergePhysBoneEditor.cs b/Editor/MergePhysBoneEditor.cs index 3bfd96783..c3701b815 100644 --- a/Editor/MergePhysBoneEditor.cs +++ b/Editor/MergePhysBoneEditor.cs @@ -554,7 +554,7 @@ sealed class MergePhysBoneValidator : MergePhysBoneEditorModificationUtils internal static void Validate(MergePhysBone mergePhysBone) { if (mergePhysBone.makeParent && mergePhysBone.transform.childCount != 0) - BuildReport.LogError("MergePhysBone:error:makeParentWithChildren", mergePhysBone); + BuildLog.LogError("MergePhysBone:error:makeParentWithChildren", mergePhysBone); new MergePhysBoneValidator(mergePhysBone).DoProcess(); } @@ -572,11 +572,11 @@ private static void Void() protected override void EndPbConfig() { if (_differProps.Count != 0) { - BuildReport.LogError("MergePhysBone:error:differValues", string.Join(", ", _differProps)); + BuildLog.LogError("MergePhysBone:error:differValues", string.Join(", ", _differProps)); } } - protected override void NoSource() => BuildReport.LogError("MergePhysBone:error:noSources"); + protected override void NoSource() => BuildLog.LogError("MergePhysBone:error:noSources"); protected override void TransformSection() { @@ -587,7 +587,7 @@ protected override void TransformSection() .ZipWithNext() .Any(x => x.Item1 != x.Item2); if (differ) - BuildReport.LogError("MergePhysBone:error:parentDiffer"); + BuildLog.LogError("MergePhysBone:error:parentDiffer"); } if (EndpointPosition.OverrideProperty.enumValueIndex == @@ -599,13 +599,13 @@ protected override void TransformSection() var multiChildType = GetSourceProperty(nameof(VRCPhysBoneBase.multiChildType)); if (multiChildType.enumValueIndex != 0 || multiChildType.hasMultipleDifferentValues) - BuildReport.LogError("MergePhysBone:error:multiChildType"); + BuildLog.LogError("MergePhysBone:error:multiChildType"); } protected override void OptionParameter() => Void(); protected override void OptionIsAnimated() => Void(); - protected override void UnsupportedPbVersion() => BuildReport.LogError("MergePhysBone:error:unsupportedPbVersion"); + protected override void UnsupportedPbVersion() => BuildLog.LogError("MergePhysBone:error:unsupportedPbVersion"); protected override void PbVersionProp(string label, ValueConfigProp prop, bool forceOverride = false) => PbProp(label, prop, forceOverride); diff --git a/Editor/ObjectMapping/ObjectMappingContext.cs b/Editor/ObjectMapping/ObjectMappingContext.cs index 75b516ffe..21e78a94e 100644 --- a/Editor/ObjectMapping/ObjectMappingContext.cs +++ b/Editor/ObjectMapping/ObjectMappingContext.cs @@ -367,7 +367,7 @@ private Object CustomClone(Object o) else { mergedFirstPersonFlag = firstPersonFlags.Contains(UniGLTF.Extensions.VRMC_vrm.FirstPersonType.both) ? UniGLTF.Extensions.VRMC_vrm.FirstPersonType.both : UniGLTF.Extensions.VRMC_vrm.FirstPersonType.auto; - BuildReport.LogWarning("MergeSkinnedMesh:warning:VRM:FirstPersonFlagsMismatch", mergedFirstPersonFlag.ToString()); + BuildLog.LogWarning("MergeSkinnedMesh:warning:VRM:FirstPersonFlagsMismatch", mergedFirstPersonFlag.ToString()); } return new UniVRM10.RendererFirstPersonFlags diff --git a/Editor/OptimizerPlugin.cs b/Editor/OptimizerPlugin.cs index 08897e740..12a04510c 100644 --- a/Editor/OptimizerPlugin.cs +++ b/Editor/OptimizerPlugin.cs @@ -23,7 +23,7 @@ protected override void Configure() // we skip check for update var components = ctx.AvatarRootObject.GetComponentInChildren(true); if (components && CheckForUpdate.OutOfDate) - BuildReport.LogInfo("CheckForUpdate:out-of-date", + BuildLog.LogInfo("CheckForUpdate:out-of-date", CheckForUpdate.LatestVersionName, CheckForUpdate.CurrentVersionName); }) .Then.Run(Processors.UnusedBonesByReferencesToolEarlyProcessor.Instance) diff --git a/Editor/Processors/MergeBoneProcessor.cs b/Editor/Processors/MergeBoneProcessor.cs index 0846c178e..ff073f919 100644 --- a/Editor/Processors/MergeBoneProcessor.cs +++ b/Editor/Processors/MergeBoneProcessor.cs @@ -18,18 +18,18 @@ public static void Validate(MergeBone mergeBone, GameObject root) // TODO: use AvatarRoot API if (mergeBone.transform == root.transform) { - BuildReport.LogError("MergeBone:validation:onAvatarRoot"); + BuildLog.LogError("MergeBone:validation:onAvatarRoot"); } if (mergeBone.GetComponents().Except(new Component[] { mergeBone, mergeBone.transform }) .Any()) - BuildReport.LogWarning("MergeBone:validation:thereAreComponent"); + BuildLog.LogWarning("MergeBone:validation:thereAreComponent"); if (AnyNotMergedBone(mergeBone.transform)) { // if the bone has non-merged bones, uneven scaling is not supported. if (!ScaledEvenly(mergeBone.transform.localScale)) - BuildReport.LogWarning("MergeBone:validation:unevenScaling"); + BuildLog.LogWarning("MergeBone:validation:unevenScaling"); } bool AnyNotMergedBone(Transform bone) diff --git a/Editor/Processors/SkinnedMeshes/FreezeBlendShapeProcessor.cs b/Editor/Processors/SkinnedMeshes/FreezeBlendShapeProcessor.cs index a3d7adc59..f8b66e1a0 100644 --- a/Editor/Processors/SkinnedMeshes/FreezeBlendShapeProcessor.cs +++ b/Editor/Processors/SkinnedMeshes/FreezeBlendShapeProcessor.cs @@ -54,7 +54,7 @@ public static void FreezeBlendShapes( if (modified.Count != 0) { // ReSharper disable once CoVariantArrayConversion - BuildReport.LogWarning("FreezeBlendShape:warning:animation", string.Join(", ", modified), + BuildLog.LogWarning("FreezeBlendShape:warning:animation", string.Join(", ", modified), targetSMR, sources); } } diff --git a/Editor/Processors/SkinnedMeshes/MergeSkinnedMeshProcessor.cs b/Editor/Processors/SkinnedMeshes/MergeSkinnedMeshProcessor.cs index 313df6a3e..ec5020338 100644 --- a/Editor/Processors/SkinnedMeshes/MergeSkinnedMeshProcessor.cs +++ b/Editor/Processors/SkinnedMeshes/MergeSkinnedMeshProcessor.cs @@ -92,7 +92,7 @@ bool RendererEnabled(Renderer x) { // collect (skinned) mesh renderers who doesn't have normal // to show the list on the error reporting - BuildReport.LogError("MergeSkinnedMesh:error:mix-normal-existence", + BuildLog.LogError("MergeSkinnedMesh:error:mix-normal-existence", from meshInfo2 in meshInfos where meshInfo2.Vertices.Count != 0 && !meshInfo2.HasNormals select meshInfo2.SourceRenderer); @@ -206,7 +206,7 @@ TexCoordStatus TexCoordStatusMax(TexCoordStatus x, TexCoordStatus y) => #endif foreach (var weightMismatchBlendShape in weightMismatchBlendShapes) - BuildReport.LogWarning("MergeSkinnedMesh:warning:blendShapeWeightMismatch", weightMismatchBlendShape); + BuildLog.LogWarning("MergeSkinnedMesh:warning:blendShapeWeightMismatch", weightMismatchBlendShape); if (updateBounds && newBoundMin != Vector3.positiveInfinity && newBoundMax != Vector3.negativeInfinity) { @@ -235,7 +235,7 @@ TexCoordStatus TexCoordStatusMax(TexCoordStatus x, TexCoordStatus y) => var toDestroy = renderer.GetComponent(); if (toDestroy) { - BuildReport.LogWarning("MergeSkinnedMesh:warning:removeZeroSizedPolygonOnSources", toDestroy); + BuildLog.LogWarning("MergeSkinnedMesh:warning:removeZeroSizedPolygonOnSources", toDestroy); Object.DestroyImmediate(toDestroy); } Object.DestroyImmediate(renderer); @@ -304,7 +304,7 @@ private void ActivenessAnimationWarning(Renderer renderer, BuildContext context, } if (sources.Count != 0) - BuildReport.LogWarning("MergeSkinnedMesh:warning:animation-mesh-hide", sources); + BuildLog.LogWarning("MergeSkinnedMesh:warning:animation-mesh-hide", sources); } private (int[][] mapping, List<(MeshTopology topology, Material material)> materials) diff --git a/Editor/Processors/SkinnedMeshes/MeshInfo2.cs b/Editor/Processors/SkinnedMeshes/MeshInfo2.cs index a8cd9eafd..69e0ddc16 100644 --- a/Editor/Processors/SkinnedMeshes/MeshInfo2.cs +++ b/Editor/Processors/SkinnedMeshes/MeshInfo2.cs @@ -420,7 +420,7 @@ public void FlattenMultiPassRendering(string reasonComponent) { if (SubMeshes.All(x => x.SharedMaterials.Length == 1)) return; - BuildReport.LogWarning("MeshInfo2:warning:multiPassRendering", reasonComponent, SourceRenderer); + BuildLog.LogWarning("MeshInfo2:warning:multiPassRendering", reasonComponent, SourceRenderer); // flatten SubMeshes var subMeshes = SubMeshes.ToArray(); @@ -753,7 +753,7 @@ public bool TryGetPrimitiveSize(string component, out int primitiveSize) primitiveSize = 1; return true; case MeshTopology.LineStrip: - BuildReport.LogWarning("MeshInfo2:warning:lineStrip", component); + BuildLog.LogWarning("MeshInfo2:warning:lineStrip", component); primitiveSize = default; return false; default: diff --git a/Editor/Processors/TraceAndOptimize/ComponentDependencyCollector.cs b/Editor/Processors/TraceAndOptimize/ComponentDependencyCollector.cs index 46d5db567..aee0d6254 100644 --- a/Editor/Processors/TraceAndOptimize/ComponentDependencyCollector.cs +++ b/Editor/Processors/TraceAndOptimize/ComponentDependencyCollector.cs @@ -44,7 +44,7 @@ public void CollectAllUsages() } else { - BuildReport.LogWarning("TraceAndOptimize:warn:unknown-type", component.GetType().Name); + BuildLog.LogWarning("TraceAndOptimize:warn:unknown-type", component.GetType().Name); FallbackDependenciesParser(component, collector); } diff --git a/Editor/Processors/TraceAndOptimize/OptimizePhysBone.cs b/Editor/Processors/TraceAndOptimize/OptimizePhysBone.cs index a6fcc9b52..c5e69e193 100644 --- a/Editor/Processors/TraceAndOptimize/OptimizePhysBone.cs +++ b/Editor/Processors/TraceAndOptimize/OptimizePhysBone.cs @@ -107,7 +107,7 @@ bool IsAnimated() }); break; default: - BuildReport.LogWarning("TraceAndOptimize:OptimizePhysBone:UnknownPhysBoneColliderShape", shapeType.ToString(), colliders); + BuildLog.LogWarning("TraceAndOptimize:OptimizePhysBone:UnknownPhysBoneColliderShape", shapeType.ToString(), colliders); break; } } From a1cde74b1a893545cd9c834e1b9cc6a2413aca5d Mon Sep 17 00:00:00 2001 From: anatawa12 Date: Thu, 28 Dec 2023 04:10:35 +0900 Subject: [PATCH 06/10] chore: remove ErrorReporting namespace --- Editor/APIInternal/ComponentInfos.VRCSDK.cs | 1 - Editor/APIInternal/ComponentInfos.VRM0.cs | 1 - Editor/AnimatorParsers/AnimationParser.cs | 1 - Editor/AnimatorParsers/AnimatorParser.cs | 1 - Editor/AnimatorParsers/ModificationSource.cs | 1 - Editor/{ErrorReporting => }/BuildLog.cs | 2 +- Editor/{ErrorReporting => }/BuildLog.cs.meta | 0 Editor/{ErrorReporting => }/ComponentValidation.cs | 2 +- Editor/{ErrorReporting => }/ComponentValidation.cs.meta | 0 Editor/ErrorReporting.meta | 3 --- Editor/MergePhysBoneEditor.cs | 1 - Editor/ObjectMapping/ObjectMappingContext.cs | 1 - Editor/OptimizerPlugin.cs | 1 - Editor/Processors/ClearEndpointPositionProcessor.cs | 1 - Editor/Processors/EditSkinnedMeshComponentProcessor.cs | 1 - Editor/Processors/MakeChildrenProcessor.cs | 1 - Editor/Processors/MergeBoneProcessor.cs | 1 - Editor/Processors/MergePhysBoneProcessor.cs | 1 - Editor/Processors/MeshInfo2Holder.cs | 1 - Editor/Processors/OriginalState.cs | 1 - Editor/Processors/SkinnedMeshes/FreezeBlendShapeProcessor.cs | 1 - Editor/Processors/SkinnedMeshes/MergeSkinnedMeshProcessor.cs | 1 - Editor/Processors/SkinnedMeshes/MeshInfo2.cs | 2 -- Editor/Processors/SkinnedMeshes/RemoveMeshInBoxProcessor.cs | 1 - .../TraceAndOptimize/ComponentDependencyCollector.cs | 1 - Editor/Processors/TraceAndOptimize/OptimizePhysBone.cs | 1 - Editor/Processors/UnusedBonesByReferencesToolEarlyProcessor.cs | 1 - 27 files changed, 2 insertions(+), 28 deletions(-) rename Editor/{ErrorReporting => }/BuildLog.cs (98%) rename Editor/{ErrorReporting => }/BuildLog.cs.meta (100%) rename Editor/{ErrorReporting => }/ComponentValidation.cs (97%) rename Editor/{ErrorReporting => }/ComponentValidation.cs.meta (100%) delete mode 100644 Editor/ErrorReporting.meta diff --git a/Editor/APIInternal/ComponentInfos.VRCSDK.cs b/Editor/APIInternal/ComponentInfos.VRCSDK.cs index 348495ab9..3bffa5072 100644 --- a/Editor/APIInternal/ComponentInfos.VRCSDK.cs +++ b/Editor/APIInternal/ComponentInfos.VRCSDK.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Linq; using Anatawa12.AvatarOptimizer.API; -using Anatawa12.AvatarOptimizer.ErrorReporting; using JetBrains.Annotations; using UnityEngine; using VRC.SDK3; diff --git a/Editor/APIInternal/ComponentInfos.VRM0.cs b/Editor/APIInternal/ComponentInfos.VRM0.cs index 8fddc5d2b..6d1afc571 100644 --- a/Editor/APIInternal/ComponentInfos.VRM0.cs +++ b/Editor/APIInternal/ComponentInfos.VRM0.cs @@ -2,7 +2,6 @@ using System.Linq; using Anatawa12.AvatarOptimizer.API; -using Anatawa12.AvatarOptimizer.ErrorReporting; using UnityEngine; using VRM; diff --git a/Editor/AnimatorParsers/AnimationParser.cs b/Editor/AnimatorParsers/AnimationParser.cs index 7a403a759..ebb379726 100644 --- a/Editor/AnimatorParsers/AnimationParser.cs +++ b/Editor/AnimatorParsers/AnimationParser.cs @@ -6,7 +6,6 @@ using UnityEditor; using UnityEditor.Animations; using UnityEngine; -using Anatawa12.AvatarOptimizer.ErrorReporting; namespace Anatawa12.AvatarOptimizer.AnimatorParsers { diff --git a/Editor/AnimatorParsers/AnimatorParser.cs b/Editor/AnimatorParsers/AnimatorParser.cs index 70fb25973..992fe2ec8 100644 --- a/Editor/AnimatorParsers/AnimatorParser.cs +++ b/Editor/AnimatorParsers/AnimatorParser.cs @@ -3,7 +3,6 @@ using System.Linq; using Anatawa12.AvatarOptimizer.API; using Anatawa12.AvatarOptimizer.APIInternal; -using Anatawa12.AvatarOptimizer.ErrorReporting; using JetBrains.Annotations; using nadena.dev.ndmf; using UnityEditor.Animations; diff --git a/Editor/AnimatorParsers/ModificationSource.cs b/Editor/AnimatorParsers/ModificationSource.cs index aee898157..a169ebde4 100644 --- a/Editor/AnimatorParsers/ModificationSource.cs +++ b/Editor/AnimatorParsers/ModificationSource.cs @@ -1,4 +1,3 @@ -using Anatawa12.AvatarOptimizer.ErrorReporting; using UnityEditor; using UnityEngine; diff --git a/Editor/ErrorReporting/BuildLog.cs b/Editor/BuildLog.cs similarity index 98% rename from Editor/ErrorReporting/BuildLog.cs rename to Editor/BuildLog.cs index 798da5acf..84ef4ca57 100644 --- a/Editor/ErrorReporting/BuildLog.cs +++ b/Editor/BuildLog.cs @@ -7,7 +7,7 @@ using UnityEngine; using Object = UnityEngine.Object; -namespace Anatawa12.AvatarOptimizer.ErrorReporting +namespace Anatawa12.AvatarOptimizer { internal static class BuildLog { diff --git a/Editor/ErrorReporting/BuildLog.cs.meta b/Editor/BuildLog.cs.meta similarity index 100% rename from Editor/ErrorReporting/BuildLog.cs.meta rename to Editor/BuildLog.cs.meta diff --git a/Editor/ErrorReporting/ComponentValidation.cs b/Editor/ComponentValidation.cs similarity index 97% rename from Editor/ErrorReporting/ComponentValidation.cs rename to Editor/ComponentValidation.cs index 633c5ae99..885438df3 100644 --- a/Editor/ErrorReporting/ComponentValidation.cs +++ b/Editor/ComponentValidation.cs @@ -1,7 +1,7 @@ using Anatawa12.AvatarOptimizer.Processors; using UnityEngine; -namespace Anatawa12.AvatarOptimizer.ErrorReporting +namespace Anatawa12.AvatarOptimizer { internal static class ComponentValidation { diff --git a/Editor/ErrorReporting/ComponentValidation.cs.meta b/Editor/ComponentValidation.cs.meta similarity index 100% rename from Editor/ErrorReporting/ComponentValidation.cs.meta rename to Editor/ComponentValidation.cs.meta diff --git a/Editor/ErrorReporting.meta b/Editor/ErrorReporting.meta deleted file mode 100644 index f9c19c155..000000000 --- a/Editor/ErrorReporting.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 1b10606d90a949c8aee9446bc6087162 -timeCreated: 1703701376 \ No newline at end of file diff --git a/Editor/MergePhysBoneEditor.cs b/Editor/MergePhysBoneEditor.cs index c3701b815..fba07e4b7 100644 --- a/Editor/MergePhysBoneEditor.cs +++ b/Editor/MergePhysBoneEditor.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; using System.Linq; -using Anatawa12.AvatarOptimizer.ErrorReporting; using CustomLocalization4EditorExtension; using JetBrains.Annotations; using UnityEditor; diff --git a/Editor/ObjectMapping/ObjectMappingContext.cs b/Editor/ObjectMapping/ObjectMappingContext.cs index 21e78a94e..7489e6f6f 100644 --- a/Editor/ObjectMapping/ObjectMappingContext.cs +++ b/Editor/ObjectMapping/ObjectMappingContext.cs @@ -3,7 +3,6 @@ using System.Linq; using Anatawa12.AvatarOptimizer.API; using Anatawa12.AvatarOptimizer.APIInternal; -using Anatawa12.AvatarOptimizer.ErrorReporting; using JetBrains.Annotations; using nadena.dev.ndmf; using UnityEditor; diff --git a/Editor/OptimizerPlugin.cs b/Editor/OptimizerPlugin.cs index 12a04510c..5df3acf5e 100644 --- a/Editor/OptimizerPlugin.cs +++ b/Editor/OptimizerPlugin.cs @@ -1,5 +1,4 @@ using System; -using Anatawa12.AvatarOptimizer.ErrorReporting; using Anatawa12.AvatarOptimizer.ndmf; using nadena.dev.ndmf; using nadena.dev.ndmf.builtin; diff --git a/Editor/Processors/ClearEndpointPositionProcessor.cs b/Editor/Processors/ClearEndpointPositionProcessor.cs index d7872a1b1..12332d805 100644 --- a/Editor/Processors/ClearEndpointPositionProcessor.cs +++ b/Editor/Processors/ClearEndpointPositionProcessor.cs @@ -1,7 +1,6 @@ #if AAO_VRCSDK3_AVATARS using System; -using Anatawa12.AvatarOptimizer.ErrorReporting; using nadena.dev.ndmf; using UnityEditor; using UnityEngine; diff --git a/Editor/Processors/EditSkinnedMeshComponentProcessor.cs b/Editor/Processors/EditSkinnedMeshComponentProcessor.cs index 903af198c..58fd37980 100644 --- a/Editor/Processors/EditSkinnedMeshComponentProcessor.cs +++ b/Editor/Processors/EditSkinnedMeshComponentProcessor.cs @@ -1,4 +1,3 @@ -using Anatawa12.AvatarOptimizer.ErrorReporting; using Anatawa12.AvatarOptimizer.ndmf; using nadena.dev.ndmf; using UnityEngine; diff --git a/Editor/Processors/MakeChildrenProcessor.cs b/Editor/Processors/MakeChildrenProcessor.cs index c0405afb2..9aac8234c 100644 --- a/Editor/Processors/MakeChildrenProcessor.cs +++ b/Editor/Processors/MakeChildrenProcessor.cs @@ -1,4 +1,3 @@ -using Anatawa12.AvatarOptimizer.ErrorReporting; using System.Linq; using nadena.dev.ndmf; using UnityEngine; diff --git a/Editor/Processors/MergeBoneProcessor.cs b/Editor/Processors/MergeBoneProcessor.cs index ff073f919..44a14216c 100644 --- a/Editor/Processors/MergeBoneProcessor.cs +++ b/Editor/Processors/MergeBoneProcessor.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using Anatawa12.AvatarOptimizer.ErrorReporting; using Anatawa12.AvatarOptimizer.Processors.SkinnedMeshes; using JetBrains.Annotations; using nadena.dev.ndmf; diff --git a/Editor/Processors/MergePhysBoneProcessor.cs b/Editor/Processors/MergePhysBoneProcessor.cs index c71afb646..e3144e5cf 100644 --- a/Editor/Processors/MergePhysBoneProcessor.cs +++ b/Editor/Processors/MergePhysBoneProcessor.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; using System.Linq; -using Anatawa12.AvatarOptimizer.ErrorReporting; using nadena.dev.ndmf; using UnityEditor; using UnityEngine; diff --git a/Editor/Processors/MeshInfo2Holder.cs b/Editor/Processors/MeshInfo2Holder.cs index 0b72b0d89..0b4a8be83 100644 --- a/Editor/Processors/MeshInfo2Holder.cs +++ b/Editor/Processors/MeshInfo2Holder.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using System.Linq; -using Anatawa12.AvatarOptimizer.ErrorReporting; using Anatawa12.AvatarOptimizer.Processors.SkinnedMeshes; using JetBrains.Annotations; using nadena.dev.ndmf; diff --git a/Editor/Processors/OriginalState.cs b/Editor/Processors/OriginalState.cs index f194494bf..6df7258f5 100644 --- a/Editor/Processors/OriginalState.cs +++ b/Editor/Processors/OriginalState.cs @@ -1,5 +1,4 @@ using System.Collections.Generic; -using Anatawa12.AvatarOptimizer.ErrorReporting; using nadena.dev.ndmf; using UnityEngine; diff --git a/Editor/Processors/SkinnedMeshes/FreezeBlendShapeProcessor.cs b/Editor/Processors/SkinnedMeshes/FreezeBlendShapeProcessor.cs index f8b66e1a0..ff7740eff 100644 --- a/Editor/Processors/SkinnedMeshes/FreezeBlendShapeProcessor.cs +++ b/Editor/Processors/SkinnedMeshes/FreezeBlendShapeProcessor.cs @@ -1,7 +1,6 @@ using System.Collections; using System.Collections.Generic; using System.Linq; -using Anatawa12.AvatarOptimizer.ErrorReporting; using nadena.dev.ndmf; using UnityEngine; using UnityEngine.Profiling; diff --git a/Editor/Processors/SkinnedMeshes/MergeSkinnedMeshProcessor.cs b/Editor/Processors/SkinnedMeshes/MergeSkinnedMeshProcessor.cs index ec5020338..a7aa35627 100644 --- a/Editor/Processors/SkinnedMeshes/MergeSkinnedMeshProcessor.cs +++ b/Editor/Processors/SkinnedMeshes/MergeSkinnedMeshProcessor.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using Anatawa12.AvatarOptimizer.ErrorReporting; using nadena.dev.ndmf; using UnityEditor; using UnityEditor.Animations; diff --git a/Editor/Processors/SkinnedMeshes/MeshInfo2.cs b/Editor/Processors/SkinnedMeshes/MeshInfo2.cs index 69e0ddc16..8e28f88f4 100644 --- a/Editor/Processors/SkinnedMeshes/MeshInfo2.cs +++ b/Editor/Processors/SkinnedMeshes/MeshInfo2.cs @@ -3,14 +3,12 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; -using Anatawa12.AvatarOptimizer.ErrorReporting; using JetBrains.Annotations; using nadena.dev.ndmf; using Unity.Burst; using Unity.Collections; using Unity.Jobs; using UnityEngine; -using UnityEngine.Assertions; using UnityEngine.Profiling; using UnityEngine.Rendering; using Debug = System.Diagnostics.Debug; diff --git a/Editor/Processors/SkinnedMeshes/RemoveMeshInBoxProcessor.cs b/Editor/Processors/SkinnedMeshes/RemoveMeshInBoxProcessor.cs index acad41373..35d098576 100644 --- a/Editor/Processors/SkinnedMeshes/RemoveMeshInBoxProcessor.cs +++ b/Editor/Processors/SkinnedMeshes/RemoveMeshInBoxProcessor.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using Anatawa12.AvatarOptimizer.ErrorReporting; using nadena.dev.ndmf; using UnityEngine; diff --git a/Editor/Processors/TraceAndOptimize/ComponentDependencyCollector.cs b/Editor/Processors/TraceAndOptimize/ComponentDependencyCollector.cs index aee0d6254..551517402 100644 --- a/Editor/Processors/TraceAndOptimize/ComponentDependencyCollector.cs +++ b/Editor/Processors/TraceAndOptimize/ComponentDependencyCollector.cs @@ -1,5 +1,4 @@ using Anatawa12.AvatarOptimizer.APIInternal; -using Anatawa12.AvatarOptimizer.ErrorReporting; using Anatawa12.AvatarOptimizer.Processors.SkinnedMeshes; using JetBrains.Annotations; using nadena.dev.ndmf; diff --git a/Editor/Processors/TraceAndOptimize/OptimizePhysBone.cs b/Editor/Processors/TraceAndOptimize/OptimizePhysBone.cs index c5e69e193..328733111 100644 --- a/Editor/Processors/TraceAndOptimize/OptimizePhysBone.cs +++ b/Editor/Processors/TraceAndOptimize/OptimizePhysBone.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Linq; using Anatawa12.AvatarOptimizer.AnimatorParsers; -using Anatawa12.AvatarOptimizer.ErrorReporting; using nadena.dev.ndmf; using UnityEngine; using VRC.Dynamics; diff --git a/Editor/Processors/UnusedBonesByReferencesToolEarlyProcessor.cs b/Editor/Processors/UnusedBonesByReferencesToolEarlyProcessor.cs index ce38d9687..912fdfc5a 100644 --- a/Editor/Processors/UnusedBonesByReferencesToolEarlyProcessor.cs +++ b/Editor/Processors/UnusedBonesByReferencesToolEarlyProcessor.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; -using Anatawa12.AvatarOptimizer.ErrorReporting; using nadena.dev.ndmf; using UnityEngine; From ddeb153f420c66b129154cea5132e0cfd27cfea5 Mon Sep 17 00:00:00 2001 From: anatawa12 Date: Thu, 28 Dec 2023 04:20:00 +0900 Subject: [PATCH 07/10] ci: fetch ndmf from bd_ prerelease repository for now --- .github/workflows/gameci.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/gameci.yml b/.github/workflows/gameci.yml index bd3f19cca..0ee397742 100644 --- a/.github/workflows/gameci.yml +++ b/.github/workflows/gameci.yml @@ -23,6 +23,7 @@ jobs: with: repos: | https://vpm.anatawa12.com/vpm.json + https://vpm.nadena.dev/vpm-prerelease.json - uses: actions/cache@v3 with: From baea02c6992204066d3e24692b59e87358ceff18 Mon Sep 17 00:00:00 2001 From: anatawa12 Date: Thu, 28 Dec 2023 18:15:18 +0900 Subject: [PATCH 08/10] chore: use new LocaleLocalization API from CL4EE v1.2.0 --- Editor/BuildLog.cs | 18 +++++++++--------- package.json | 4 ++-- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/Editor/BuildLog.cs b/Editor/BuildLog.cs index 84ef4ca57..b302712ce 100644 --- a/Editor/BuildLog.cs +++ b/Editor/BuildLog.cs @@ -1,10 +1,11 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Linq; +using CustomLocalization4EditorExtension; using nadena.dev.ndmf; using nadena.dev.ndmf.localization; -using UnityEditor; -using UnityEngine; +using Debug = System.Diagnostics.Debug; using Object = UnityEngine.Object; namespace Anatawa12.AvatarOptimizer @@ -23,14 +24,13 @@ public static void LogError(string code, params object[] args) => internal class InlineError : SimpleError, IError { - private static Localizer _localizer = new Localizer("en-US", () => new List() + private static Localizer _localizer = new Localizer("en-US", () => { - // en.po - AssetDatabase.LoadAssetAtPath( - AssetDatabase.GUIDToAssetPath("f9d382355a0a485980e8e7271bca53d7")), - // ja.po - AssetDatabase.LoadAssetAtPath( - AssetDatabase.GUIDToAssetPath("feed5ac7cc024b9e92e46f7e2dbdbe82")), + var localization = CL4EE.GetLocalization(); + Debug.Assert(localization != null, nameof(localization) + " != null"); + return localization.LocalizationByIsoCode.Values + .Select(locale => (locale.LocaleIsoCode, (Func)locale.TryGetLocalizedString)) + .ToList(); }); private readonly string _key; diff --git a/package.json b/package.json index 54a076b06..cc49a866d 100644 --- a/package.json +++ b/package.json @@ -12,8 +12,8 @@ "url": "https://github.com/anatawa12/AvatarOptimizer", "repo": "https://vpm.anatawa12.com/vpm.json", "vpmDependencies": { - "com.anatawa12.custom-localization-for-editor-extension": "^1.0.0", - "nadena.dev.ndmf": "^1.3.0-rc.0", + "com.anatawa12.custom-localization-for-editor-extension": "^1.2.0", + "nadena.dev.ndmf": "1.3.0-rc.0", "com.vrchat.avatars": ">=3.2.0-beta.1 <3.6.0" } } From cde424b6d175fe5165900065ef37b8efdcbea45b Mon Sep 17 00:00:00 2001 From: anatawa12 Date: Thu, 28 Dec 2023 18:18:58 +0900 Subject: [PATCH 09/10] docs(changelog): AvatarOptimizer now uses ErrorReporting API of NDMF instead of our own API --- CHANGELOG-PRERELEASE.md | 1 + CHANGELOG.md | 1 + 2 files changed, 2 insertions(+) diff --git a/CHANGELOG-PRERELEASE.md b/CHANGELOG-PRERELEASE.md index 48d4c82d2..e09d80ad6 100644 --- a/CHANGELOG-PRERELEASE.md +++ b/CHANGELOG-PRERELEASE.md @@ -10,6 +10,7 @@ The format is based on [Keep a Changelog]. ### Added ### Changed +- AvatarOptimizer now uses ErrorReporting API of NDMF instead of our own API `#805` ### Deprecated diff --git a/CHANGELOG.md b/CHANGELOG.md index 29408e665..8cd76360e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ The format is based on [Keep a Changelog]. ### Added ### Changed +- AvatarOptimizer now uses ErrorReporting API of NDMF instead of our own API `#805` ### Deprecated From 513382d0cf9c6f7bda26ee235ef798297978376b Mon Sep 17 00:00:00 2001 From: anatawa12 Date: Thu, 28 Dec 2023 18:27:07 +0900 Subject: [PATCH 10/10] chore: prevent next release since we're using prerelease version of NDMF --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index cc49a866d..17407ea76 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "com.anatawa12.avatar-optimizer", "version": "1.6.5-beta.0", - "private": false, + "private": true, "unity": "2019.4", "description": "Set of Anatawa12's Small Avatar Optimization Utilities", "displayName": "Anatawa12's AvatarOptimizer",