Files
wwdpublic/Content.Server/Chemistry/EntitySystems/InjectorSystem.cs
RedFoxIV daf4f66414 "Proper" "Softcrit" "Support" (#1545)
# Description

Implements the softcrit functionality.
Similiar to critical state but spessmen will be able to communicate and
crawl around, but not pick up items.
Also supports configuring what is and isn't allowed in different
MobStates (per mob prototype): you can enable picking up items while in
softcrit so people can pick up their lasgun and continue shooting after
taking a 40x46mm to their ass cheeks from the guest nukies while being
dragged to safety.

![escape-from-tarkov-raid](https://github.com/user-attachments/assets/7f31702d-5677-4daf-a13d-8a9525fd3f9f)

<details> <summary><h1>Technical details</h1></summary>
New prototype type: "mobStateParams" (`MobStateParametersPrototype`)
Used to specify what can and can't be done when in a certain mobstate.
Of note that they are not actually bound to any `MobState` by
themselves. To assign a params prototype to a mobstate, use
`InitMobStateParams` in `MobStateComponent`.
It has to be a prototype because if I just did something akin to
`Dictionary<MobState, Dictionary<string, bool>>`, you'd have to check
the parent and copy every flag besides the one you wish to modify. That
is, if I understand how the prototype system works correctly, which I
frankly doubt. <!-- Working on softcrit made me hate prototypes. -->

MobStateComponent now has:
- `Dictionary<string, string> InitMobStateParams`, for storing "mobstate
- parameter prototype" pairs. `<string, string>` because it has to be
editable via mob prototypes. Named "mobStateParams" for mob prototypes.
- `public Dictionary<MobState, MobStateParametersPrototype>
MobStateParams` for actually storing the params for each state
- `public Dictionary<MobState, MobStateParametersOverride>
MobStateParamsOverrides` for storing overrides.
`MobStateParametersOverride` is a struct which mirrors all
`MobStateParametersPrototype`'s fields, except they're all nullable.
This is meant for code which wants to temporarily override some setting,
like a spell which allows dead people to talk. This is not the best
solution, but it should do at first. A better option would be tracking
each change separately, instead of hoping different systems overriding
the same flag will play nicely with eachother.
- a shitton of getter methods

TraitModifyMobState now has:
- `public Dictionary<string, string> Params` to specify a new prototype
to use.
- Important note: All values of `MobStateParametersPrototype` are
nullable, which is a hack to support `TraitModifyMobState`. This trait
takes one `MobStateParametersPrototype` per mobstate and applies all of
its non-null values. This way, a params prototype can be created which
will only have `pointing: true` and the trait can apply it (e.g. to
critstate, so we can spam pointing while dying like it's a game of turbo
dota)
- The above is why that wall of getters exists: They check the relevant
override struct, then the relevant prototype. If both are null, they
default to false (0f for floats.) The only exception is
OxyDamageOverlay, because it's used both for oxy damage overlay (if
null) and as a vision-limiting black void in crit..

MobStateSystem now has:
- a bunch of new "IsSomething"/"CanDoSomething" methods to check the
various flags, alongside rewritten old ones.
-
![image](https://github.com/user-attachments/assets/33a6b296-c12c-4311-9abe-90ca4288e871)
lookin ahh predicate factory

</details>
---

# TODO

done:
- [x] Make proper use of `MobStateSystem.IsIncapacitated()`.
done: some checks were changed, some left as they did what was (more or
less) intended.
<details>Previous `IsIncapacitated()` implementation simply checked if
person was in crit or dead. Now there is a `IsIncapacitated` flag in the
parameters, but it's heavily underutilized. I may need some help on this
one, since I don't know where would be a good place to check for it and
I absolutely will not just scour the entire build in search for them.
</details>

- [x] Separate force-dropping items from being downed
done: dropItemsOnEntering bool field. If true, will drop items upon
entering linked mobstate.
- [x] Don't drop items if `ForceDown` is true but `PickingUp` is also
true.
done: dropItemsOnEntering bool field. If true, will drop items upon
entering linked mobstate.
- [x] Actually check what are "conscious attempts" are used for
done: whether or not mob is conscious. Renamed the bool field
accordingly.
- [x] Look into adding a way to make people choke "slowly" in softcrit
as opposed to choking at "regular speed" in crit. Make that into a param
option? Make that into a float so the speed can be finetuned?
done: `BreathingMultiplier` float field added.
<details>
1f is regular breathing, 0.25 is "quarter-breathing". Air taken is
multiplied by `BreathingMultiplier` and suffocation damage taken (that
is dealt by RespiratorSystem, not all oxy damage) is multiplied by
`1-BreathingMultiplier`.
</details>

- [x] make sure the serializer actually does its job
done: it doesn't. Removed.
- [x] Make an option to prohibit using radio headsets while in softcrit
done: Requires Incapacitated parameter to be false to be able to use
headset radio.
- [x] Make sure it at least compiles

not done:
- [ ] probably move some other stuff to Params if it makes sense. Same
thing as with `IsIncapacitated` though: I kinda don't want to, at least
for now.

---

<details><summary><h1>No media</h1></summary>
<p>

:p

</p>
</details>

---

# Changelog

🆑
- add: Soft critical state. Crawl to safety, or to your doom - whatever
is closer.

---------

Signed-off-by: RedFoxIV <38788538+RedFoxIV@users.noreply.github.com>
Co-authored-by: VMSolidus <evilexecutive@gmail.com>

(cherry picked from commit 9a357c1774f1a783844a07b5414f504ca574d84c)
2025-02-15 00:12:50 +03:00

426 lines
17 KiB
C#

using Content.Server.Abilities.Chitinid;
using Content.Server.Body.Components;
using Content.Server.Body.Systems;
using Content.Server.Chat.Managers;
using Content.Shared.Chat;
using Content.Shared.Chemistry;
using Content.Shared.Chemistry.Components;
using Content.Shared.Chemistry.Components.SolutionManager;
using Content.Shared.Chemistry.EntitySystems;
using Content.Shared.Chemistry.Reagent;
using Content.Shared.Database;
using Content.Shared.DoAfter;
using Content.Shared.FixedPoint;
using Content.Shared.Forensics;
using Content.Shared.IdentityManagement;
using Content.Shared.Interaction;
using Content.Shared.Mobs.Components;
using Content.Shared.Stacks;
using Robust.Server.Player;
namespace Content.Server.Chemistry.EntitySystems;
public sealed class InjectorSystem : SharedInjectorSystem
{
[Dependency] private readonly BloodstreamSystem _blood = default!;
[Dependency] private readonly ReactiveSystem _reactiveSystem = default!;
[Dependency] private readonly IChatManager _chat = default!;
[Dependency] private readonly IPlayerManager _playerManager = default!;
private const ChatChannel BlockInjectionDenyChannel = ChatChannel.Emotes;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<InjectorComponent, InjectorDoAfterEvent>(OnInjectDoAfter);
SubscribeLocalEvent<InjectorComponent, AfterInteractEvent>(OnInjectorAfterInteract);
}
private void UseInjector(Entity<InjectorComponent> injector, EntityUid target, EntityUid user)
{
// Handle injecting/drawing for solutions
if (injector.Comp.ToggleState == InjectorToggleMode.Inject)
{
if (SolutionContainers.TryGetInjectableSolution(target, out var injectableSolution, out _))
{
TryInject(injector, target, injectableSolution.Value, user, false);
}
else if (SolutionContainers.TryGetRefillableSolution(target, out var refillableSolution, out _))
{
TryInject(injector, target, refillableSolution.Value, user, true);
}
else if (TryComp<BloodstreamComponent>(target, out var bloodstream))
{
TryInjectIntoBloodstream(injector, (target, bloodstream), user);
}
else
{
Popup.PopupEntity(Loc.GetString("injector-component-cannot-transfer-message",
("target", Identity.Entity(target, EntityManager))), injector, user);
}
}
else if (injector.Comp.ToggleState == InjectorToggleMode.Draw)
{
// Draw from a bloodstream, if the target has that
if (TryComp<BloodstreamComponent>(target, out var stream) &&
SolutionContainers.ResolveSolution(target, stream.BloodSolutionName, ref stream.BloodSolution))
{
TryDraw(injector, (target, stream), stream.BloodSolution.Value, user);
return;
}
// Draw from an object (food, beaker, etc)
if (SolutionContainers.TryGetDrawableSolution(target, out var drawableSolution, out _))
{
TryDraw(injector, target, drawableSolution.Value, user);
}
else
{
Popup.PopupEntity(Loc.GetString("injector-component-cannot-draw-message",
("target", Identity.Entity(target, EntityManager))), injector.Owner, user);
}
}
}
private void OnInjectDoAfter(Entity<InjectorComponent> entity, ref InjectorDoAfterEvent args)
{
if (args.Cancelled || args.Handled || args.Args.Target == null)
return;
UseInjector(entity, args.Args.Target.Value, args.Args.User);
args.Handled = true;
}
private void OnInjectorAfterInteract(Entity<InjectorComponent> entity, ref AfterInteractEvent args)
{
if (args.Handled || !args.CanReach)
return;
//Make sure we have the attacking entity
if (args.Target is not { Valid: true } target || !HasComp<SolutionContainerManagerComponent>(entity))
return;
// Is the target a mob? If yes, use a do-after to give them time to respond.
if (HasComp<MobStateComponent>(target) || HasComp<BloodstreamComponent>(target))
{
// Are use using an injector capible of targeting a mob?
if (entity.Comp.IgnoreMobs)
return;
InjectDoAfter(entity, target, args.User);
args.Handled = true;
return;
}
UseInjector(entity, target, args.User);
args.Handled = true;
}
/// <summary>
/// Send informative pop-up messages and wait for a do-after to complete.
/// </summary>
private void InjectDoAfter(Entity<InjectorComponent> injector, EntityUid target, EntityUid user)
{
if (TryComp<BlockInjectionComponent>(target, out var blockComponent)) // DeltaV
{
var msg = Loc.GetString($"injector-component-deny-{blockComponent.BlockReason}");
Popup.PopupEntity(msg, target, user);
if (!_playerManager.TryGetSessionByEntity(target, out var session))
return;
_chat.ChatMessageToOne(
BlockInjectionDenyChannel,
msg,
msg,
EntityUid.Invalid,
false,
session.Channel);
return;
}
// Create a pop-up for the user
if (injector.Comp.ToggleState == InjectorToggleMode.Draw)
{
Popup.PopupEntity(Loc.GetString("injector-component-drawing-user"), target, user);
}
else
{
Popup.PopupEntity(Loc.GetString("injector-component-injecting-user"), target, user);
}
if (!SolutionContainers.TryGetSolution(injector.Owner, injector.Comp.SolutionName, out _, out var solution))
return;
var actualDelay = MathHelper.Max(injector.Comp.Delay, TimeSpan.FromSeconds(1));
float amountToInject;
if (injector.Comp.ToggleState == InjectorToggleMode.Draw)
{
// additional delay is based on actual volume left to draw in syringe when smaller than transfer amount
amountToInject = Math.Min(injector.Comp.TransferAmount.Float(), (solution.MaxVolume - solution.Volume).Float());
}
else
{
// additional delay is based on actual volume left to inject in syringe when smaller than transfer amount
amountToInject = Math.Min(injector.Comp.TransferAmount.Float(), solution.Volume.Float());
}
// Injections take 0.5 seconds longer per 5u of possible space/content
actualDelay += TimeSpan.FromSeconds(amountToInject / 10);
var isTarget = user != target;
if (isTarget)
{
// Create a pop-up for the target
var userName = Identity.Entity(user, EntityManager);
if (injector.Comp.ToggleState == InjectorToggleMode.Draw)
{
Popup.PopupEntity(Loc.GetString("injector-component-drawing-target",
("user", userName)), user, target);
}
else
{
Popup.PopupEntity(Loc.GetString("injector-component-injecting-target",
("user", userName)), user, target);
}
// Check if the target is incapacitated or in combat mode and modify time accordingly.
if (MobState.IsIncapacitated(target) /*|| _statusEffects.TryGetTime(target, "Stun", out var _)*/)
{
actualDelay /= 2.5f;
}
else if (Combat.IsInCombatMode(target))
{
// Slightly increase the delay when the target is in combat mode. Helps prevents cheese injections in
// combat with fast syringes & lag.
actualDelay += TimeSpan.FromSeconds(1);
}
// Add an admin log, using the "force feed" log type. It's not quite feeding, but the effect is the same.
if (injector.Comp.ToggleState == InjectorToggleMode.Inject)
{
AdminLogger.Add(LogType.ForceFeed,
$"{EntityManager.ToPrettyString(user):user} is attempting to inject {EntityManager.ToPrettyString(target):target} with a solution {SharedSolutionContainerSystem.ToPrettyString(solution):solution}");
}
else
{
AdminLogger.Add(LogType.ForceFeed,
$"{EntityManager.ToPrettyString(user):user} is attempting to draw {injector.Comp.TransferAmount.ToString()} units from {EntityManager.ToPrettyString(target):target}");
}
}
else
{
// Self-injections take half as long.
actualDelay /= 2;
if (injector.Comp.ToggleState == InjectorToggleMode.Inject)
{
AdminLogger.Add(LogType.Ingestion,
$"{EntityManager.ToPrettyString(user):user} is attempting to inject themselves with a solution {SharedSolutionContainerSystem.ToPrettyString(solution):solution}.");
}
else
{
AdminLogger.Add(LogType.ForceFeed,
$"{EntityManager.ToPrettyString(user):user} is attempting to draw {injector.Comp.TransferAmount.ToString()} units from themselves.");
}
}
DoAfter.TryStartDoAfter(new DoAfterArgs(EntityManager, user, actualDelay, new InjectorDoAfterEvent(), injector.Owner, target: target, used: injector.Owner)
{
BreakOnMove = true,
BreakOnWeightlessMove = false,
BreakOnDamage = true,
NeedHand = true,
BreakOnHandChange = true,
MovementThreshold = 0.1f,
});
}
private void TryInjectIntoBloodstream(Entity<InjectorComponent> injector, Entity<BloodstreamComponent> target,
EntityUid user)
{
// Get transfer amount. May be smaller than _transferAmount if not enough room
if (!SolutionContainers.ResolveSolution(target.Owner, target.Comp.ChemicalSolutionName,
ref target.Comp.ChemicalSolution, out var chemSolution))
{
Popup.PopupEntity(
Loc.GetString("injector-component-cannot-inject-message",
("target", Identity.Entity(target, EntityManager))), injector.Owner, user);
return;
}
var realTransferAmount = FixedPoint2.Min(injector.Comp.TransferAmount, chemSolution.AvailableVolume);
if (realTransferAmount <= 0)
{
Popup.PopupEntity(
Loc.GetString("injector-component-cannot-inject-message",
("target", Identity.Entity(target, EntityManager))), injector.Owner, user);
return;
}
// Move units from attackSolution to targetSolution
var removedSolution = SolutionContainers.SplitSolution(target.Comp.ChemicalSolution.Value, realTransferAmount);
_blood.TryAddToChemicals(target, removedSolution, target.Comp);
_reactiveSystem.DoEntityReaction(target, removedSolution, ReactionMethod.Injection);
Popup.PopupEntity(Loc.GetString("injector-component-inject-success-message",
("amount", removedSolution.Volume),
("target", Identity.Entity(target, EntityManager))), injector.Owner, user);
Dirty(injector);
AfterInject(injector, target);
}
private void TryInject(Entity<InjectorComponent> injector, EntityUid targetEntity,
Entity<SolutionComponent> targetSolution, EntityUid user, bool asRefill)
{
if (HasComp<BlockInjectionComponent>(targetEntity)) // DeltaV
return;
if (!SolutionContainers.TryGetSolution(injector.Owner, injector.Comp.SolutionName, out var soln,
out var solution) || solution.Volume == 0)
return;
// Get transfer amount. May be smaller than _transferAmount if not enough room
var realTransferAmount =
FixedPoint2.Min(injector.Comp.TransferAmount, targetSolution.Comp.Solution.AvailableVolume);
if (realTransferAmount <= 0)
{
Popup.PopupEntity(
Loc.GetString("injector-component-target-already-full-message",
("target", Identity.Entity(targetEntity, EntityManager))),
injector.Owner, user);
return;
}
// Move units from attackSolution to targetSolution
Solution removedSolution;
if (TryComp<StackComponent>(targetEntity, out var stack))
removedSolution = SolutionContainers.SplitStackSolution(soln.Value, realTransferAmount, stack.Count);
else
removedSolution = SolutionContainers.SplitSolution(soln.Value, realTransferAmount);
_reactiveSystem.DoEntityReaction(targetEntity, removedSolution, ReactionMethod.Injection);
if (!asRefill)
SolutionContainers.Inject(targetEntity, targetSolution, removedSolution);
else
SolutionContainers.Refill(targetEntity, targetSolution, removedSolution);
Popup.PopupEntity(Loc.GetString("injector-component-transfer-success-message",
("amount", removedSolution.Volume),
("target", Identity.Entity(targetEntity, EntityManager))), injector.Owner, user);
Dirty(injector);
AfterInject(injector, targetEntity);
}
private void AfterInject(Entity<InjectorComponent> injector, EntityUid target)
{
// Automatically set syringe to draw after completely draining it.
if (SolutionContainers.TryGetSolution(injector.Owner, injector.Comp.SolutionName, out _,
out var solution) && solution.Volume == 0)
{
SetMode(injector, InjectorToggleMode.Draw);
}
// Leave some DNA from the injectee on it
var ev = new TransferDnaEvent { Donor = target, Recipient = injector };
RaiseLocalEvent(target, ref ev);
}
private void AfterDraw(Entity<InjectorComponent> injector, EntityUid target)
{
// Automatically set syringe to inject after completely filling it.
if (SolutionContainers.TryGetSolution(injector.Owner, injector.Comp.SolutionName, out _,
out var solution) && solution.AvailableVolume == 0)
{
SetMode(injector, InjectorToggleMode.Inject);
}
// Leave some DNA from the drawee on it
var ev = new TransferDnaEvent { Donor = target, Recipient = injector };
RaiseLocalEvent(target, ref ev);
}
private void TryDraw(Entity<InjectorComponent> injector, Entity<BloodstreamComponent?> target,
Entity<SolutionComponent> targetSolution, EntityUid user)
{
if (!SolutionContainers.TryGetSolution(injector.Owner, injector.Comp.SolutionName, out var soln,
out var solution) || solution.AvailableVolume == 0)
{
return;
}
// Get transfer amount. May be smaller than _transferAmount if not enough room, also make sure there's room in the injector
var realTransferAmount = FixedPoint2.Min(injector.Comp.TransferAmount, targetSolution.Comp.Solution.Volume,
solution.AvailableVolume);
if (realTransferAmount <= 0)
{
Popup.PopupEntity(
Loc.GetString("injector-component-target-is-empty-message",
("target", Identity.Entity(target, EntityManager))),
injector.Owner, user);
return;
}
// We have some snowflaked behavior for streams.
if (target.Comp != null)
{
DrawFromBlood(injector, (target.Owner, target.Comp), soln.Value, realTransferAmount, user);
return;
}
// Move units from attackSolution to targetSolution
var removedSolution = SolutionContainers.Draw(target.Owner, targetSolution, realTransferAmount);
if (!SolutionContainers.TryAddSolution(soln.Value, removedSolution))
{
return;
}
Popup.PopupEntity(Loc.GetString("injector-component-draw-success-message",
("amount", removedSolution.Volume),
("target", Identity.Entity(target, EntityManager))), injector.Owner, user);
Dirty(injector);
AfterDraw(injector, target);
}
private void DrawFromBlood(Entity<InjectorComponent> injector, Entity<BloodstreamComponent> target,
Entity<SolutionComponent> injectorSolution, FixedPoint2 transferAmount, EntityUid user)
{
var drawAmount = (float) transferAmount;
if (SolutionContainers.ResolveSolution(target.Owner, target.Comp.ChemicalSolutionName,
ref target.Comp.ChemicalSolution))
{
var chemTemp = SolutionContainers.SplitSolution(target.Comp.ChemicalSolution.Value, drawAmount * 0.15f);
SolutionContainers.TryAddSolution(injectorSolution, chemTemp);
drawAmount -= (float) chemTemp.Volume;
}
if (SolutionContainers.ResolveSolution(target.Owner, target.Comp.BloodSolutionName,
ref target.Comp.BloodSolution))
{
var bloodTemp = SolutionContainers.SplitSolution(target.Comp.BloodSolution.Value, drawAmount);
SolutionContainers.TryAddSolution(injectorSolution, bloodTemp);
}
Popup.PopupEntity(Loc.GetString("injector-component-draw-success-message",
("amount", transferAmount),
("target", Identity.Entity(target, EntityManager))), injector.Owner, user);
Dirty(injector);
AfterDraw(injector, target);
}
}