Hunger ECS (#14939)

This commit is contained in:
Nemanja
2023-04-02 22:42:30 -04:00
committed by GitHub
parent 19277a2276
commit 0f0b534239
14 changed files with 440 additions and 364 deletions

View File

@@ -0,0 +1,151 @@
using Content.Shared.Alert;
using Content.Shared.Damage;
using Content.Shared.Nutrition.EntitySystems;
using Robust.Shared.GameStates;
using Robust.Shared.Serialization;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Generic;
namespace Content.Shared.Nutrition.Components;
[RegisterComponent, NetworkedComponent, Access(typeof(HungerSystem))]
public sealed class HungerComponent : Component
{
/// <summary>
/// The current hunger amount of the entity
/// </summary>
[DataField("currentHunger"), ViewVariables(VVAccess.ReadWrite)]
public float CurrentHunger;
/// <summary>
/// The base amount at which <see cref="CurrentHunger"/> decays.
/// </summary>
[DataField("baseDecayRate"), ViewVariables(VVAccess.ReadWrite)]
public float BaseDecayRate = 0.01666666666f;
/// <summary>
/// The actual amount at which <see cref="CurrentHunger"/> decays.
/// Affected by <seealso cref="CurrentThreshold"/>
/// </summary>
[DataField("actualDecayRate"), ViewVariables(VVAccess.ReadWrite)]
public float ActualDecayRate;
/// <summary>
/// The last threshold this entity was at.
/// Stored in order to prevent recalculating
/// </summary>
[DataField("lastThreshold"), ViewVariables(VVAccess.ReadWrite)]
public HungerThreshold LastThreshold;
/// <summary>
/// The current hunger threshold the entity is at
/// </summary>
[DataField("currentThreshold"), ViewVariables(VVAccess.ReadWrite)]
public HungerThreshold CurrentThreshold;
/// <summary>
/// A dictionary relating HungerThreshold to the amount of <see cref="CurrentHunger"/> needed for each one
/// </summary>
[DataField("thresholds", customTypeSerializer: typeof(DictionarySerializer<HungerThreshold, float>))]
public Dictionary<HungerThreshold, float> Thresholds = new()
{
{ HungerThreshold.Overfed, 200.0f },
{ HungerThreshold.Okay, 150.0f },
{ HungerThreshold.Peckish, 100.0f },
{ HungerThreshold.Starving, 50.0f },
{ HungerThreshold.Dead, 0.0f }
};
/// <summary>
/// A dictionary relating hunger thresholds to corresponding alerts.
/// </summary>
[DataField("hungerThresholdAlerts", customTypeSerializer: typeof(DictionarySerializer<HungerThreshold, AlertType>))]
public Dictionary<HungerThreshold, AlertType> HungerThresholdAlerts = new()
{
{ HungerThreshold.Peckish, AlertType.Peckish },
{ HungerThreshold.Starving, AlertType.Starving },
{ HungerThreshold.Dead, AlertType.Starving }
};
/// <summary>
/// A dictionary relating HungerThreshold to how much they modify <see cref="BaseDecayRate"/>.
/// </summary>
[DataField("hungerThresholdDecayModifiers", customTypeSerializer: typeof(DictionarySerializer<HungerThreshold, float>))]
public Dictionary<HungerThreshold, float> HungerThresholdDecayModifiers = new()
{
{ HungerThreshold.Overfed, 1.2f },
{ HungerThreshold.Okay, 1f },
{ HungerThreshold.Peckish, 0.8f },
{ HungerThreshold.Starving, 0.6f },
{ HungerThreshold.Dead, 0.6f }
};
/// <summary>
/// The amount of slowdown applied when an entity is starving
/// </summary>
[DataField("starvingSlowdownModifier"), ViewVariables(VVAccess.ReadWrite)]
public float StarvingSlowdownModifier = 0.75f;
/// <summary>
/// Damage dealt when your current threshold is at HungerThreshold.Dead
/// </summary>
[DataField("starvationDamage")]
public DamageSpecifier? StarvationDamage;
/// <summary>
/// The time when the hunger will update next.
/// </summary>
[DataField("nextUpdateTime", customTypeSerializer: typeof(TimeOffsetSerializer)), ViewVariables(VVAccess.ReadWrite)]
public TimeSpan NextUpdateTime;
/// <summary>
/// The time between each update.
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
public TimeSpan UpdateRate = TimeSpan.FromSeconds(1);
}
[Serializable, NetSerializable]
public sealed class HungerComponentState : ComponentState
{
public float CurrentHunger;
public float BaseDecayRate;
public float ActualDecayRate;
public HungerThreshold LastHungerThreshold;
public HungerThreshold CurrentThreshold;
public float StarvingSlowdownModifier;
public TimeSpan NextUpdateTime;
public HungerComponentState(float currentHunger,
float baseDecayRate,
float actualDecayRate,
HungerThreshold lastHungerThreshold,
HungerThreshold currentThreshold,
float starvingSlowdownModifier,
TimeSpan nextUpdateTime)
{
CurrentHunger = currentHunger;
BaseDecayRate = baseDecayRate;
ActualDecayRate = actualDecayRate;
LastHungerThreshold = lastHungerThreshold;
CurrentThreshold = currentThreshold;
StarvingSlowdownModifier = starvingSlowdownModifier;
NextUpdateTime = nextUpdateTime;
}
}
[Serializable, NetSerializable]
public enum HungerThreshold : byte
{
Overfed = 1 << 3,
Okay = 1 << 2,
Peckish = 1 << 1,
Starving = 1 << 0,
Dead = 0,
}

View File

@@ -1,33 +0,0 @@
using Robust.Shared.GameStates;
using Robust.Shared.Serialization;
namespace Content.Shared.Nutrition.Components
{
[NetworkedComponent()]
public abstract class SharedHungerComponent : Component
{
[ViewVariables]
public abstract HungerThreshold CurrentHungerThreshold { get; }
[Serializable, NetSerializable]
protected sealed class HungerComponentState : ComponentState
{
public HungerThreshold CurrentThreshold { get; }
public HungerComponentState(HungerThreshold currentThreshold)
{
CurrentThreshold = currentThreshold;
}
}
}
[Serializable, NetSerializable]
public enum HungerThreshold : byte
{
Overfed = 1 << 3,
Okay = 1 << 2,
Peckish = 1 << 1,
Starving = 1 << 0,
Dead = 0,
}
}

View File

@@ -0,0 +1,226 @@
using Content.Shared.Alert;
using Content.Shared.Damage;
using Content.Shared.Mobs.Systems;
using Content.Shared.Movement.Systems;
using Content.Shared.Nutrition.Components;
using Content.Shared.Rejuvenate;
using Robust.Shared.GameStates;
using Robust.Shared.Random;
using Robust.Shared.Timing;
namespace Content.Shared.Nutrition.EntitySystems;
public sealed class HungerSystem : EntitySystem
{
[Dependency] private readonly IGameTiming _timing = default!;
[Dependency] private readonly IRobustRandom _random = default!;
[Dependency] private readonly AlertsSystem _alerts = default!;
[Dependency] private readonly DamageableSystem _damageable = default!;
[Dependency] private readonly MobStateSystem _mobState = default!;
[Dependency] private readonly MovementSpeedModifierSystem _movementSpeedModifier = default!;
[Dependency] private readonly SharedJetpackSystem _jetpack = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<HungerComponent, ComponentGetState>(OnGetState);
SubscribeLocalEvent<HungerComponent, ComponentHandleState>(OnHandleState);
SubscribeLocalEvent<HungerComponent, EntityUnpausedEvent>(OnUnpaused);
SubscribeLocalEvent<HungerComponent, MapInitEvent>(OnMapInit);
SubscribeLocalEvent<HungerComponent, ComponentShutdown>(OnShutdown);
SubscribeLocalEvent<HungerComponent, RefreshMovementSpeedModifiersEvent>(OnRefreshMovespeed);
SubscribeLocalEvent<HungerComponent, RejuvenateEvent>(OnRejuvenate);
}
private void OnGetState(EntityUid uid, HungerComponent component, ref ComponentGetState args)
{
args.State = new HungerComponentState(component.CurrentHunger,
component.BaseDecayRate,
component.ActualDecayRate,
component.LastThreshold,
component.CurrentThreshold,
component.StarvingSlowdownModifier,
component.NextUpdateTime);
}
private void OnHandleState(EntityUid uid, HungerComponent component, ref ComponentHandleState args)
{
if (args.Current is not HungerComponentState state)
return;
component.CurrentHunger = state.CurrentHunger;
component.BaseDecayRate = state.BaseDecayRate;
component.ActualDecayRate = state.ActualDecayRate;
component.LastThreshold = state.LastHungerThreshold;
component.CurrentThreshold = state.CurrentThreshold;
component.StarvingSlowdownModifier = state.StarvingSlowdownModifier;
component.NextUpdateTime = state.NextUpdateTime;
}
private void OnUnpaused(EntityUid uid, HungerComponent component, ref EntityUnpausedEvent args)
{
component.NextUpdateTime += args.PausedTime;
}
private void OnMapInit(EntityUid uid, HungerComponent component, MapInitEvent args)
{
var amount = _random.Next(
(int) component.Thresholds[HungerThreshold.Peckish] + 10,
(int) component.Thresholds[HungerThreshold.Okay]);
SetHunger(uid, amount, component);
}
private void OnShutdown(EntityUid uid, HungerComponent component, ComponentShutdown args)
{
_alerts.ClearAlertCategory(uid, AlertCategory.Hunger);
}
private void OnRefreshMovespeed(EntityUid uid, HungerComponent component, RefreshMovementSpeedModifiersEvent args)
{
if (component.CurrentThreshold > HungerThreshold.Starving)
return;
if (_jetpack.IsUserFlying(uid))
return;
args.ModifySpeed(component.StarvingSlowdownModifier, component.StarvingSlowdownModifier);
}
private void OnRejuvenate(EntityUid uid, HungerComponent component, RejuvenateEvent args)
{
SetHunger(uid, component.Thresholds[HungerThreshold.Okay], component);
}
/// <summary>
/// Adds to the current hunger of an entity by the specified value
/// </summary>
/// <param name="uid"></param>
/// <param name="amount"></param>
/// <param name="component"></param>
public void ModifyHunger(EntityUid uid, float amount, HungerComponent? component = null)
{
if (!Resolve(uid, ref component))
return;
SetHunger(uid, component.CurrentHunger + amount, component);
}
/// <summary>
/// Sets the current hunger of an entity to the specified value
/// </summary>
/// <param name="uid"></param>
/// <param name="amount"></param>
/// <param name="component"></param>
public void SetHunger(EntityUid uid, float amount, HungerComponent? component = null)
{
if (!Resolve(uid, ref component))
return;
component.CurrentHunger = Math.Clamp(amount,
component.Thresholds[HungerThreshold.Dead],
component.Thresholds[HungerThreshold.Overfed]);
UpdateCurrentThreshold(uid, component);
Dirty(component);
}
private void UpdateCurrentThreshold(EntityUid uid, HungerComponent? component = null)
{
if (!Resolve(uid, ref component))
return;
var calculatedHungerThreshold = GetHungerThreshold(component);
if (calculatedHungerThreshold == component.CurrentThreshold)
return;
component.CurrentThreshold = calculatedHungerThreshold;
DoHungerThresholdEffects(uid, component);
Dirty(component);
}
private void DoHungerThresholdEffects(EntityUid uid, HungerComponent? component = null, bool force = false)
{
if (!Resolve(uid, ref component))
return;
if (component.CurrentThreshold == component.LastThreshold && !force)
return;
if (GetMovementThreshold(component.CurrentThreshold) != GetMovementThreshold(component.LastThreshold))
{
_movementSpeedModifier.RefreshMovementSpeedModifiers(uid);
}
if (component.HungerThresholdAlerts.TryGetValue(component.CurrentThreshold, out var alertId))
{
_alerts.ShowAlert(uid, alertId);
}
else
{
_alerts.ClearAlertCategory(uid, AlertCategory.Hunger);
}
if (component.StarvationDamage is { } damage && !_mobState.IsDead(uid))
{
_damageable.TryChangeDamage(uid, damage, true, false);
}
if (component.HungerThresholdDecayModifiers.TryGetValue(component.CurrentThreshold, out var modifier))
{
component.ActualDecayRate = component.BaseDecayRate * modifier;
}
component.LastThreshold = component.CurrentThreshold;
}
/// <summary>
/// Gets the hunger threshold for an entity based on the amount of food specified.
/// If a specific amount isn't specified, just uses the current hunger of the entity
/// </summary>
/// <param name="component"></param>
/// <param name="food"></param>
/// <returns></returns>
public HungerThreshold GetHungerThreshold(HungerComponent component, float? food = null)
{
food ??= component.CurrentHunger;
var result = HungerThreshold.Dead;
var value = component.Thresholds[HungerThreshold.Overfed];
foreach (var threshold in component.Thresholds)
{
if (threshold.Value <= value && threshold.Value >= food)
{
result = threshold.Key;
value = threshold.Value;
}
}
return result;
}
private bool GetMovementThreshold(HungerThreshold threshold)
{
switch (threshold)
{
case HungerThreshold.Overfed:
case HungerThreshold.Okay:
return true;
case HungerThreshold.Peckish:
case HungerThreshold.Starving:
case HungerThreshold.Dead:
return false;
default:
throw new ArgumentOutOfRangeException(nameof(threshold), threshold, null);
}
}
public override void Update(float frameTime)
{
base.Update(frameTime);
var query = EntityQueryEnumerator<HungerComponent>();
while (query.MoveNext(out var uid, out var hunger))
{
if (_timing.CurTime < hunger.NextUpdateTime)
continue;
hunger.NextUpdateTime = _timing.CurTime + hunger.UpdateRate;
ModifyHunger(uid, -hunger.ActualDecayRate, hunger);
}
}
}

View File

@@ -1,26 +0,0 @@
using Content.Shared.Movement.Systems;
using Content.Shared.Nutrition.Components;
namespace Content.Shared.Nutrition.EntitySystems
{
public sealed class SharedHungerSystem : EntitySystem
{
[Dependency] private readonly SharedJetpackSystem _jetpack = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<SharedHungerComponent, RefreshMovementSpeedModifiersEvent>(OnRefreshMovespeed);
}
private void OnRefreshMovespeed(EntityUid uid, SharedHungerComponent component, RefreshMovementSpeedModifiersEvent args)
{
if (_jetpack.IsUserFlying(component.Owner))
return;
float mod = component.CurrentHungerThreshold <= HungerThreshold.Starving ? 0.75f : 1.0f;
args.ModifySpeed(mod, mod);
}
}
}