Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,12 @@ public bool IsAnimatorInTag(int hashTag) =>
public int GetAnimatorCurrentStateTag(int layerIndex) =>
AvatarAnimator.GetCurrentAnimatorStateInfo(layerIndex).tagHash;

public int GetAnimatorCurrentStateTag(string layerName)
{
int layerIndex = AvatarAnimator.GetLayerIndex(layerName);
return AvatarAnimator.GetCurrentAnimatorStateInfo(layerIndex).tagHash;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Dead production code — GetAnimatorCurrentStateTag(string) is not declared on the IAvatarView interface and has no production consumer — only the perf test (AvatarAnimatorLayerIndexCachePerformanceTest) calls it on the concrete AvatarBase. Since all production code goes through IAvatarView, this overload is unreachable outside tests. Consider removing it and having the perf test call AvatarAnimator.GetLayerIndex + the int overload directly, or defer adding it until a production consumer exists.

Suggested change
public int GetAnimatorCurrentStateTag(string layerName)
{
int layerIndex = AvatarAnimator.GetLayerIndex(layerName);
return AvatarAnimator.GetCurrentAnimatorStateInfo(layerIndex).tagHash;
}


public int GetEmoteLayerIndex(AvatarEmoteMask mask) =>
mask == AvatarEmoteMask.AemUpperBody ? upperBodyLayerIndex : AnimatorEmoteLayers.BASE_LAYER_INDEX;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,9 @@ private void CancelEmotesByMoveToWithDuration(Entity entity, ref CharacterEmoteC
[Query]
private void UpdateEmoteTags(ref CharacterEmoteComponent emoteComponent, in IAvatarView avatarView)
{
if (emoteComponent.CurrentEmoteReference == null && emoteComponent.CurrentAnimationTag == 0)
return;

int currentStateTag = avatarView.GetAnimatorCurrentStateTag(AnimatorEmoteLayers.BASE_LAYER_INDEX);
emoteComponent.SetAnimationTag(currentStateTag);
}
Expand Down Expand Up @@ -643,12 +646,10 @@ private static bool TryResolveSceneByNamePrefix(IReadOnlyCollection<ISceneFacade
if (candidateName.Length == 0)
continue;

ReadOnlySpan<char> candidatePrefix = (candidateName + "-").AsSpan();

if (payloadWithoutLoop.StartsWith(candidatePrefix, StringComparison.Ordinal))
if (TryMatchSceneEmotePayload(payloadWithoutLoop, candidateName, out string emoteHash))
{
sceneId = candidateName;
parsedEmoteHash = payloadWithoutLoop.Slice(candidatePrefix.Length).ToString();
parsedEmoteHash = emoteHash;
resolvedScene = facade;
return true;
}
Expand All @@ -657,6 +658,25 @@ private static bool TryResolveSceneByNamePrefix(IReadOnlyCollection<ISceneFacade
return false;
}

/// <summary>
/// Determines whether a scene-emote payload names <paramref name="candidateName"/> and, if so, extracts that
/// emote's content hash. Scene emotes are addressed as "&lt;name&gt;-&lt;hash&gt;", so the payload matches a candidate
/// only when it is that name followed by '-' and a (possibly empty) hash.
/// </summary>
internal static bool TryMatchSceneEmotePayload(ReadOnlySpan<char> payloadWithoutLoop, string candidateName, out string parsedEmoteHash)
{
int n = candidateName.Length;

if (payloadWithoutLoop.Length >= n + 1 && payloadWithoutLoop[n] == '-' && payloadWithoutLoop.Slice(0, n).SequenceEqual(candidateName.AsSpan()))
{
parsedEmoteHash = payloadWithoutLoop.Slice(n + 1).ToString();
return true;
}

parsedEmoteHash = string.Empty;
return false;
}

private bool TryResolveLocalSceneEmotePath(ISceneFacade sceneFacade, string hash, out string emotePath)
{
var content = sceneFacade.SceneData.SceneEntityDefinition.content;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ public bool Play(GameObject mainAsset, AudioClip? audioAsset, bool isLooping, bo
EmoteReferences? emoteReferences = AcquireEmoteReferences(mainAsset, audioAsset, isLooping, isSpatial, in view, emoteInUse);
if (emoteReferences == null) return false;

emotesInUse.Add(emoteReferences, pools[mainAsset]);

if (emoteReferences.legacy)
{
if (!legacyAnimationsEnabled)
Expand All @@ -71,7 +73,6 @@ public bool Play(GameObject mainAsset, AudioClip? audioAsset, bool isLooping, bo
else
PlayMecanimEmote(view, ref emoteComponent, emoteReferences, isLooping);

emotesInUse.Add(emoteReferences, pools[mainAsset]);
emoteComponent.CurrentEmoteReference = emoteReferences;
return true;
}
Expand All @@ -87,6 +88,8 @@ public bool PlayMasked(GameObject mainAsset, AudioClip? audioAsset, bool isLoopi
EmoteReferences? emoteReferences = AcquireEmoteReferences(mainAsset, audioAsset, isLooping, isSpatial, in view, emoteInUse);
if (emoteReferences == null) return false;

emotesInUse.Add(emoteReferences, pools[mainAsset]);

if (emoteReferences.legacy)
{
if (!PlayMaskedLegacyEmote(view, ref maskedEmote, emoteReferences, isLooping))
Expand All @@ -98,7 +101,6 @@ public bool PlayMasked(GameObject mainAsset, AudioClip? audioAsset, bool isLoopi
else
PlayMaskedMecanimEmote(view, ref maskedEmote, emoteReferences, isLooping);

emotesInUse.Add(emoteReferences, pools[mainAsset]);
maskedEmote.CurrentEmoteReference = emoteReferences;
return true;
}
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
using Arch.Core;
using DCL.AvatarRendering.AvatarShape.UnityInterface;
using DCL.AvatarRendering.Emotes.Play;
using DCL.DebugUtilities;
using DCL.Multiplayer.Emotes;
using ECS.SceneLifeCycle;
using ECS.TestSuite;
using NSubstitute;
using NUnit.Framework;
using Unity.PerformanceTesting;
using UnityEngine;
using Object = UnityEngine.Object;

namespace DCL.AvatarRendering.Emotes.Tests.PerformanceTests
{
/// <summary>
/// <see cref="CharacterEmoteSystem"/>'s <c>UpdateEmoteTags</c> query must poll the native Mecanim
/// animator state (<c>IAvatarView.GetAnimatorCurrentStateTag</c>) only for avatars that are
/// actually emoting — not for every entity carrying a <see cref="CharacterEmoteComponent"/>. The
/// guard early-outs when
/// <c>CurrentEmoteReference == null &amp;&amp; CurrentAnimationTag == 0</c>.
/// <para>
/// Metric: the number of <c>GetAnimatorCurrentStateTag</c> calls during a single
/// <c>system.Update</c> over a crowd of <c>n</c> avatars, <c>emoting</c> of which hold a live
/// (legacy) emote reference. Pass criterion: poll count == <c>emoting</c>. A <c>Measure.Method</c>
/// also records the guarded full-Update cost over the crowd for the timing dimension.
/// </para>
/// <para>
/// A single shared, counting <see cref="IAvatarView"/> substitute is used across every entity: the
/// query invokes it exactly once per entity that reaches the native poll, so the running total is
/// the poll count. <c>IsLegacyAnimationPlaying</c> returns true so the emoting fixtures stay
/// "playing" and are not stopped by <c>CancelEmotes</c> earlier in the same Update — keeping their
/// live reference so <c>UpdateEmoteTags</c> must poll them.
/// </para>
/// </summary>
[Category("Performance")]
public class CharacterEmoteSystemPerformanceTest : UnitySystemTestBase<CharacterEmoteSystem>
{
private GameObject audioSourcePrefab = null!;
private GameObject poolRootContainer = null!;
private EmoteReferences legacyEmote = null!;
private IAvatarView avatarView = null!;
private int animatorTagPolls;

[SetUp]
public void SetUp()
{
// EmotePlayer's ctor resolves its pool parent via GameObject.Find("ROOT_POOL_CONTAINER").
// The bare EditMode scene has no such object, so the null-forgiving `!` in production
// would let a runtime NRE through — create the expected scene object before constructing it.
poolRootContainer = new GameObject("ROOT_POOL_CONTAINER");

audioSourcePrefab = new GameObject("EmoteAudioSource");
AudioSource audioSource = audioSourcePrefab.AddComponent<AudioSource>();
var emotePlayer = new EmotePlayer(audioSource, ScriptableObject.CreateInstance<EmoteMaskCatalog>(), legacyAnimationsEnabled: true);

system = new CharacterEmoteSystem(world, Substitute.For<IEmoteStorage>(), Substitute.For<IEmotesMessageBus>(),
emotePlayer, Substitute.For<IDebugContainerBuilder>(), localSceneDevelopment: false, new ScenesCache());

avatarView = Substitute.For<IAvatarView>();
avatarView.IsLegacyAnimationPlaying.Returns(true);
// UpdateEmoteTags polls the int-layer overload (GetAnimatorCurrentStateTag(BASE_LAYER_INDEX),
// BASE_LAYER_INDEX is a const int) — not the string-layer one. NSubstitute keys returns per
// overload, so the counter must be registered on the int overload or the real polls go
// uncounted and every case reads 0.
avatarView.GetAnimatorCurrentStateTag(Arg.Any<int>()).Returns(_ =>
{
animatorTagPolls++;
return 0;
});

legacyEmote = new GameObject(nameof(EmoteReferences)).AddComponent<EmoteReferences>();
legacyEmote.Initialize(null, null, null, null, 0, legacy: true);
}

protected override void OnTearDown()
{
if (legacyEmote != null) Object.DestroyImmediate(legacyEmote.gameObject);
if (audioSourcePrefab != null) Object.DestroyImmediate(audioSourcePrefab);
if (poolRootContainer != null) Object.DestroyImmediate(poolRootContainer);
}

private void PopulateCrowd(int n, int emoting)
{
for (int i = 0; i < n; i++)
{
var emoteComponent = new CharacterEmoteComponent();

if (i < emoting)
emoteComponent.CurrentEmoteReference = legacyEmote;

world.Create(emoteComponent, avatarView);
}
}

[Test]
[Performance]
[TestCase(100, 0)]
[TestCase(100, 5)]
public void UpdateEmoteTags_PollsOnlyEmotingAvatars(int n, int emoting)
{
PopulateCrowd(n, emoting);

animatorTagPolls = 0;
system!.Update(0f);

Measure.Custom(new SampleGroup("Animator.GetStateTag.Calls", SampleUnit.Undefined), animatorTagPolls);

Assert.AreEqual(emoting, animatorTagPolls,
$"UpdateEmoteTags polled the Mecanim animator {animatorTagPolls} times over {n} avatars " +
$"({emoting} emoting); the guard must limit native polls to emoting avatars.");

Measure.Method(() => system!.Update(0f))
.WarmupCount(5)
.MeasurementCount(30)
.GC()
.Run();
}
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -1,10 +1,31 @@
using DCL.ECSComponents;

namespace Utility.Animations
{
public static class AnimatorEmoteLayers
{
// Unity's Animator always places the base layer at index 0.
public const string BASE_LAYER = "Base Layer";
public const string UPPER_BODY_LAYER = "Upper Body Layer";

public const int BASE_LAYER_INDEX = 0;

public const string UPPER_BODY_LAYER = "Upper Body Layer";
public static readonly string[] ALL_LAYERS =
{
BASE_LAYER,
UPPER_BODY_LAYER,
};

public static readonly string[] NON_BASE_LAYERS =
{
UPPER_BODY_LAYER,
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Dead infrastructure — ALL_LAYERS, NON_BASE_LAYERS, and using DCL.ECSComponents have zero production consumers. ALL_LAYERS and NON_BASE_LAYERS are not referenced by any code outside this file, and the using DCL.ECSComponents import is only needed by the equally unused GetFromEmoteMask below. Adding unused infrastructure pulls the Protocol assembly dependency into Utility for no runtime benefit. Per CLAUDE.md §11 (anti-patterns), unused code should not be added speculatively — add these when the consumer that needs them arrives.

Suggested change
using DCL.ECSComponents;
namespace Utility.Animations
{
public static class AnimatorEmoteLayers
{
// Unity's Animator always places the base layer at index 0.
public const string BASE_LAYER = "Base Layer";
public const string UPPER_BODY_LAYER = "Upper Body Layer";
public const int BASE_LAYER_INDEX = 0;
public const string UPPER_BODY_LAYER = "Upper Body Layer";
public static readonly string[] ALL_LAYERS =
{
BASE_LAYER,
UPPER_BODY_LAYER,
};
public static readonly string[] NON_BASE_LAYERS =
{
UPPER_BODY_LAYER,
};
namespace Utility.Animations
{
public static class AnimatorEmoteLayers
{
public const string BASE_LAYER = "Base Layer";
public const string UPPER_BODY_LAYER = "Upper Body Layer";
public const int BASE_LAYER_INDEX = 0;


public static string GetFromEmoteMask(AvatarEmoteMask mask) =>
mask switch
{
AvatarEmoteMask.AemFullBody => BASE_LAYER,
AvatarEmoteMask.AemUpperBody => UPPER_BODY_LAYER,
_ => BASE_LAYER,
};
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Dead infrastructure — GetFromEmoteMask has zero consumers in the codebase. Additionally, the switch body has inconsistent indentation (extra leading spaces on the switch expression). Remove until a consumer exists; if kept, fix the indentation to match project style.

Suggested change
public static string GetFromEmoteMask(AvatarEmoteMask mask) =>
mask switch
{
AvatarEmoteMask.AemFullBody => BASE_LAYER,
AvatarEmoteMask.AemUpperBody => UPPER_BODY_LAYER,
_ => BASE_LAYER,
};
}
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
using DCL.AvatarRendering.AvatarShape.UnityInterface;
using DCL.ECSComponents;
using NUnit.Framework;
using System.Diagnostics;
using System.Reflection;
using Unity.PerformanceTesting;
using UnityEngine;
using Utility.Animations;
#if UNITY_EDITOR
using UnityEditor;
#endif

namespace DCL.Tests.PlayMode.PerformanceTests
{
/// <summary>
/// Verifies the int-indexed layer lookups exposed by AvatarBase (cached in Awake) return identical results to
/// the string-based Animator lookups for every layer, including after a state change on the Upper Body layer,
/// and that the int path is faster than the string path it replaces.
/// </summary>
[Category("Performance")]
public class AvatarAnimatorLayerIndexCachePerformanceTest
{
#if UNITY_EDITOR
private const string AVATAR_BASE_TEST_ASSET_PATH = "Assets/DCL/AvatarRendering/AvatarShape/Tests/Instantiate/TestAssets/AvatarBase_TestAsset.prefab";
private const string ANIMATOR_CONTROLLER_PATH = "Assets/DCL/AvatarRendering/AvatarShape/Assets/Animator/CharacterAnimator.controller";

private GameObject avatarGameObject = null!;
private AvatarBase avatarBase = null!;
private Animator animator = null!;

[SetUp]
public void SetUp()
{
var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(AVATAR_BASE_TEST_ASSET_PATH);
Assert.IsNotNull(prefab, $"Could not load AvatarBase test prefab from {AVATAR_BASE_TEST_ASSET_PATH}");

avatarGameObject = Object.Instantiate(prefab);
avatarBase = avatarGameObject.GetComponentInChildren<AvatarBase>();
Assert.IsNotNull(avatarBase, "AvatarBase component not found on test prefab");

animator = avatarBase.AvatarAnimator;
Assert.IsNotNull(animator, "AvatarAnimator not configured on test prefab");

var controller = AssetDatabase.LoadAssetAtPath<RuntimeAnimatorController>(ANIMATOR_CONTROLLER_PATH);
Assert.IsNotNull(controller, $"Could not load animator controller from {ANIMATOR_CONTROLLER_PATH}");
animator.runtimeAnimatorController = controller;

typeof(AvatarBase).GetMethod("Awake", BindingFlags.NonPublic | BindingFlags.Instance)!
.Invoke(avatarBase, null);

animator.Update(0f);
}

[TearDown]
public void TearDown()
{
if (avatarGameObject != null) Object.DestroyImmediate(avatarGameObject);
}

[Test]
[Performance]
public void IntTagLookup_MatchesStringPath_AndIsFaster()
{
Assert.AreEqual(0, animator.GetLayerIndex(AnimatorEmoteLayers.BASE_LAYER), "Base Layer must be index 0");
Assert.AreEqual(AnimatorEmoteLayers.BASE_LAYER_INDEX, animator.GetLayerIndex(AnimatorEmoteLayers.BASE_LAYER));

int upperBodyIndex = animator.GetLayerIndex(AnimatorEmoteLayers.UPPER_BODY_LAYER);
Assert.AreEqual(upperBodyIndex, avatarBase.UpperBodyLayerIndex, "Cached UpperBodyLayerIndex must match the string lookup");

for (int i = 0; i < animator.layerCount; i++)
{
string layerName = animator.GetLayerName(i);
Assert.AreEqual(avatarBase.GetAnimatorCurrentStateTag(layerName), avatarBase.GetAnimatorCurrentStateTag(i),
$"int/string tag lookup diverged on layer {i} ({layerName})");
}

if (upperBodyIndex >= 0)
{
animator.Play(animator.GetCurrentAnimatorStateInfo(upperBodyIndex).fullPathHash, upperBodyIndex, 0f);
animator.Update(0f);

for (int i = 0; i < animator.layerCount; i++)
{
string layerName = animator.GetLayerName(i);
Assert.AreEqual(avatarBase.GetAnimatorCurrentStateTag(layerName), avatarBase.GetAnimatorCurrentStateTag(i));
}
}

Assert.AreEqual(0, avatarBase.GetEmoteLayerIndex(AvatarEmoteMask.AemFullBody));
Assert.AreEqual(avatarBase.UpperBodyLayerIndex, avatarBase.GetEmoteLayerIndex(AvatarEmoteMask.AemUpperBody));

const int ITER = 200_000;
long bestString = long.MaxValue, bestInt = long.MaxValue;

for (int run = 0; run < 5; run++)
{
var sw = Stopwatch.StartNew();
for (int k = 0; k < ITER; k++) avatarBase.GetAnimatorCurrentStateTag(AnimatorEmoteLayers.UPPER_BODY_LAYER);
sw.Stop();
bestString = System.Math.Min(bestString, sw.ElapsedTicks);

sw.Restart();
for (int k = 0; k < ITER; k++) avatarBase.GetAnimatorCurrentStateTag(upperBodyIndex);
sw.Stop();
bestInt = System.Math.Min(bestInt, sw.ElapsedTicks);
}

Measure.Custom(new SampleGroup("StringLayerLookup", SampleUnit.Nanosecond), bestString);
Measure.Custom(new SampleGroup("IntLayerLookup", SampleUnit.Nanosecond), bestInt);

Assert.Less(bestInt, bestString, $"int lookup ({bestInt} ticks) must beat string lookup ({bestString} ticks)");
}
#endif
}
}
Loading
Loading