1
0
mirror of https://github.com/ppy/osu.git synced 2024-12-18 07:22:57 +08:00
osu-lazer/osu.Game/Rulesets/Mods/Mod.cs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

344 lines
14 KiB
C#
Raw Normal View History

// 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.
2018-04-13 17:19:50 +08:00
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
2023-12-13 13:07:38 +08:00
using System.Globalization;
using System.Linq;
using System.Reflection;
2018-11-28 12:12:29 +08:00
using Newtonsoft.Json;
using osu.Framework.Bindables;
using osu.Framework.Extensions.TypeExtensions;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Localisation;
using osu.Game.Configuration;
using osu.Game.Extensions;
2020-03-19 11:43:26 +08:00
using osu.Game.Rulesets.UI;
using osu.Game.Utils;
2018-04-13 17:19:50 +08:00
2017-04-18 15:05:58 +08:00
namespace osu.Game.Rulesets.Mods
2017-02-17 04:05:03 +08:00
{
2017-02-23 19:59:27 +08:00
/// <summary>
/// The base class for gameplay modifiers.
/// </summary>
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]
public abstract class Mod : IMod, IEquatable<Mod>, IDeepCloneable<Mod>
2017-02-17 04:05:03 +08:00
{
2018-11-28 12:12:29 +08:00
[JsonIgnore]
public abstract string Name { get; }
2018-04-13 17:19:50 +08:00
public abstract string Acronym { get; }
2018-04-13 17:19:50 +08:00
[JsonIgnore]
public virtual string ExtendedIconInformation => string.Empty;
2018-11-28 12:12:29 +08:00
[JsonIgnore]
2020-01-14 21:22:00 +08:00
public virtual IconUsage? Icon => null;
2018-04-13 17:19:50 +08:00
2018-11-28 12:12:29 +08:00
[JsonIgnore]
public virtual ModType Type => ModType.Fun;
2018-04-13 17:19:50 +08:00
2018-11-28 12:12:29 +08:00
[JsonIgnore]
public abstract LocalisableString Description { get; }
2018-04-13 17:19:50 +08:00
2020-03-19 11:43:26 +08:00
/// <summary>
/// The tooltip to display for this mod when used in a <see cref="ModIcon"/>.
/// </summary>
/// <remarks>
/// Differs from <see cref="Name"/>, as the value of attributes (AR, CS, etc) changeable via the mod
/// are displayed in the tooltip.
/// </remarks>
[JsonIgnore]
public string IconTooltip
{
get
{
2020-03-23 14:20:56 +08:00
string description = SettingDescription;
return string.IsNullOrEmpty(description) ? Name : $"{Name} ({description})";
}
}
/// <summary>
/// The description of editable settings of a mod to use in the <see cref="IconTooltip"/>.
/// </summary>
/// <remarks>
/// Parentheses are added to the tooltip, surrounding the value of this property. If this property is <c>string.Empty</c>,
/// the tooltip will not have parentheses.
/// </remarks>
public virtual string SettingDescription
{
get
{
var tooltipTexts = new List<string>();
foreach ((SettingSourceAttribute attr, PropertyInfo property) in this.GetOrderedSettingsSourceProperties())
{
var bindable = (IBindable)property.GetValue(this)!;
2020-03-23 14:20:56 +08:00
string valueText;
switch (bindable)
{
case Bindable<bool> b:
valueText = b.Value ? "on" : "off";
break;
default:
valueText = bindable.ToString() ?? string.Empty;
break;
}
if (!bindable.IsDefault)
tooltipTexts.Add($"{attr.Label}: {valueText}");
}
2020-03-23 14:20:56 +08:00
return string.Join(", ", tooltipTexts.Where(s => !string.IsNullOrEmpty(s)));
}
}
2020-03-19 11:43:26 +08:00
2017-02-23 19:57:58 +08:00
/// <summary>
/// The score multiplier of this mod.
2017-02-23 19:57:58 +08:00
/// </summary>
2018-11-28 12:12:29 +08:00
[JsonIgnore]
public abstract double ScoreMultiplier { get; }
2018-04-13 17:19:50 +08:00
/// <summary>
/// Returns true if this mod is implemented (and playable).
/// </summary>
2018-11-28 12:12:29 +08:00
[JsonIgnore]
public virtual bool HasImplementation => this is IApplicableMod;
2018-04-13 17:19:50 +08:00
2023-10-31 23:13:44 +08:00
/// <summary>
/// Whether this mod can be played by a real human user.
/// Non-user-playable mods are not viable for single-player score submission.
/// </summary>
/// <example>
/// <list type="bullet">
/// <item><see cref="ModDoubleTime"/> is user-playable.</item>
/// <item><see cref="ModAutoplay"/> is not user-playable.</item>
/// </list>
/// </example>
[JsonIgnore]
public virtual bool UserPlayable => true;
2023-10-31 23:13:44 +08:00
/// <summary>
/// Whether this mod can be specified as a "required" mod in a multiplayer context.
/// </summary>
/// <example>
/// <list type="bullet">
/// <item><see cref="ModHardRock"/> is valid for multiplayer.</item>
/// <item>
/// <see cref="ModDoubleTime"/> is valid for multiplayer as long as it is a <b>required</b> mod,
/// as that ensures the same duration of gameplay for all users in the room.
/// </item>
/// <item>
/// <see cref="ModAdaptiveSpeed"/> is not valid for multiplayer, as it leads to varying
/// gameplay duration depending on how the users in the room play.
/// </item>
/// <item><see cref="ModAutoplay"/> is not valid for multiplayer.</item>
/// </list>
/// </example>
[JsonIgnore]
public virtual bool ValidForMultiplayer => true;
2023-10-31 23:13:44 +08:00
/// <summary>
/// Whether this mod can be specified as a "free" or "allowed" mod in a multiplayer context.
/// </summary>
/// <example>
/// <list type="bullet">
/// <item><see cref="ModHardRock"/> is valid for multiplayer as a free mod.</item>
/// <item>
/// <see cref="ModDoubleTime"/> is <b>not</b> valid for multiplayer as a free mod,
/// as it could to varying gameplay duration between users in the room depending on whether they picked it.
/// </item>
/// <item><see cref="ModAutoplay"/> is not valid for multiplayer as a free mod.</item>
/// </list>
/// </example>
[JsonIgnore]
public virtual bool ValidForMultiplayerAsFreeMod => true;
/// <inheritdoc/>
[JsonIgnore]
public virtual bool AlwaysValidForSubmission => false;
/// <summary>
/// Whether this mod requires configuration to apply changes to the game.
/// </summary>
[JsonIgnore]
public virtual bool RequiresConfiguration => false;
/// <summary>
/// Whether scores with this mod active can give performance points.
/// </summary>
[JsonIgnore]
public virtual bool Ranked => false;
2017-02-23 19:57:58 +08:00
/// <summary>
2017-03-02 08:57:33 +08:00
/// The mods this mod cannot be enabled with.
2017-02-23 19:57:58 +08:00
/// </summary>
2018-11-28 12:12:29 +08:00
[JsonIgnore]
2019-11-28 21:41:29 +08:00
public virtual Type[] IncompatibleMods => Array.Empty<Type>();
2023-04-26 03:05:40 +08:00
private IReadOnlyDictionary<string, IBindable>? settingsBacking;
/// <summary>
2023-04-26 03:05:40 +08:00
/// All <see cref="IBindable"/> settings within this mod.
/// </summary>
/// <remarks>
2023-05-05 00:30:41 +08:00
/// The settings are returned in ascending key order as per <see cref="SettingsMap"/>.
/// The ordering is intentionally enforced manually, as ordering of <see cref="Dictionary{TKey,TValue}.Values"/> is unspecified.
/// </remarks>
2023-05-05 00:30:41 +08:00
internal IEnumerable<IBindable> SettingsBindables => SettingsMap.OrderBy(pair => pair.Key).Select(pair => pair.Value);
2023-04-26 03:05:40 +08:00
/// <summary>
/// Provides mapping of names to <see cref="IBindable"/>s of all settings within this mod.
/// </summary>
2023-05-05 00:30:41 +08:00
internal IReadOnlyDictionary<string, IBindable> SettingsMap =>
settingsBacking ??= this.GetSettingsSourceProperties()
2023-04-26 03:05:40 +08:00
.Select(p => p.Item2)
.ToDictionary(property => property.Name.ToSnakeCase(), property => (IBindable)property.GetValue(this)!);
/// <summary>
/// Whether all settings in this mod are set to their default state.
/// </summary>
2023-12-29 16:16:16 +08:00
public virtual bool UsesDefaultConfiguration => SettingsBindables.All(s => s.IsDefault);
/// <summary>
/// Creates a copy of this <see cref="Mod"/> initialised to a default state.
/// </summary>
public virtual Mod DeepClone()
2020-08-13 18:48:31 +08:00
{
var result = (Mod)Activator.CreateInstance(GetType())!;
result.CopyFrom(this);
return result;
}
/// <summary>
2023-02-22 03:59:36 +08:00
/// Copies mod setting values from <paramref name="source"/> into this instance, overwriting all existing settings.
/// </summary>
/// <param name="source">The mod to copy properties from.</param>
2023-02-22 03:59:36 +08:00
public void CopyFrom(Mod source)
{
2023-02-22 03:59:36 +08:00
if (source.GetType() != GetType())
throw new ArgumentException($"Expected mod of type {GetType()}, got {source.GetType()}.", nameof(source));
foreach (var (_, property) in this.GetSettingsSourceProperties())
{
var targetBindable = (IBindable)property.GetValue(this)!;
2023-02-22 03:59:36 +08:00
var sourceBindable = (IBindable)property.GetValue(source)!;
2023-02-22 03:59:36 +08:00
CopyAdjustedSetting(targetBindable, sourceBindable);
}
}
/// <summary>
2023-05-05 00:33:49 +08:00
/// This method copies the values of all settings from <paramref name="source"/> that share the same names with this mod instance.
/// The most frequent use of this is when switching rulesets, in order to preserve values of common settings during the switch.
/// </summary>
2023-05-05 00:33:49 +08:00
/// <remarks>
/// The values are copied directly, without adjusting for possibly different allowed ranges of values.
/// If the value of a setting is not valid for this instance due to not falling inside of the allowed range, it will be clamped accordingly.
/// </remarks>
2023-04-26 03:05:40 +08:00
/// <param name="source">The mod to extract settings from.</param>
public void CopyCommonSettingsFrom(Mod source)
{
2023-04-26 03:05:40 +08:00
if (source.UsesDefaultConfiguration)
return;
2023-02-22 03:59:36 +08:00
2023-05-05 00:30:41 +08:00
foreach (var (name, targetSetting) in SettingsMap)
2023-02-22 03:59:36 +08:00
{
2023-05-05 00:30:41 +08:00
if (!source.SettingsMap.TryGetValue(name, out IBindable? sourceSetting))
2023-02-22 03:59:36 +08:00
continue;
2023-04-26 03:05:40 +08:00
if (sourceSetting.IsDefault)
continue;
2023-03-12 06:29:36 +08:00
2023-05-05 01:06:07 +08:00
var targetBindableType = targetSetting.GetType();
var sourceBindableType = sourceSetting.GetType();
2023-04-26 16:46:29 +08:00
2023-05-05 01:06:07 +08:00
// if either the target is assignable to the source or the source is assignable to the target,
// then we presume that the data types contained in both bindables are compatible and we can proceed with the copy.
// this handles cases like `Bindable<int>` and `BindableInt`.
if (!targetBindableType.IsAssignableFrom(sourceBindableType) && !sourceBindableType.IsAssignableFrom(targetBindableType))
2023-03-12 06:29:36 +08:00
continue;
2023-04-26 03:05:40 +08:00
// TODO: special case for handling number types
2023-04-26 03:05:40 +08:00
PropertyInfo property = targetSetting.GetType().GetProperty(nameof(Bindable<bool>.Value))!;
property.SetValue(targetSetting, property.GetValue(sourceSetting));
2020-08-13 18:48:31 +08:00
}
}
/// <summary>
2021-01-03 20:30:21 +08:00
/// When creating copies or clones of a Mod, this method will be called
/// to copy explicitly adjusted user settings from <paramref name="target"/>.
/// The base implementation will transfer the value via <see cref="Bindable{T}.Parse"/>
/// or by binding and unbinding (if <paramref name="source"/> is an <see cref="IBindable"/>)
/// and should be called unless replaced with custom logic.
/// </summary>
2021-01-03 20:30:21 +08:00
/// <param name="target">The target bindable to apply the adjustment to.</param>
2021-01-03 20:25:44 +08:00
/// <param name="source">The adjustment to apply.</param>
internal virtual void CopyAdjustedSetting(IBindable target, object source)
{
2021-01-03 20:25:44 +08:00
if (source is IBindable sourceBindable)
{
2021-01-03 20:30:21 +08:00
// copy including transfer of default values.
2021-01-03 20:25:44 +08:00
target.BindTo(sourceBindable);
target.UnbindFrom(sourceBindable);
2020-08-13 18:48:31 +08:00
}
else
{
if (!(target is IParseable parseable))
2021-04-16 14:40:06 +08:00
throw new InvalidOperationException($"Bindable type {target.GetType().ReadableName()} is not {nameof(IParseable)}.");
2023-12-13 13:07:38 +08:00
parseable.Parse(source, CultureInfo.InvariantCulture);
}
2020-08-13 18:48:31 +08:00
}
public bool Equals(IMod? other) => other is Mod them && Equals(them);
public bool Equals(Mod? other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return GetType() == other.GetType() &&
2023-04-26 03:05:40 +08:00
SettingsBindables.SequenceEqual(other.SettingsBindables, ModSettingsEqualityComparer.Default);
}
2021-08-17 09:27:04 +08:00
public override int GetHashCode()
{
var hashCode = new HashCode();
hashCode.Add(GetType());
2023-04-26 03:05:40 +08:00
foreach (var setting in SettingsBindables)
hashCode.Add(setting.GetUnderlyingSettingValue());
2021-08-17 09:27:04 +08:00
return hashCode.ToHashCode();
}
/// <summary>
/// Reset all custom settings for this mod back to their defaults.
/// </summary>
public virtual void ResetSettingsToDefaults() => CopyFrom((Mod)Activator.CreateInstance(GetType())!);
private class ModSettingsEqualityComparer : IEqualityComparer<IBindable>
{
public static ModSettingsEqualityComparer Default { get; } = new ModSettingsEqualityComparer();
public bool Equals(IBindable? x, IBindable? y)
{
object? xValue = x?.GetUnderlyingSettingValue();
object? yValue = y?.GetUnderlyingSettingValue();
return EqualityComparer<object>.Default.Equals(xValue, yValue);
}
public int GetHashCode(IBindable obj) => obj.GetUnderlyingSettingValue().GetHashCode();
}
}
2017-03-02 08:57:33 +08:00
}