osu/osu.Game/Rulesets/RulesetInfo.cs

109 lines
3.1 KiB
C#

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using JetBrains.Annotations;
using osu.Framework.Testing;
using Realms;
#nullable enable
namespace osu.Game.Rulesets
{
[ExcludeFromDynamicCompile]
[MapTo("Ruleset")]
public class RulesetInfo : RealmObject, IEquatable<RulesetInfo>, IRulesetInfo
{
[PrimaryKey]
public string ShortName { get; set; } = string.Empty;
[Indexed]
public int OnlineID { get; set; } = -1;
public string Name { get; set; } = string.Empty;
public string InstantiationInfo { get; set; } = string.Empty;
public RulesetInfo(string shortName, string name, string instantiationInfo, int onlineID)
{
ShortName = shortName;
Name = name;
InstantiationInfo = instantiationInfo;
OnlineID = onlineID;
}
[UsedImplicitly]
public RulesetInfo()
{
}
public RulesetInfo(int? onlineID, string name, string shortName, bool available)
{
OnlineID = onlineID ?? -1;
Name = name;
ShortName = shortName;
Available = available;
}
public bool Available { get; set; }
public bool Equals(RulesetInfo? other)
{
if (ReferenceEquals(this, other)) return true;
if (other == null) return false;
return ShortName == other.ShortName;
}
public bool Equals(IRulesetInfo? other) => other is RulesetInfo b && Equals(b);
public override int GetHashCode()
{
// Importantly, ignore the underlying realm hash code, as it will usually not match.
var hashCode = new HashCode();
// ReSharper disable once NonReadonlyMemberInGetHashCode
hashCode.Add(ShortName);
return hashCode.ToHashCode();
}
public override string ToString() => Name;
public RulesetInfo Clone() => new RulesetInfo
{
OnlineID = OnlineID,
Name = Name,
ShortName = ShortName,
InstantiationInfo = InstantiationInfo,
Available = Available
};
public Ruleset CreateInstance()
{
if (!Available)
throw new RulesetLoadException(@"Ruleset not available");
var type = Type.GetType(InstantiationInfo);
if (type == null)
throw new RulesetLoadException(@"Type lookup failure");
var ruleset = Activator.CreateInstance(type) as Ruleset;
if (ruleset == null)
throw new RulesetLoadException(@"Instantiation failure");
// overwrite the pre-populated RulesetInfo with a potentially database attached copy.
// TODO: figure if we still want/need this after switching to realm.
// ruleset.RulesetInfo = this;
return ruleset;
}
#region Compatibility properties
public int ID => OnlineID;
#endregion
}
}