CatStation/Content.Shared/Metabolism/MetabolizerSystem.cs
beck-thompson 266f978228
Add xenoborg bio knife (#45152)
* bio knife

* fix licence

* fix damage override

* remove weird null

* Abstrac the methods

* add new icon

* add bool

* add hash set
2026-08-18 20:13:53 +00:00

382 lines
14 KiB
C#

using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Content.Shared.Body.Events;
using Content.Shared.Body;
using Content.Shared.Chemistry.Components;
using Content.Shared.Chemistry.Components.SolutionManager;
using Content.Shared.Chemistry.EntitySystems;
using Content.Shared.Chemistry.Reagent;
using Content.Shared.EntityConditions;
using Content.Shared.EntityConditions.Conditions;
using Content.Shared.EntityConditions.Conditions.Body;
using Content.Shared.EntityEffects;
using Content.Shared.EntityEffects.Effects.Body;
using Content.Shared.EntityEffects.Effects.Solution;
using Content.Shared.FixedPoint;
using Content.Shared.Mobs.Systems;
using Content.Shared.Random.Helpers;
using Robust.Shared.Prototypes;
using Robust.Shared.Timing;
namespace Content.Shared.Metabolism;
/// <inheritdoc/>
public sealed partial class MetabolizerSystem : EntitySystem
{
[Dependency] private BodySystem _body = default!;
[Dependency] private IGameTiming _gameTiming = default!;
[Dependency] private MobStateSystem _mobStateSystem = default!;
[Dependency] private SharedEntityConditionsSystem _entityConditions = default!;
[Dependency] private SharedEntityEffectsSystem _entityEffects = default!;
[Dependency] private SharedSolutionContainerSystem _solutionContainerSystem = default!;
[Dependency] private EntityQuery<OrganComponent> _organQuery = default!;
[Dependency] private EntityQuery<SolutionManagerComponent> _solutionQuery = default!;
[SubscribeLocalEvent]
private void OnAddMetabolismInit(Entity<AddMetabolismComponent> ent, ref MapInitEvent args)
{
if (ent.Comp.AddedMetabolizer == null)
return;
AddMetabolizerToBody(ent, ent.Comp.AddedMetabolizer.Value);
}
[SubscribeLocalEvent]
private void OnMapInit(Entity<MetabolizerComponent> ent, ref MapInitEvent args)
{
ent.Comp.NextUpdate = _gameTiming.CurTime + ent.Comp.AdjustedUpdateInterval;
Dirty(ent);
}
[SubscribeLocalEvent]
private void OnApplyMetabolicMultiplier(Entity<MetabolizerComponent> ent, ref BodyRelayedEvent<ApplyMetabolicMultiplierEvent> args)
{
ent.Comp.UpdateIntervalMultiplier = args.Args.Multiplier;
Dirty(ent);
}
public override void Update(float frameTime)
{
base.Update(frameTime);
var query = EntityQueryEnumerator<MetabolizerComponent>();
while (query.MoveNext(out var uid, out var comp))
{
// Only update as frequently as it should
if (_gameTiming.CurTime < comp.NextUpdate)
continue;
comp.NextUpdate += comp.AdjustedUpdateInterval;
TryMetabolize((uid, comp));
Dirty(uid, comp);
}
}
/// <summary>
/// Updates the metabolic rate multiplier for a given entity,
/// raising both <see cref="GetMetabolicMultiplierEvent"/> to determine what the multiplier is and <see cref="ApplyMetabolicMultiplierEvent"/> to update relevant components.
/// </summary>
/// <param name="uid"></param>
public void UpdateMetabolicMultiplier(EntityUid uid)
{
var getEv = new GetMetabolicMultiplierEvent();
RaiseLocalEvent(uid, ref getEv);
var applyEv = new ApplyMetabolicMultiplierEvent(getEv.Multiplier);
RaiseLocalEvent(uid, ref applyEv);
}
private bool LookupSolution(
Entity<MetabolizerComponent, OrganComponent?, SolutionManagerComponent?> ent,
MetabolismSolutionEntry solutionData,
bool lookupTransfer,
[NotNullWhen(true)] out Solution? solution,
[NotNullWhen(true)] out Entity<SolutionComponent>? solutionEntity,
[NotNullWhen(true)] out EntityUid? solutionOwner
)
{
solution = null;
solutionEntity = null;
solutionOwner = null;
var solutionName = lookupTransfer ? solutionData.TransferSolutionName : solutionData.SolutionName;
if (solutionName is null)
return false;
if (lookupTransfer ? solutionData.TransferSolutionOnBody : solutionData.SolutionOnBody)
{
if (ent.Comp2?.Body is not { } body)
return false;
if (!_solutionContainerSystem.TryGetSolution(body, solutionName, out solutionEntity, out solution))
return false;
solutionOwner = body;
return true;
}
if (!_solutionContainerSystem.TryGetSolution((ent, ent.Comp3), solutionName, out solutionEntity, out solution))
return false;
solutionOwner = ent;
return true;
}
private void TryMetabolizeStage(Entity<MetabolizerComponent, OrganComponent?, SolutionManagerComponent?> ent, ProtoId<MetabolismStagePrototype> stage)
{
if (!ent.Comp1.Solutions.TryGetValue(stage, out var solutionData))
return;
if (!LookupSolution(ent, solutionData, false, out var solution, out var solutionEntity, out var solutionOwner))
return;
if (solution.Contents.Count == 0)
return;
LookupSolution(ent, solutionData, true, out var transferSolution, out var transferSolutionEntity, out _);
// Copy the solution do not edit the original solution list
var list = solution.Contents.ToList();
// Collecting blood reagent for filtering
var ev = new MetabolismExclusionEvent();
RaiseLocalEvent(solutionOwner.Value, ref ev);
// randomize the reagent list so we don't have any weird quirks
// like alphabetical order or insertion order mattering for processing
var rand = SharedRandomExtensions.PredictedRandom(_gameTiming, GetNetEntity(ent), GetNetEntity(solutionOwner));
rand.Shuffle(list);
var isDead = _mobStateSystem.IsDead(solutionOwner.Value);
int reagents = 0;
foreach (var (reagent, quantity) in list)
{
if (!ProtoMan.TryIndex<ReagentPrototype>(reagent.Prototype, out var proto))
continue;
// Skip blood reagents
if (ev.Reagents.Contains(reagent))
continue;
if (proto.Metabolisms is null || !proto.Metabolisms.Metabolisms.TryGetValue(stage, out var entry))
{
var mostToTransfer = FixedPoint2.Clamp(solutionData.TransferRate, 0, quantity);
if (transferSolution is not null)
{
solution.RemoveReagent(reagent, mostToTransfer);
transferSolution.AddReagent(reagent, mostToTransfer * solutionData.TransferEfficacy);
}
else
{
solution.RemoveReagent(reagent, FixedPoint2.New(1));
}
continue;
}
var rate = solutionData.MetabolizeAll ? quantity : entry.MetabolismRate;
// Remove $rate, as long as there's enough reagent there to actually remove that much
var mostToRemove = FixedPoint2.Clamp(rate, 0, quantity);
// we're done here entirely if this is true
if (reagents >= ent.Comp1.MaxReagentsProcessable)
return;
var scale = (float) mostToRemove;
if (!solutionData.MetabolizeAll)
scale /= (float) rate;
// if it's possible for them to be dead, and they are,
// then we shouldn't process any effects, but should probably
// still remove reagents
if (isDead && !proto.WorksOnTheDead)
continue;
var actualEntity = ent.Comp2?.Body ?? solutionOwner.Value;
// do all effects, if conditions apply
foreach (var effect in entry.Effects)
{
if (scale < effect.MinScale)
continue;
if (rand.NextFloat() >= effect.Probability)
continue;
// See if conditions apply
if (effect.Conditions != null && !CanMetabolizeEffect(actualEntity, ent, solutionEntity.Value, effect.Conditions))
continue;
ApplyEffect(effect);
}
// TODO: We should have to do this with metabolism. ReagentEffect struct needs refactoring and so does metabolism!
void ApplyEffect(EntityEffect effect)
{
switch (effect)
{
case ModifyLungGas:
_entityEffects.ApplyEffect(ent, effect, scale);
break;
case AdjustReagent:
_entityEffects.ApplyEffect(solutionEntity.Value, effect, scale);
break;
default:
_entityEffects.ApplyEffect(actualEntity, effect, scale);
break;
}
}
// remove a certain amount of reagent
if (mostToRemove > FixedPoint2.Zero)
{
solution.RemoveReagent(reagent, mostToRemove);
// We have processed a reagant, so count it towards the cap
reagents += 1;
if (transferSolution is not null && entry.Metabolites is not null)
{
foreach (var (metabolite, ratio) in entry.Metabolites)
{
transferSolution.AddReagent(metabolite, mostToRemove * ratio);
}
}
}
}
_solutionContainerSystem.UpdateChemicals(solutionEntity.Value);
if (transferSolutionEntity is not null)
{
_solutionContainerSystem.UpdateChemicals(transferSolutionEntity.Value);
}
}
private void TryMetabolize(Entity<MetabolizerComponent, OrganComponent?, SolutionManagerComponent?> ent)
{
_organQuery.Resolve(ent, ref ent.Comp2, logMissing: false);
_solutionQuery.Resolve(ent, ref ent.Comp3, logMissing: false);
foreach (var stage in ent.Comp1.Stages)
{
TryMetabolizeStage(ent, stage);
}
}
/// <summary>
/// Public API to check if a certain metabolism effect can be applied to an entity.
/// TODO: With metabolism refactor make this logic smarter and unhardcode the old hardcoding entity effects used to have for metabolism!
/// </summary>
/// <param name="body">The body metabolizing the effects</param>
/// <param name="organ">The organ doing the metabolizing</param>
/// <param name="solution">The solution we are metabolizing from</param>
/// <param name="conditions">The conditions that need to be met to metabolize</param>
/// <returns>True if we can metabolize! False if we cannot!</returns>
public bool CanMetabolizeEffect(EntityUid body, EntityUid organ, Entity<SolutionComponent> solution, EntityCondition[] conditions)
{
foreach (var condition in conditions)
{
switch (condition)
{
// Need specific handling of specific conditions since Metabolism is funny like that.
// TODO: MetabolizerTypes should be handled well before this stage by metabolism itself.
case MetabolizerTypeCondition:
if (_entityConditions.TryCondition(organ, condition))
continue;
break;
case ReagentCondition:
if (_entityConditions.TryCondition(solution, condition))
continue;
break;
default:
if (_entityConditions.TryCondition(body, condition))
continue;
break;
}
return false;
}
return true;
}
/// <summary>
/// Adds a metabolizer type to all organs with <see cref="MetabolizerComponent"/> owned by an entity.
/// </summary>
/// <param name="entity">The entity whose organs to affect.</param>
/// <param name="metabolizer">The metabolizer type to add to the organs.</param>
public void AddMetabolizerToBody(EntityUid entity, ProtoId<MetabolizerTypePrototype> metabolizer)
{
var organs = _body.EnumerateOrgans<MetabolizerComponent>(entity);
foreach (var organ in organs)
{
TryAddMetabolizerType((organ.Owner, organ.Comp2), metabolizer);
}
}
/// <summary>
/// Tries to add a new metabolizer type to an entity with <see cref="MetabolizerComponent"/>
/// </summary>
/// <param name="ent">The metabolizer to add to.</param>
/// <param name="metabolizer">The prototype to add.</param>
/// <returns>True if the type was added, otherwise False.</returns>
public bool TryAddMetabolizerType(Entity<MetabolizerComponent?> ent, ProtoId<MetabolizerTypePrototype> metabolizer)
{
if (!Resolve(ent, ref ent.Comp, false))
return false;
// If there is no metabolizer types, we still want to add one.
if (ent.Comp.MetabolizerTypes == null)
ent.Comp.MetabolizerTypes = new HashSet<ProtoId<MetabolizerTypePrototype>>();
return ent.Comp.MetabolizerTypes.Add(metabolizer);
}
/// <summary>
/// Checks if the given organ has the given metabolizer.
/// </summary>
/// <param name="targetOrgan">The organ we are checking.</param>
/// <param name="targetMetabolizer">The metabolizer we are checking for.</param>
/// <returns>Returns true if the organ has the given metabolizer, false if the organ doesn't (this includes it not being a metabolizer at all)</returns>
public bool HasMetabolizer(Entity<MetabolizerComponent?> targetOrgan, ProtoId<MetabolizerTypePrototype> targetMetabolizer)
{
if (!Resolve(targetOrgan.Owner, ref targetOrgan.Comp, false))
return false;
if (targetOrgan.Comp.MetabolizerTypes is null)
return false;
if (!targetOrgan.Comp.MetabolizerTypes.Contains(targetMetabolizer))
return false;
return true;
}
/// <summary>
/// Checks if a given body has a metabolizer of the target type.
/// </summary>
/// <param name="targetBody">The body we are checking for the metabolizer.</param>
/// <param name="targetMetabolizer">The metabolizer we are checking for.</param>
/// <returns></returns>
public bool BodyHasMetabolizer(EntityUid targetBody, ProtoId<MetabolizerTypePrototype> targetMetabolizer)
{
var metabolisms = _body.EnumerateOrgans<MetabolizerComponent>(targetBody);
foreach (var organ in metabolisms)
{
if (HasMetabolizer((organ, organ.Comp2), targetMetabolizer))
return true;
}
return false;
}
}