CatStation/Content.Server/Fluids/EntitySystems/SmokeSystem.cs
Prole 502af6955d
Predict Forensics V2.0 (Ready for Review) (#40693)
* What sitting on code does to a branch + no mo owner v2

* Replacing ViewVariables with AutoNetworkedField + Missed One V2

* Removing Virtual Methods & Renaming ForensicsSystem to SharedForensicsSystem (Also made it abstract) V2

* IProduceWidgets Review Changes & some of my own V2

* Lil Cleanup V2

* Part 1 of Review Changes (Only thing left is the BUI stuff and the constructor) V2

* It now WORKS!!! (Still needs the BUI and constuctor changes, ill figure it out later)

* Test (Removal of ServerSide VomitSystem.cs)

* Ok...

* Moved System BloodstreamSystem.cs to SharedBloodstreamSystem.cs & deleted client BloodStreamSystem.cs to make SharedBloodstreamSystem.cs sealed. (No Unregistered errors)

* Prediction

* Fix?

* No mo log error?

* Revert "No mo log error?"

This reverts commit 50c15a3deab6af9dffd7baed45820bae5558e41f.

* Constructor going up

* No ForensicScannerBoundUserInterface.cs (It doesnt wanna scan anymore but it doesnt crash)

* For Conflicts

* Guh

* Yea

* Organization & no ErrorHell (maybe)

* Dirtying

* Dirtying take 2

* Revert "Dirtying take 2"

This reverts commit 5735012e21f43808db3ae010fce268eac24d0583.

* the dirties dont do much here

* For Conflict

* Readded

* Another Conflict Commit Fix

* Conflict Fix Thrice

* Empty Space

* Keep it simple

* Add it back in

* Move BloodstreamSystem stuff thats causing the error back to system. This'll prob fix the conflict

* Conflict fix?

* Trust the fix

* Looked at other prediction PR's, they had better code.

* To not mix up the system in client

* Removing Conflict

* For conflict

* For the conflic fix, will be removed later

* Scuffed Fix

* Removal & Adding the Decouple

* Took some HEAVY pointers from SirWarocks work. The Roadblock has been CLEARED, DOAFTERS WORK NOW!!

* Cleanup & Optimizing, mostly comps.

* More Optimization, most of this is just imported Warock Code, his QOL included. Did not want to remove SolutionDNA's tho, mostly due to a Log.Debug in OnPrint.

* Forgot that the Print Refreshes, more of Warocks work.

* Removing Loc.GetString

* All of BloodStream to Shared, hopefully no errors.

* Sketchy Dirty Removed

* Removed Timer.Spawn, added FrameUpdate cause anything else only updated when the window opened, & a bit of cleanup.

* No mo Mispredict

* GenerateDnaEvent Predicted

* Forgot the user

* I knew it was real, bloodstutter is REAL and now GONE.

* Cant dirty NewEntityBloodData due to potential stutter, so its safer to put it all back into server. again...

* Clearer

* Thank you leahcat, no more identity leak.

* Routine Maintenance

* sealing the class

* it checks for this now?!

* While im here, FileScope Namespaces & removing unused namespaces

* Update Attribute Type (SirWarock Import), it works and is much easier to read.

* Forever Fixing Conflicts

* Readonly Genocide & Partial Maxing

* LGTM, BloodstreamSystem moved to SharedBloodstreamSystem!

* Sohn

* If OG Github back push this commit

* One Billionth Commit Fix

* Removed client/server stuff

* Made implicit

* NewLine & comment on why AutoGenCompState is true

* Updatin the rest of the Popups to use Entity

* I think that's what they meant? It looks cleaner at least.

* Mass Attribute for LocalEvents that are safe to change.

* Putting it back as abstract

* maybe?

* Guhh, rolling back empty client/server of BloodStream

* Removed Client/Server BloodstreamSystems, changed access modifier from protected to private, & renamed SharedBloodstreamSystem to BloodstreamSystem

* From Protected to Private

* Removed comment & made it explicit on what changed to true

* Guh, hopefully thats all of it...

* Forgot

* Review

* Test Push

* Line 316 in SharedForensicsSystem was causing the errors, better to play it safe

* Review Changes

* Update Content.Shared/Forensics/Events.cs

Co-authored-by: Whatstone <166147148+whatston3@users.noreply.github.com>

* The only thing SolutionDNAs does is search and clears itself. I see no reason to keep it

* The print.disabled didnt properly disable when cleared. So ill just use the old if check

* Figured out the rest of the SubscribeLocalEvents and networking BloodData cause its fully in Shared

---------

Co-authored-by: Whatstone <166147148+whatston3@users.noreply.github.com>
2026-08-08 22:48:36 +00:00

342 lines
13 KiB
C#

using Content.Server.Administration.Logs;
using Content.Server.Body.Systems;
using Content.Server.Spreader;
using Content.Shared.Body.Components;
using Content.Shared.Chemistry;
using Content.Shared.Chemistry.Components;
using Content.Shared.Chemistry.EntitySystems;
using Content.Shared.Chemistry.Reaction;
using Content.Shared.Chemistry.Reagent;
using Content.Shared.Database;
using Content.Shared.FixedPoint;
using Content.Shared.Smoking;
using Robust.Server.GameObjects;
using Robust.Shared.Map.Components;
using Robust.Shared.Physics;
using Robust.Shared.Physics.Components;
using Robust.Shared.Physics.Events;
using Robust.Shared.Physics.Systems;
using Robust.Shared.Random;
using Robust.Shared.Timing;
using System.Linq;
using Content.Shared.Body.Systems;
using Content.Shared.EntityEffects.Effects.Solution;
using TimedDespawnComponent = Robust.Shared.Spawners.TimedDespawnComponent;
namespace Content.Server.Fluids.EntitySystems;
/// <summary>
/// Handles non-atmos solution entities similar to puddles.
/// </summary>
public sealed partial class SmokeSystem : EntitySystem
{
// If I could do it all again this could probably use a lot more of puddles.
[Dependency] private IAdminLogManager _logger = default!;
[Dependency] private IGameTiming _timing = default!;
[Dependency] private SharedMapSystem _map = default!;
[Dependency] private IRobustRandom _random = default!;
[Dependency] private AppearanceSystem _appearance = default!;
[Dependency] private BloodstreamSystem _blood = default!;
[Dependency] private InternalsSystem _internals = default!;
[Dependency] private ReactiveSystem _reactive = default!;
[Dependency] private SharedBroadphaseSystem _broadphase = default!;
[Dependency] private SharedPhysicsSystem _physics = default!;
[Dependency] private SharedSolutionContainerSystem _solutionContainerSystem = default!;
[Dependency] private EntityQuery<SmokeComponent> _smokeQuery = default!;
[Dependency] private EntityQuery<SmokeAffectedComponent> _smokeAffectedQuery = default!;
/// <inheritdoc/>
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<SmokeComponent, StartCollideEvent>(OnStartCollide);
SubscribeLocalEvent<SmokeComponent, EndCollideEvent>(OnEndCollide);
SubscribeLocalEvent<SmokeComponent, ReactionAttemptEvent>(OnReactionAttempt);
SubscribeLocalEvent<SmokeComponent, SolutionRelayEvent<ReactionAttemptEvent>>(OnReactionAttempt);
SubscribeLocalEvent<SmokeComponent, SpreadNeighborsEvent>(OnSmokeSpread);
}
/// <inheritdoc/>
public override void Update(float frameTime)
{
base.Update(frameTime);
var query = EntityQueryEnumerator<SmokeAffectedComponent>();
var curTime = _timing.CurTime;
while (query.MoveNext(out var uid, out var smoke))
{
if (curTime < smoke.NextSecond)
continue;
smoke.NextSecond += TimeSpan.FromSeconds(1);
SmokeReact(uid, smoke.SmokeEntity);
}
}
private void OnStartCollide(Entity<SmokeComponent> entity, ref StartCollideEvent args)
{
if (_smokeAffectedQuery.HasComponent(args.OtherEntity))
return;
var smokeAffected = AddComp<SmokeAffectedComponent>(args.OtherEntity);
smokeAffected.SmokeEntity = entity;
smokeAffected.NextSecond = _timing.CurTime + TimeSpan.FromSeconds(1);
}
private void OnEndCollide(Entity<SmokeComponent> entity, ref EndCollideEvent args)
{
// if we are already in smoke, make sure the thing we are exiting is the current smoke we are in.
if (_smokeAffectedQuery.TryGetComponent(args.OtherEntity, out var smokeAffectedComponent))
{
if (smokeAffectedComponent.SmokeEntity != entity.Owner)
return;
}
var exists = Exists(entity);
if (!TryComp<PhysicsComponent>(args.OtherEntity, out var body))
return;
foreach (var ent in _physics.GetContactingEntities(args.OtherEntity, body))
{
if (exists && ent == entity.Owner)
continue;
if (!_smokeQuery.HasComponent(ent))
continue;
smokeAffectedComponent ??= EnsureComp<SmokeAffectedComponent>(args.OtherEntity);
smokeAffectedComponent.SmokeEntity = ent;
return; // exit the function so we don't remove the component.
}
if (smokeAffectedComponent != null)
RemComp(args.OtherEntity, smokeAffectedComponent);
}
private void OnSmokeSpread(Entity<SmokeComponent> entity, ref SpreadNeighborsEvent args)
{
if (entity.Comp.SpreadAmount == 0 || !_solutionContainerSystem.ResolveSolution(entity.Owner, SmokeComponent.SolutionName, ref entity.Comp.Solution, out var solution))
{
RemCompDeferred<ActiveEdgeSpreaderComponent>(entity);
return;
}
if (Prototype(entity) is not { } prototype)
{
RemCompDeferred<ActiveEdgeSpreaderComponent>(entity);
return;
}
if (args.NeighborFreeTiles.Count == 0)
return;
TryComp<TimedDespawnComponent>(entity, out var timer);
// wtf is the logic behind any of this.
var smokePerSpread = entity.Comp.SpreadAmount / Math.Max(1, args.NeighborFreeTiles.Count);
foreach (var neighbor in args.NeighborFreeTiles)
{
var coords = _map.GridTileToLocal(neighbor.Tile.GridUid, neighbor.Grid, neighbor.Tile.GridIndices);
var ent = Spawn(prototype.ID, coords);
var spreadAmount = Math.Max(0, smokePerSpread);
entity.Comp.SpreadAmount -= args.NeighborFreeTiles.Count;
StartSmoke(ent, solution.Clone(), timer?.Lifetime ?? entity.Comp.Duration, spreadAmount);
if (entity.Comp.SpreadAmount == 0)
{
RemCompDeferred<ActiveEdgeSpreaderComponent>(entity);
break;
}
}
args.Updates--;
if (args.NeighborFreeTiles.Count > 0 || args.Neighbors.Count == 0 || entity.Comp.SpreadAmount < 1)
return;
// We have no more neighbours to spread to. So instead we will randomly distribute our volume to neighbouring smoke tiles.
_random.Shuffle(args.Neighbors);
foreach (var neighbor in args.Neighbors)
{
if (!_smokeQuery.TryGetComponent(neighbor, out var smoke))
continue;
smoke.SpreadAmount++;
entity.Comp.SpreadAmount--;
EnsureComp<ActiveEdgeSpreaderComponent>(neighbor);
if (entity.Comp.SpreadAmount == 0)
{
RemCompDeferred<ActiveEdgeSpreaderComponent>(entity);
break;
}
}
}
private void OnReactionAttempt(Entity<SmokeComponent> entity, ref ReactionAttemptEvent args)
{
if (args.Cancelled)
return;
// Prevent smoke/foam fork bombs (smoke creating more smoke).
foreach (var effect in args.Reaction.Effects)
{
if (effect is AreaReactionEffect)
{
args.Cancelled = true;
return;
}
}
}
private void OnReactionAttempt(Entity<SmokeComponent> entity, ref SolutionRelayEvent<ReactionAttemptEvent> args)
{
if (args.Solution.Comp.Id == SmokeComponent.SolutionName)
OnReactionAttempt(entity, ref args.Event);
}
/// <summary>
/// Sets up a smoke component for spreading.
/// </summary>
public void StartSmoke(EntityUid uid, Solution solution, float duration, int spreadAmount, SmokeComponent? component = null)
{
if (!Resolve(uid, ref component))
return;
component.SpreadAmount = spreadAmount;
component.Duration = duration;
component.TransferRate = solution.Volume / duration;
TryAddSolution(uid, solution);
Dirty(uid, component);
EnsureComp<ActiveEdgeSpreaderComponent>(uid);
if (TryComp<PhysicsComponent>(uid, out var body) && TryComp<FixturesComponent>(uid, out var fixtures))
{
var xform = Transform(uid);
_physics.SetBodyType(uid, BodyType.Dynamic, fixtures, body, xform);
_physics.SetCanCollide(uid, true, manager: fixtures, body: body);
_broadphase.RegenerateContacts((uid, body, fixtures, xform));
}
var timer = EnsureComp<TimedDespawnComponent>(uid);
timer.Lifetime = duration;
// The tile reaction happens here because it only occurs once.
ReactOnTile(uid, component);
}
/// <summary>
/// Does the relevant smoke reactions for an entity.
/// </summary>
public void SmokeReact(EntityUid entity, EntityUid smokeUid, SmokeComponent? component = null)
{
if (!Resolve(smokeUid, ref component))
return;
if (!_solutionContainerSystem.ResolveSolution(smokeUid, SmokeComponent.SolutionName, ref component.Solution, out var solution) ||
solution.Contents.Count == 0)
{
return;
}
ReactWithEntity(entity, smokeUid, solution, component);
UpdateVisuals((smokeUid, component));
}
private void ReactWithEntity(EntityUid entity, EntityUid smokeUid, Solution solution, SmokeComponent? component = null)
{
if (!Resolve(smokeUid, ref component))
return;
if (!TryComp<BloodstreamComponent>(entity, out var bloodstream))
return;
if (!_solutionContainerSystem.ResolveSolution(entity, bloodstream.BloodSolutionName, ref bloodstream.BloodSolution, out var bloodSolution) || bloodSolution.AvailableVolume <= 0)
return;
var blockIngestion = _internals.AreInternalsWorking(entity);
var cloneSolution = solution.Clone();
var availableTransfer = FixedPoint2.Min(cloneSolution.Volume, component.TransferRate);
var transferAmount = FixedPoint2.Min(availableTransfer, bloodSolution.AvailableVolume);
var transferSolution = cloneSolution.SplitSolution(transferAmount);
foreach (var reagentQuantity in transferSolution.Contents.ToArray())
{
if (reagentQuantity.Quantity == FixedPoint2.Zero)
continue;
_reactive.ReactionEntity(entity, ReactionMethod.Touch, reagentQuantity);
if (!blockIngestion)
_reactive.ReactionEntity(entity, ReactionMethod.Ingestion, reagentQuantity);
}
if (blockIngestion)
return;
if (_blood.TryAddToBloodstream((entity, bloodstream), transferSolution))
{
// Log solution addition by smoke
_logger.Add(LogType.ForceFeed, LogImpact.Medium, $"{ToPrettyString(entity):target} ingested smoke {SharedSolutionContainerSystem.ToPrettyString(transferSolution)}");
}
}
private void ReactOnTile(EntityUid uid, SmokeComponent? component = null, TransformComponent? xform = null)
{
if (!Resolve(uid, ref component, ref xform))
return;
if (!_solutionContainerSystem.ResolveSolution(uid, SmokeComponent.SolutionName, ref component.Solution, out var solution) || !solution.Any())
return;
if (!TryComp<MapGridComponent>(xform.GridUid, out var mapGrid))
return;
var tile = _map.GetTileRef(xform.GridUid.Value, mapGrid, xform.Coordinates);
foreach (var reagentQuantity in solution.Contents.ToArray())
{
if (reagentQuantity.Quantity == FixedPoint2.Zero)
continue;
var reagent = ProtoMan.Index<ReagentPrototype>(reagentQuantity.Reagent.Prototype);
reagent.ReactionTile(tile, reagentQuantity.Quantity, EntityManager, reagentQuantity.Reagent.Data);
}
}
/// <summary>
/// Adds the specified solution to the relevant smoke solution.
/// </summary>
private void TryAddSolution(Entity<SmokeComponent?> smoke, Solution solution)
{
if (solution.Volume == FixedPoint2.Zero)
return;
if (!Resolve(smoke, ref smoke.Comp))
return;
if (!_solutionContainerSystem.ResolveSolution(smoke.Owner, SmokeComponent.SolutionName, ref smoke.Comp.Solution, out var solutionArea))
return;
var addSolution = solution.SplitSolution(FixedPoint2.Min(solution.Volume, solutionArea.AvailableVolume));
_solutionContainerSystem.TryAddSolution(smoke.Comp.Solution.Value, addSolution);
UpdateVisuals(smoke);
}
private void UpdateVisuals(Entity<SmokeComponent?, AppearanceComponent?> smoke)
{
if (!Resolve(smoke, ref smoke.Comp1, ref smoke.Comp2) ||
!_solutionContainerSystem.ResolveSolution(smoke.Owner, SmokeComponent.SolutionName, ref smoke.Comp1.Solution, out var solution))
return;
var color = solution.GetColor(ProtoMan);
_appearance.SetData(smoke.Owner, SmokeVisuals.Color, color, smoke.Comp2);
}
}