// Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Extensions.TypeExtensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Performance; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Drawables; namespace osu.Game.Rulesets.UI { public class HitObjectContainer : CompositeDrawable, IHitObjectContainer { /// /// All entries in this including dead entries. /// public IEnumerable Entries => allEntries; /// /// All alive entries and s used by the entries. /// public IEnumerable<(HitObjectLifetimeEntry Entry, DrawableHitObject Drawable)> AliveEntries => aliveDrawableMap.Select(x => (x.Key, x.Value)); public IEnumerable Objects => InternalChildren.Cast().OrderBy(h => h.HitObject.StartTime); public IEnumerable AliveObjects => AliveInternalChildren.Cast().OrderBy(h => h.HitObject.StartTime); /// /// Invoked when a is judged. /// public event Action NewResult; /// /// Invoked when a judgement is reverted. /// public event Action RevertResult; /// /// Invoked when a becomes used by a . /// /// /// If this uses pooled objects, this represents the time when the s become alive. /// internal event Action HitObjectUsageBegan; /// /// Invoked when a becomes unused by a . /// /// /// If this uses pooled objects, this represents the time when the s become dead. /// internal event Action HitObjectUsageFinished; /// /// The amount of time prior to the current time within which s should be considered alive. /// internal double PastLifetimeExtension { get; set; } /// /// The amount of time after the current time within which s should be considered alive. /// internal double FutureLifetimeExtension { get; set; } private readonly Dictionary startTimeMap = new Dictionary(); private readonly Dictionary aliveDrawableMap = new Dictionary(); private readonly Dictionary nonPooledDrawableMap = new Dictionary(); private readonly LifetimeEntryManager lifetimeManager = new LifetimeEntryManager(); private readonly HashSet allEntries = new HashSet(); [Resolved(CanBeNull = true)] private IPooledHitObjectProvider pooledObjectProvider { get; set; } public HitObjectContainer() { RelativeSizeAxes = Axes.Both; lifetimeManager.EntryBecameAlive += entryBecameAlive; lifetimeManager.EntryBecameDead += entryBecameDead; lifetimeManager.EntryCrossedBoundary += entryCrossedBoundary; } protected override void LoadAsyncComplete() { base.LoadAsyncComplete(); // Application of hitobjects during load() may have changed their start times, so ensure the correct sorting order. SortInternal(); } #region Pooling support public void Add(HitObjectLifetimeEntry entry) { allEntries.Add(entry); lifetimeManager.AddEntry(entry); } public bool Remove(HitObjectLifetimeEntry entry) { if (!lifetimeManager.RemoveEntry(entry)) return false; // This logic is not in `Remove(DrawableHitObject)` because a non-pooled drawable may be removed by specifying its entry. if (nonPooledDrawableMap.Remove(entry, out var drawable)) removeDrawable(drawable); allEntries.Remove(entry); return true; } private void entryBecameAlive(LifetimeEntry lifetimeEntry) { var entry = (HitObjectLifetimeEntry)lifetimeEntry; Debug.Assert(!aliveDrawableMap.ContainsKey(entry)); bool isNonPooled = nonPooledDrawableMap.TryGetValue(entry, out var drawable); drawable ??= pooledObjectProvider?.GetPooledDrawableRepresentation(entry.HitObject, null); if (drawable == null) throw new InvalidOperationException($"A drawable representation could not be retrieved for hitobject type: {entry.HitObject.GetType().ReadableName()}."); aliveDrawableMap[entry] = drawable; OnAdd(drawable); if (isNonPooled) return; addDrawable(drawable); HitObjectUsageBegan?.Invoke(entry.HitObject); } private void entryBecameDead(LifetimeEntry lifetimeEntry) { var entry = (HitObjectLifetimeEntry)lifetimeEntry; Debug.Assert(aliveDrawableMap.ContainsKey(entry)); var drawable = aliveDrawableMap[entry]; bool isNonPooled = nonPooledDrawableMap.ContainsKey(entry); drawable.OnKilled(); aliveDrawableMap.Remove(entry); OnRemove(drawable); if (isNonPooled) return; removeDrawable(drawable); // The hit object is not freed when the DHO was not pooled. HitObjectUsageFinished?.Invoke(entry.HitObject); } private void addDrawable(DrawableHitObject drawable) { drawable.OnNewResult += onNewResult; drawable.OnRevertResult += onRevertResult; bindStartTime(drawable); AddInternal(drawable); } private void removeDrawable(DrawableHitObject drawable) { drawable.OnNewResult -= onNewResult; drawable.OnRevertResult -= onRevertResult; unbindStartTime(drawable); RemoveInternal(drawable); } #endregion #region Non-pooling support public virtual void Add(DrawableHitObject drawable) { if (drawable.Entry == null) throw new InvalidOperationException($"May not add a {nameof(DrawableHitObject)} without {nameof(HitObject)} associated"); nonPooledDrawableMap.Add(drawable.Entry, drawable); addDrawable(drawable); Add(drawable.Entry); } public virtual bool Remove(DrawableHitObject drawable) { if (drawable.Entry == null) return false; return Remove(drawable.Entry); } public int IndexOf(DrawableHitObject hitObject) => IndexOfInternal(hitObject); private void entryCrossedBoundary(LifetimeEntry entry, LifetimeBoundaryKind kind, LifetimeBoundaryCrossingDirection direction) { if (nonPooledDrawableMap.TryGetValue((HitObjectLifetimeEntry)entry, out var drawable)) OnChildLifetimeBoundaryCrossed(new LifetimeBoundaryCrossedEvent(drawable, kind, direction)); } protected virtual void OnChildLifetimeBoundaryCrossed(LifetimeBoundaryCrossedEvent e) { } #endregion /// /// Invoked when a is added to this container. /// /// /// This method is not invoked for nested s. /// protected virtual void OnAdd(DrawableHitObject drawableHitObject) { } /// /// Invoked when a is removed from this container. /// /// /// This method is not invoked for nested s. /// protected virtual void OnRemove(DrawableHitObject drawableHitObject) { } public virtual void Clear() { lifetimeManager.ClearEntries(); foreach (var drawable in nonPooledDrawableMap.Values) removeDrawable(drawable); nonPooledDrawableMap.Clear(); Debug.Assert(InternalChildren.Count == 0 && startTimeMap.Count == 0 && aliveDrawableMap.Count == 0, "All hit objects should have been removed"); } protected override bool CheckChildrenLife() { bool aliveChanged = base.CheckChildrenLife(); aliveChanged |= lifetimeManager.Update(Time.Current - PastLifetimeExtension, Time.Current + FutureLifetimeExtension); return aliveChanged; } private void onNewResult(DrawableHitObject d, JudgementResult r) => NewResult?.Invoke(d, r); private void onRevertResult(DrawableHitObject d, JudgementResult r) => RevertResult?.Invoke(d, r); #region Comparator + StartTime tracking private void bindStartTime(DrawableHitObject hitObject) { var bindable = hitObject.StartTimeBindable.GetBoundCopy(); bindable.BindValueChanged(_ => { if (LoadState >= LoadState.Ready) SortInternal(); }); startTimeMap[hitObject] = bindable; } private void unbindStartTime(DrawableHitObject hitObject) { startTimeMap[hitObject].UnbindAll(); startTimeMap.Remove(hitObject); } private void unbindAllStartTimes() { foreach (var kvp in startTimeMap) kvp.Value.UnbindAll(); startTimeMap.Clear(); } protected override int Compare(Drawable x, Drawable y) { if (!(x is DrawableHitObject xObj) || !(y is DrawableHitObject yObj)) return base.Compare(x, y); // Put earlier hitobjects towards the end of the list, so they handle input first int i = yObj.HitObject.StartTime.CompareTo(xObj.HitObject.StartTime); return i == 0 ? CompareReverseChildID(x, y) : i; } #endregion protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); unbindAllStartTimes(); } } }