Salvage magnet revamp (#23119)

* Generic offering window

* More work

* weh

* Parity

* Progression meter

* magnet

* rona

* PG asteroid work

* code red

* Asteroid spawnings

* clams

* a

* Marker fixes

* More fixes

* Workings of biome asteroids

* A

* Fix this loading code

* a

* Fix masking

* weh

* Fixes

* Magnet claiming

* toe

* petogue

* magnet

* Bunch of fixes

* Fix default

* Fixes

* asteroids

* Fix offerings

* Localisation and a bunch of fixes

* a

* Fixes

* Preliminary draft

* Announcement fixes

* Fixes and bump spawn rate

* Fix asteroid spawns and UI

* More fixes

* Expeditions fix

* fix

* Gravity

* Fix announcement rounding

* a

* Offset tweak

* sus

* jankass

* Fix merge
This commit is contained in:
metalgearsloth
2024-01-04 14:25:32 +11:00
committed by GitHub
parent 98f5f47355
commit bf79acd127
66 changed files with 2257 additions and 1252 deletions

View File

@@ -5,6 +5,9 @@ using Robust.Shared.Random;
namespace Content.Server.Salvage;
/// <summary>
/// Transports attached entities to the linked beacon after a timer has elapsed.
/// </summary>
public sealed class FultonSystem : SharedFultonSystem
{
[Dependency] private readonly IRobustRandom _random = default!;

View File

@@ -0,0 +1,7 @@
namespace Content.Server.Salvage.Magnet;
[RegisterComponent]
public sealed partial class SalvageMagnetComponent : Component
{
}

View File

@@ -0,0 +1,57 @@
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom;
namespace Content.Server.Salvage.Magnet;
/// <summary>
/// Added to the station to hold salvage magnet data.
/// </summary>
[RegisterComponent]
public sealed partial class SalvageMagnetDataComponent : Component
{
// May be multiple due to splitting.
/// <summary>
/// Entities currently magnetised.
/// </summary>
[DataField]
public List<EntityUid>? ActiveEntities;
/// <summary>
/// If the magnet is currently active when does it end.
/// </summary>
[DataField(customTypeSerializer:typeof(TimeOffsetSerializer))]
public TimeSpan? EndTime;
[DataField(customTypeSerializer:typeof(TimeOffsetSerializer))]
public TimeSpan NextOffer;
/// <summary>
/// How long salvage will be active for before despawning.
/// </summary>
[DataField]
public TimeSpan ActiveTime = TimeSpan.FromMinutes(6);
/// <summary>
/// Cooldown between offerings after one ends.
/// </summary>
[DataField]
public TimeSpan OfferCooldown = TimeSpan.FromMinutes(3);
/// <summary>
/// Seeds currently offered
/// </summary>
[DataField]
public List<int> Offered = new();
[DataField]
public int OfferCount = 6;
[DataField]
public int ActiveSeed;
/// <summary>
/// Final countdown announcement.
/// </summary>
[DataField]
public bool Announced;
}

View File

@@ -0,0 +1,14 @@
namespace Content.Server.Salvage.Magnet;
/// <summary>
/// Indicates the entity is a salvage target for tracking.
/// </summary>
[RegisterComponent]
public sealed partial class SalvageMagnetTargetComponent : Component
{
/// <summary>
/// Entity that spawned us.
/// </summary>
[DataField]
public EntityUid DataTarget;
}

View File

@@ -0,0 +1,12 @@
namespace Content.Server.Salvage.Magnet;
// This is dumb
/// <summary>
/// Deletes the attached entity if the linked entity is deleted.
/// </summary>
[RegisterComponent]
public sealed partial class SalvageMobRestrictionsComponent : Component
{
[DataField, ViewVariables(VVAccess.ReadWrite)]
public EntityUid LinkedEntity;
}

View File

@@ -1,14 +0,0 @@
namespace Content.Server.Salvage
{
/// <summary>
/// A grid spawned by a salvage magnet.
/// </summary>
[RegisterComponent]
public sealed partial class SalvageGridComponent : Component
{
/// <summary>
/// The magnet that spawned this grid.
/// </summary>
public EntityUid? SpawnerMagnet;
}
}

View File

@@ -1,138 +0,0 @@
using Content.Shared.Radio;
using Content.Shared.Random;
using Content.Shared.Salvage;
using Robust.Shared.GameStates;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype;
namespace Content.Server.Salvage
{
/// <summary>
/// A salvage magnet.
/// </summary>
[NetworkedComponent, RegisterComponent]
[Access(typeof(SalvageSystem))]
public sealed partial class SalvageMagnetComponent : SharedSalvageMagnetComponent
{
/// <summary>
/// Maximum distance from the offset position that will be used as a salvage's spawnpoint.
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
[DataField("offsetRadiusMax")]
public float OffsetRadiusMax = 32;
/// <summary>
/// The entity attached to the magnet
/// </summary>
[ViewVariables(VVAccess.ReadOnly)]
[DataField("attachedEntity")]
public EntityUid? AttachedEntity;
/// <summary>
/// Current state of this magnet
/// </summary>
[ViewVariables(VVAccess.ReadOnly)]
[DataField("magnetState")]
public MagnetState MagnetState = MagnetState.Inactive;
/// <summary>
/// How long it takes for the magnet to pull in the debris
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
[DataField("baseAttachingTime")]
public TimeSpan BaseAttachingTime = TimeSpan.FromSeconds(30);
/// <summary>
/// How long it actually takes for the magnet to pull in the debris
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
[DataField("attachingTime")]
public TimeSpan AttachingTime = TimeSpan.FromSeconds(30);
/// <summary>
/// How long the magnet can hold the debris until it starts losing the lock
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
[DataField("holdTime")]
public TimeSpan HoldTime = TimeSpan.FromSeconds(240);
/// <summary>
/// How long the magnet can hold the debris while losing the lock
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
[DataField("detachingTime")]
public TimeSpan DetachingTime = TimeSpan.FromSeconds(30);
/// <summary>
/// How long the magnet has to cool down for after use
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
[DataField("baseCooldownTime")]
public TimeSpan BaseCooldownTime = TimeSpan.FromSeconds(60);
/// <summary>
/// How long the magnet actually has to cool down for after use
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
[DataField("cooldownTime")]
public TimeSpan CooldownTime = TimeSpan.FromSeconds(60);
[DataField("salvageChannel", customTypeSerializer: typeof(PrototypeIdSerializer<RadioChannelPrototype>))]
public string SalvageChannel = "Supply";
/// <summary>
/// Current how much charge the magnet currently has
/// </summary>
[DataField("chargeRemaining")]
public int ChargeRemaining = 5;
/// <summary>
/// How much capacity the magnet can hold
/// </summary>
[DataField("chargeCapacity")]
public int ChargeCapacity = 5;
/// <summary>
/// Used as a guard to prevent spamming the appearance system
/// </summary>
[DataField("previousCharge")]
public int PreviousCharge = 5;
/// <summary>
/// The chance that a random procgen asteroid will be
/// generated rather than a static salvage prototype.
/// </summary>
[DataField("asteroidChance"), ViewVariables(VVAccess.ReadWrite)]
public float AsteroidChance = 0.6f;
/// <summary>
/// A weighted random prototype corresponding to
/// what asteroid entities will be generated.
/// </summary>
[DataField("asteroidPool", customTypeSerializer: typeof(PrototypeIdSerializer<WeightedRandomEntityPrototype>)), ViewVariables(VVAccess.ReadWrite)]
public string AsteroidPool = "RandomAsteroidPool";
}
[CopyByRef, DataRecord]
public record struct MagnetState(MagnetStateType StateType, TimeSpan Until)
{
public static readonly MagnetState Inactive = new (MagnetStateType.Inactive, TimeSpan.Zero);
};
public sealed class SalvageMagnetActivatedEvent : EntityEventArgs
{
public EntityUid Magnet;
public SalvageMagnetActivatedEvent(EntityUid magnet)
{
Magnet = magnet;
}
}
public enum MagnetStateType
{
Inactive,
Attaching,
Holding,
Detaching,
CoolingDown,
}
}

View File

@@ -1,20 +0,0 @@
using Robust.Shared.Prototypes;
using Robust.Shared.Utility;
namespace Content.Server.Salvage;
[Prototype("salvageMap")]
public sealed partial class SalvageMapPrototype : IPrototype
{
[ViewVariables] [IdDataField] public string ID { get; } = default!;
/// <summary>
/// Relative directory path to the given map, i.e. `Maps/Salvage/template.yml`
/// </summary>
[DataField("mapPath", required: true)] public ResPath MapPath;
/// <summary>
/// Name for admin use
/// </summary>
[DataField("name")] public string Name = string.Empty;
}

View File

@@ -1,23 +0,0 @@
using Robust.Shared.GameObjects;
using Robust.Shared.Maths;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.ViewVariables;
using System;
namespace Content.Server.Salvage;
/// <summary>
/// This component exists as a sort of stateful marker for a
/// killswitch meant to keep salvage mobs from doing stuff they
/// really shouldn't (attacking station).
/// The main thing is that adding this component ties the mob to
/// whatever it's currently parented to.
/// </summary>
[RegisterComponent]
public sealed partial class SalvageMobRestrictionsComponent : Component
{
[ViewVariables(VVAccess.ReadOnly)]
[DataField("linkedGridEntity")]
public EntityUid LinkedGridEntity = EntityUid.Invalid;
}

View File

@@ -1,23 +0,0 @@
using Robust.Shared.GameObjects;
using Robust.Shared.Maths;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.ViewVariables;
using System;
namespace Content.Server.Salvage;
/// <summary>
/// This component is attached to grids when a salvage mob is
/// spawned on them.
/// This attachment is done by SalvageMobRestrictionsSystem.
/// *Simply put, when this component is removed, the mobs die.*
/// *This applies even if the mobs are off-grid at the time.*
/// </summary>
[RegisterComponent]
public sealed partial class SalvageMobRestrictionsGridComponent : Component
{
[ViewVariables(VVAccess.ReadOnly)]
[DataField("mobsToKill")]
public List<EntityUid> MobsToKill = new();
}

View File

@@ -1,70 +0,0 @@
using Content.Server.Body.Systems;
using Content.Shared.Body.Components;
using Content.Shared.Damage;
using Content.Shared.Mobs.Systems;
namespace Content.Server.Salvage;
public sealed class SalvageMobRestrictionsSystem : EntitySystem
{
[Dependency] private readonly BodySystem _bodySystem = default!;
[Dependency] private readonly DamageableSystem _damageableSystem = default!;
[Dependency] private readonly MobStateSystem _mobStateSystem = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<SalvageMobRestrictionsComponent, ComponentInit>(OnInit);
SubscribeLocalEvent<SalvageMobRestrictionsComponent, ComponentRemove>(OnRemove);
SubscribeLocalEvent<SalvageMobRestrictionsGridComponent, ComponentRemove>(OnRemoveGrid);
}
private void OnInit(EntityUid uid, SalvageMobRestrictionsComponent component, ComponentInit args)
{
var gridUid = Transform(uid).ParentUid;
if (!EntityManager.EntityExists(gridUid))
{
// Give up, we were spawned improperly
return;
}
// When this code runs, the salvage magnet hasn't actually gotten ahold of the entity yet.
// So it therefore isn't in a position to do this.
if (!TryComp(gridUid, out SalvageMobRestrictionsGridComponent? rg))
{
rg = AddComp<SalvageMobRestrictionsGridComponent>(gridUid);
}
rg.MobsToKill.Add(uid);
component.LinkedGridEntity = gridUid;
}
private void OnRemove(EntityUid uid, SalvageMobRestrictionsComponent component, ComponentRemove args)
{
if (TryComp(component.LinkedGridEntity, out SalvageMobRestrictionsGridComponent? rg))
{
rg.MobsToKill.Remove(uid);
}
}
private void OnRemoveGrid(EntityUid uid, SalvageMobRestrictionsGridComponent component, ComponentRemove args)
{
var metaQuery = GetEntityQuery<MetaDataComponent>();
var bodyQuery = GetEntityQuery<BodyComponent>();
var damageQuery = GetEntityQuery<DamageableComponent>();
foreach (var target in component.MobsToKill)
{
if (Deleted(target, metaQuery)) continue;
if (_mobStateSystem.IsDead(target)) continue; // DONT WASTE BIOMASS
if (bodyQuery.TryGetComponent(target, out var body))
{
// Just because.
_bodySystem.GibBody(target, body: body);
}
else if (damageQuery.TryGetComponent(target, out var damageableComponent))
{
_damageableSystem.SetAllDamage(target, damageableComponent, 200);
}
}
}
}

View File

@@ -44,7 +44,7 @@ sealed class SalvageRulerCommand : IConsoleCommand
var first = true;
foreach (var mapGrid in _maps.GetAllGrids(entityTransform.MapID))
{
var aabb = _entities.GetComponent<TransformComponent>(mapGrid).WorldMatrix.TransformBox(mapGrid.Comp.LocalAABB);
var aabb = _entities.System<SharedTransformSystem>().GetWorldMatrix(mapGrid).TransformBox(mapGrid.Comp.LocalAABB);
if (first)
{
total = aabb;

View File

@@ -0,0 +1,408 @@
using System.Linq;
using System.Numerics;
using System.Threading.Tasks;
using Content.Server.Salvage.Magnet;
using Content.Shared.Humanoid;
using Content.Shared.Mobs.Components;
using Content.Shared.Radio;
using Content.Shared.Salvage.Magnet;
using Robust.Server.Maps;
using Robust.Shared.Map;
namespace Content.Server.Salvage;
public sealed partial class SalvageSystem
{
[ValidatePrototypeId<RadioChannelPrototype>]
private const string MagnetChannel = "Supply";
private EntityQuery<SalvageMobRestrictionsComponent> _salvMobQuery;
private void InitializeMagnet()
{
_salvMobQuery = GetEntityQuery<SalvageMobRestrictionsComponent>();
SubscribeLocalEvent<SalvageMagnetDataComponent, MapInitEvent>(OnMagnetDataMapInit);
SubscribeLocalEvent<SalvageMagnetTargetComponent, GridSplitEvent>(OnMagnetTargetSplit);
SubscribeLocalEvent<SalvageMagnetComponent, MagnetClaimOfferEvent>(OnMagnetClaim);
SubscribeLocalEvent<SalvageMagnetComponent, ComponentStartup>(OnMagnetStartup);
SubscribeLocalEvent<SalvageMagnetComponent, AnchorStateChangedEvent>(OnMagnetAnchored);
}
private void OnMagnetClaim(EntityUid uid, SalvageMagnetComponent component, ref MagnetClaimOfferEvent args)
{
var player = args.Session.AttachedEntity;
if (player is null)
return;
var station = _station.GetOwningStation(uid);
if (!TryComp(station, out SalvageMagnetDataComponent? dataComp) ||
dataComp.EndTime != null)
{
return;
}
TakeMagnetOffer((station.Value, dataComp), args.Index, (uid, component));
}
private void OnMagnetStartup(EntityUid uid, SalvageMagnetComponent component, ComponentStartup args)
{
UpdateMagnetUI((uid, component), Transform(uid));
}
private void OnMagnetAnchored(EntityUid uid, SalvageMagnetComponent component, ref AnchorStateChangedEvent args)
{
if (!args.Anchored)
return;
UpdateMagnetUI((uid, component), args.Transform);
}
private void OnMagnetDataMapInit(EntityUid uid, SalvageMagnetDataComponent component, ref MapInitEvent args)
{
CreateMagnetOffers((uid, component));
}
private void OnMagnetTargetSplit(EntityUid uid, SalvageMagnetTargetComponent component, ref GridSplitEvent args)
{
// Don't think I'm not onto you people splitting to make new grids.
if (TryComp(component.DataTarget, out SalvageMagnetDataComponent? dataComp))
{
foreach (var gridUid in args.NewGrids)
{
dataComp.ActiveEntities?.Add(gridUid);
}
}
}
private void UpdateMagnet()
{
var dataQuery = EntityQueryEnumerator<SalvageMagnetDataComponent>();
var curTime = _timing.CurTime;
while (dataQuery.MoveNext(out var uid, out var magnetData))
{
// Magnet currently active.
if (magnetData.EndTime != null)
{
if (magnetData.EndTime.Value < curTime)
{
EndMagnet((uid, magnetData));
}
else if (!magnetData.Announced && (magnetData.EndTime.Value - curTime).TotalSeconds < 31)
{
var magnet = GetMagnet((uid, magnetData));
if (magnet != null)
{
Report(magnet.Value.Owner, MagnetChannel,
"salvage-system-announcement-losing",
("timeLeft", (magnetData.EndTime.Value - curTime).Seconds));
}
magnetData.Announced = true;
}
}
if (magnetData.NextOffer < curTime)
{
CreateMagnetOffers((uid, magnetData));
}
}
}
/// <summary>
/// Ends the magnet attachment and deletes the relevant grids.
/// </summary>
private void EndMagnet(Entity<SalvageMagnetDataComponent> data)
{
if (data.Comp.ActiveEntities != null)
{
// Handle mobrestrictions getting deleted
var query = AllEntityQuery<SalvageMobRestrictionsComponent>();
while (query.MoveNext(out var salvUid, out var salvMob))
{
if (data.Comp.ActiveEntities.Contains(salvMob.LinkedEntity))
{
QueueDel(salvUid);
}
}
// Uhh yeah don't delete mobs or whatever
var mobQuery = AllEntityQuery<HumanoidAppearanceComponent, MobStateComponent, TransformComponent>();
while (mobQuery.MoveNext(out var mobUid, out _, out _, out var xform))
{
if (xform.GridUid == null || !data.Comp.ActiveEntities.Contains(xform.GridUid.Value) || xform.MapUid == null)
continue;
_transform.SetParent(mobUid, xform.MapUid.Value);
}
// Go and cleanup the active ents.
foreach (var ent in data.Comp.ActiveEntities)
{
Del(ent);
}
data.Comp.ActiveEntities = null;
}
data.Comp.EndTime = null;
UpdateMagnetUIs(data);
}
private void CreateMagnetOffers(Entity<SalvageMagnetDataComponent> data)
{
data.Comp.Offered.Clear();
for (var i = 0; i < data.Comp.OfferCount; i++)
{
var seed = _random.Next();
// Fuck with the seed to mix wrecks and asteroids.
seed = (int) (seed / 10f) * 10;
if (i >= data.Comp.OfferCount / 2)
{
seed++;
}
data.Comp.Offered.Add(seed);
}
data.Comp.NextOffer = _timing.CurTime + data.Comp.OfferCooldown;
UpdateMagnetUIs(data);
}
// Just need something to announce.
private Entity<SalvageMagnetComponent>? GetMagnet(Entity<SalvageMagnetDataComponent> data)
{
var query = AllEntityQuery<SalvageMagnetComponent, TransformComponent>();
while (query.MoveNext(out var magnetUid, out var magnet, out var xform))
{
var stationUid = _station.GetOwningStation(magnetUid, xform);
if (stationUid != data.Owner)
continue;
return (magnetUid, magnet);
}
return null;
}
private void UpdateMagnetUI(Entity<SalvageMagnetComponent> entity, TransformComponent xform)
{
var station = _station.GetOwningStation(entity, xform);
if (!TryComp(station, out SalvageMagnetDataComponent? dataComp))
return;
_ui.TrySetUiState(entity, SalvageMagnetUiKey.Key,
new SalvageMagnetBoundUserInterfaceState(dataComp.Offered)
{
Cooldown = dataComp.OfferCooldown,
Duration = dataComp.ActiveTime,
EndTime = dataComp.EndTime,
NextOffer = dataComp.NextOffer,
ActiveSeed = dataComp.ActiveSeed,
});
}
private void UpdateMagnetUIs(Entity<SalvageMagnetDataComponent> data)
{
var query = AllEntityQuery<SalvageMagnetComponent, TransformComponent>();
while (query.MoveNext(out var magnetUid, out var magnet, out var xform))
{
var station = _station.GetOwningStation(magnetUid, xform);
if (station != data.Owner)
continue;
_ui.TrySetUiState(magnetUid, SalvageMagnetUiKey.Key,
new SalvageMagnetBoundUserInterfaceState(data.Comp.Offered)
{
Cooldown = data.Comp.OfferCooldown,
Duration = data.Comp.ActiveTime,
EndTime = data.Comp.EndTime,
NextOffer = data.Comp.NextOffer,
ActiveSeed = data.Comp.ActiveSeed,
});
}
}
private async Task TakeMagnetOffer(Entity<SalvageMagnetDataComponent> data, int index, Entity<SalvageMagnetComponent> magnet)
{
var seed = data.Comp.Offered[index];
var offering = GetSalvageOffering(seed);
var salvMap = _mapManager.CreateMap();
// Set values while awaiting asteroid dungeon if relevant so we can't double-take offers.
data.Comp.ActiveSeed = seed;
data.Comp.EndTime = _timing.CurTime + data.Comp.ActiveTime;
data.Comp.NextOffer = data.Comp.EndTime.Value;
UpdateMagnetUIs(data);
switch (offering)
{
case AsteroidOffering asteroid:
var grid = _mapManager.CreateGrid(salvMap);
await _dungeon.GenerateDungeonAsync(asteroid.DungeonConfig, grid.Owner, grid, Vector2i.Zero, seed);
break;
case SalvageOffering wreck:
var salvageProto = wreck.SalvageMap;
var opts = new MapLoadOptions
{
Offset = new Vector2(0, 0)
};
if (!_map.TryLoad(salvMap, salvageProto.MapPath.ToString(), out var roots, opts))
{
Report(magnet, MagnetChannel, "salvage-system-announcement-spawn-debris-disintegrated");
_mapManager.DeleteMap(salvMap);
return;
}
break;
default:
throw new ArgumentOutOfRangeException();
}
Box2? bounds = null;
var mapXform = _xformQuery.GetComponent(_mapManager.GetMapEntityId(salvMap));
if (mapXform.ChildCount == 0)
{
Report(magnet.Owner, MagnetChannel, "salvage-system-announcement-spawn-no-debris-available");
return;
}
var mapChildren = mapXform.ChildEnumerator;
while (mapChildren.MoveNext(out var mapChild))
{
// If something went awry in dungen.
if (!_gridQuery.TryGetComponent(mapChild, out var childGrid))
continue;
var childAABB = _transform.GetWorldMatrix(mapChild).TransformBox(childGrid.LocalAABB);
bounds = bounds?.Union(childAABB) ?? childAABB;
// Update mass scanner names as relevant.
if (offering is AsteroidOffering)
{
_metaData.SetEntityName(mapChild, Loc.GetString("salvage-asteroid-name"));
_gravity.EnableGravity(mapChild);
}
}
var magnetGridUid = _xformQuery.GetComponent(magnet.Owner).GridUid;
Box2 attachedBounds = Box2.Empty;
MapId mapId = MapId.Nullspace;
if (magnetGridUid != null)
{
var magnetGridXform = _xformQuery.GetComponent(magnetGridUid.Value);
attachedBounds = _transform.GetWorldMatrix(magnetGridXform)
.TransformBox(_gridQuery.GetComponent(magnetGridUid.Value).LocalAABB);
mapId = magnetGridXform.MapID;
}
if (!TryGetSalvagePlacementLocation(mapId, attachedBounds, bounds!.Value, out var spawnLocation, out var spawnAngle))
{
Report(magnet.Owner, MagnetChannel, "salvage-system-announcement-spawn-no-debris-available");
_mapManager.DeleteMap(salvMap);
return;
}
data.Comp.ActiveEntities = null;
mapChildren = mapXform.ChildEnumerator;
// It worked, move it into position and cleanup values.
while (mapChildren.MoveNext(out var mapChild))
{
var salvXForm = _xformQuery.GetComponent(mapChild);
var localPos = salvXForm.LocalPosition;
_transform.SetParent(mapChild, salvXForm, _mapManager.GetMapEntityId(spawnLocation.MapId));
_transform.SetWorldPositionRotation(mapChild, spawnLocation.Position + localPos, spawnAngle, salvXForm);
data.Comp.ActiveEntities ??= new List<EntityUid>();
data.Comp.ActiveEntities?.Add(mapChild);
// Handle mob restrictions
var children = salvXForm.ChildEnumerator;
while (children.MoveNext(out var child))
{
if (!_salvMobQuery.TryGetComponent(child, out var salvMob))
continue;
salvMob.LinkedEntity = mapChild;
}
}
Report(magnet.Owner, MagnetChannel, "salvage-system-announcement-arrived", ("timeLeft", data.Comp.ActiveTime.TotalSeconds));
_mapManager.DeleteMap(salvMap);
data.Comp.Announced = false;
var active = new SalvageMagnetActivatedEvent()
{
Magnet = magnet,
};
RaiseLocalEvent(ref active);
}
private bool TryGetSalvagePlacementLocation(MapId mapId, Box2 attachedBounds, Box2 bounds, out MapCoordinates coords, out Angle angle)
{
const float OffsetRadiusMin = 4f;
const float OffsetRadiusMax = 16f;
var minDistance = (attachedBounds.Height < attachedBounds.Width ? attachedBounds.Width : attachedBounds.Height) / 2f;
var minActualDistance = bounds.Height < bounds.Width ? minDistance + bounds.Width / 2f : minDistance + bounds.Height / 2f;
var attachedCenter = attachedBounds.Center;
angle = _random.NextAngle();
// Thanks 20kdc
for (var i = 0; i < 20; i++)
{
var randomPos = attachedCenter +
_random.NextAngle().ToVec() * (minActualDistance +
_random.NextFloat(OffsetRadiusMin, OffsetRadiusMax));
var finalCoords = new MapCoordinates(randomPos, mapId);
var box2 = Box2.CenteredAround(finalCoords.Position, bounds.Size);
var box2Rot = new Box2Rotated(box2, angle, finalCoords.Position);
// This doesn't stop it from spawning on top of random things in space
// Might be better like this, ghosts could stop it before
if (_mapManager.FindGridsIntersecting(finalCoords.MapId, box2Rot).Any())
continue;
coords = finalCoords;
return true;
}
coords = MapCoordinates.Nullspace;
return false;
}
}
[ByRefEvent]
public record struct SalvageMagnetActivatedEvent
{
public EntityUid Magnet;
}

View File

@@ -17,6 +17,7 @@ using Robust.Shared.Prototypes;
using Robust.Shared.Random;
using Robust.Shared.Utility;
using Content.Server.Chat.Managers;
using Content.Server.Gravity;
using Content.Server.Parallax;
using Content.Server.Procedural;
using Content.Server.Shuttles.Systems;
@@ -46,39 +47,29 @@ namespace Content.Server.Salvage
[Dependency] private readonly AnchorableSystem _anchorable = default!;
[Dependency] private readonly BiomeSystem _biome = default!;
[Dependency] private readonly DungeonSystem _dungeon = default!;
[Dependency] private readonly GravitySystem _gravity = default!;
[Dependency] private readonly MapLoaderSystem _map = default!;
[Dependency] private readonly SharedPopupSystem _popupSystem = default!;
[Dependency] private readonly MetaDataSystem _metaData = default!;
[Dependency] private readonly RadioSystem _radioSystem = default!;
[Dependency] private readonly SharedAppearanceSystem _appearanceSystem = default!;
[Dependency] private readonly SharedAudioSystem _audio = default!;
[Dependency] private readonly SharedTransformSystem _transform = default!;
[Dependency] private readonly ShuttleSystem _shuttle = default!;
[Dependency] private readonly ShuttleConsoleSystem _shuttleConsoles = default!;
[Dependency] private readonly StationSystem _station = default!;
[Dependency] private readonly UserInterfaceSystem _ui = default!;
[Dependency] private readonly MetaDataSystem _metaData = default!;
private const int SalvageLocationPlaceAttempts = 25;
// TODO: This is probably not compatible with multi-station
private readonly Dictionary<EntityUid, SalvageGridState> _salvageGridStates = new();
private EntityQuery<MapGridComponent> _gridQuery;
private EntityQuery<TransformComponent> _xformQuery;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<SalvageMagnetComponent, InteractHandEvent>(OnInteractHand);
SubscribeLocalEvent<SalvageMagnetComponent, RefreshPartsEvent>(OnRefreshParts);
SubscribeLocalEvent<SalvageMagnetComponent, UpgradeExamineEvent>(OnUpgradeExamine);
SubscribeLocalEvent<SalvageMagnetComponent, ExaminedEvent>(OnExamined);
SubscribeLocalEvent<SalvageMagnetComponent, ToolUseAttemptEvent>(OnToolUseAttempt);
SubscribeLocalEvent<SalvageMagnetComponent, ComponentShutdown>(OnMagnetRemoval);
SubscribeLocalEvent<GridRemovalEvent>(OnGridRemoval);
// Can't use RoundRestartCleanupEvent, I need to clean up before the grid, and components are gone to prevent the announcements
SubscribeLocalEvent<GameRunLevelChangedEvent>(OnRoundEnd);
_gridQuery = GetEntityQuery<MapGridComponent>();
_xformQuery = GetEntityQuery<TransformComponent>();
InitializeExpeditions();
InitializeMagnet();
InitializeRunner();
}
@@ -88,327 +79,6 @@ namespace Content.Server.Salvage
ShutdownExpeditions();
}
private void OnRoundEnd(GameRunLevelChangedEvent ev)
{
if(ev.New != GameRunLevel.InRound)
{
_salvageGridStates.Clear();
}
}
private void UpdateAppearance(EntityUid uid, SalvageMagnetComponent? component = null)
{
if (!Resolve(uid, ref component, false))
return;
_appearanceSystem.SetData(uid, SalvageMagnetVisuals.ReadyBlinking, component.MagnetState.StateType == MagnetStateType.Attaching);
_appearanceSystem.SetData(uid, SalvageMagnetVisuals.Ready, component.MagnetState.StateType == MagnetStateType.Holding);
_appearanceSystem.SetData(uid, SalvageMagnetVisuals.Unready, component.MagnetState.StateType == MagnetStateType.CoolingDown);
_appearanceSystem.SetData(uid, SalvageMagnetVisuals.UnreadyBlinking, component.MagnetState.StateType == MagnetStateType.Detaching);
}
private void UpdateChargeStateAppearance(EntityUid uid, TimeSpan currentTime, SalvageMagnetComponent? component = null)
{
if (!Resolve(uid, ref component, false))
return;
var timeLeft = Convert.ToInt32(component.MagnetState.Until.TotalSeconds - currentTime.TotalSeconds);
component.ChargeRemaining = component.MagnetState.StateType switch
{
MagnetStateType.Inactive => 5,
MagnetStateType.Holding => timeLeft / (Convert.ToInt32(component.HoldTime.TotalSeconds) / component.ChargeCapacity) + 1,
MagnetStateType.Detaching => 0,
MagnetStateType.CoolingDown => component.ChargeCapacity - timeLeft / (Convert.ToInt32(component.CooldownTime.TotalSeconds) / component.ChargeCapacity) - 1,
_ => component.ChargeRemaining
};
if (component.PreviousCharge == component.ChargeRemaining)
return;
_appearanceSystem.SetData(uid, SalvageMagnetVisuals.ChargeState, component.ChargeRemaining);
component.PreviousCharge = component.ChargeRemaining;
}
private void OnGridRemoval(GridRemovalEvent ev)
{
// If we ever want to give magnets names, and announce them individually, we would need to loop this, before removing it.
if (_salvageGridStates.Remove(ev.EntityUid))
{
if (TryComp<SalvageGridComponent>(ev.EntityUid, out var salvComp) &&
TryComp<SalvageMagnetComponent>(salvComp.SpawnerMagnet, out var magnet))
Report(salvComp.SpawnerMagnet.Value, magnet.SalvageChannel, "salvage-system-announcement-spawn-magnet-lost");
// For the very unlikely possibility that the salvage magnet was on a salvage, we will not return here
}
foreach(var gridState in _salvageGridStates)
{
foreach(var magnet in gridState.Value.ActiveMagnets)
{
if (!TryComp<SalvageMagnetComponent>(magnet, out var magnetComponent))
continue;
if (magnetComponent.AttachedEntity != ev.EntityUid)
continue;
magnetComponent.AttachedEntity = null;
magnetComponent.MagnetState = MagnetState.Inactive;
return;
}
}
}
private void OnMagnetRemoval(EntityUid uid, SalvageMagnetComponent component, ComponentShutdown args)
{
if (component.MagnetState.StateType == MagnetStateType.Inactive)
return;
var magnetTranform = Transform(uid);
if (magnetTranform.GridUid is not { } gridId || !_salvageGridStates.TryGetValue(gridId, out var salvageGridState))
return;
salvageGridState.ActiveMagnets.Remove(uid);
Report(uid, component.SalvageChannel, "salvage-system-announcement-spawn-magnet-lost");
if (component.AttachedEntity.HasValue)
{
SafeDeleteSalvage(component.AttachedEntity.Value);
component.AttachedEntity = null;
Report(uid, component.SalvageChannel, "salvage-system-announcement-lost");
}
else if (component.MagnetState is { StateType: MagnetStateType.Attaching })
{
Report(uid, component.SalvageChannel, "salvage-system-announcement-spawn-no-debris-available");
}
component.MagnetState = MagnetState.Inactive;
}
private void OnRefreshParts(EntityUid uid, SalvageMagnetComponent component, RefreshPartsEvent args)
{
var rating = args.PartRatings[component.MachinePartDelay] - 1;
var factor = MathF.Pow(component.PartRatingDelay, rating);
component.AttachingTime = component.BaseAttachingTime * factor;
component.CooldownTime = component.BaseCooldownTime * factor;
}
private void OnUpgradeExamine(EntityUid uid, SalvageMagnetComponent component, UpgradeExamineEvent args)
{
args.AddPercentageUpgrade("salvage-system-magnet-delay-upgrade", (float) (component.CooldownTime / component.BaseCooldownTime));
}
private void OnExamined(EntityUid uid, SalvageMagnetComponent component, ExaminedEvent args)
{
if (!args.IsInDetailsRange)
return;
var gotGrid = false;
var remainingTime = TimeSpan.Zero;
if (Transform(uid).GridUid is { } gridId &&
_salvageGridStates.TryGetValue(gridId, out var salvageGridState))
{
remainingTime = component.MagnetState.Until - salvageGridState.CurrentTime;
gotGrid = true;
}
else
{
Log.Warning("Failed to load salvage grid state, can't display remaining time");
}
switch (component.MagnetState.StateType)
{
case MagnetStateType.Inactive:
args.PushMarkup(Loc.GetString("salvage-system-magnet-examined-inactive"));
break;
case MagnetStateType.Attaching:
args.PushMarkup(Loc.GetString("salvage-system-magnet-examined-pulling-in"));
break;
case MagnetStateType.Detaching:
args.PushMarkup(Loc.GetString("salvage-system-magnet-examined-releasing"));
break;
case MagnetStateType.CoolingDown:
if (gotGrid)
args.PushMarkup(Loc.GetString("salvage-system-magnet-examined-cooling-down", ("timeLeft", Math.Ceiling(remainingTime.TotalSeconds))));
break;
case MagnetStateType.Holding:
if (gotGrid)
args.PushMarkup(Loc.GetString("salvage-system-magnet-examined-active", ("timeLeft", Math.Ceiling(remainingTime.TotalSeconds))));
break;
default:
throw new ArgumentOutOfRangeException();
}
}
private void OnToolUseAttempt(EntityUid uid, SalvageMagnetComponent comp, ToolUseAttemptEvent args)
{
// prevent reconstruct exploit to "leak" wrecks or skip cooldowns
if (comp.MagnetState != MagnetState.Inactive)
{
args.Cancel();
}
}
private void OnInteractHand(EntityUid uid, SalvageMagnetComponent component, InteractHandEvent args)
{
if (args.Handled)
return;
args.Handled = true;
StartMagnet(uid, component, args.User);
UpdateAppearance(uid, component);
}
private void StartMagnet(EntityUid uid, SalvageMagnetComponent component, EntityUid user)
{
switch (component.MagnetState.StateType)
{
case MagnetStateType.Inactive:
ShowPopup(uid, "salvage-system-report-activate-success", user);
var magnetTransform = Transform(uid);
var gridId = magnetTransform.GridUid ?? throw new InvalidOperationException("Magnet had no grid associated");
if (!_salvageGridStates.TryGetValue(gridId, out var gridState))
{
gridState = new SalvageGridState();
_salvageGridStates[gridId] = gridState;
}
gridState.ActiveMagnets.Add(uid);
component.MagnetState = new MagnetState(MagnetStateType.Attaching, gridState.CurrentTime + component.AttachingTime);
RaiseLocalEvent(new SalvageMagnetActivatedEvent(uid));
Report(uid, component.SalvageChannel, "salvage-system-report-activate-success");
break;
case MagnetStateType.Attaching:
case MagnetStateType.Holding:
ShowPopup(uid, "salvage-system-report-already-active", user);
break;
case MagnetStateType.Detaching:
case MagnetStateType.CoolingDown:
ShowPopup(uid, "salvage-system-report-cooling-down", user);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
private void ShowPopup(EntityUid uid, string messageKey, EntityUid user)
{
_popupSystem.PopupEntity(Loc.GetString(messageKey), uid, user);
}
private void SafeDeleteSalvage(EntityUid salvage)
{
if(!EntityManager.TryGetComponent<TransformComponent>(salvage, out var salvageTransform))
{
Log.Error("Salvage entity was missing transform component");
return;
}
if (salvageTransform.GridUid == null)
{
Log.Error( "Salvage entity has no associated grid?");
return;
}
foreach (var player in Filter.Empty().AddInGrid(salvageTransform.GridUid.Value, EntityManager).Recipients)
{
if (player.AttachedEntity.HasValue)
{
var playerEntityUid = player.AttachedEntity.Value;
if (HasComp<SalvageMobRestrictionsComponent>(playerEntityUid))
{
// Salvage mobs are NEVER immune (even if they're from a different salvage, they shouldn't be here)
continue;
}
_transform.SetParent(playerEntityUid, salvageTransform.ParentUid);
}
}
// Deletion has to happen before grid traversal re-parents players.
Del(salvage);
}
private bool TryGetSalvagePlacementLocation(EntityUid uid, SalvageMagnetComponent component, Box2 bounds, out MapCoordinates coords, out Angle angle)
{
var xform = Transform(uid);
var smallestBound = (bounds.Height < bounds.Width
? bounds.Height
: bounds.Width) / 2f;
var maxRadius = component.OffsetRadiusMax + smallestBound;
angle = Angle.Zero;
coords = new EntityCoordinates(uid, new Vector2(0, -maxRadius)).ToMap(EntityManager, _transform);
if (xform.GridUid is not null)
angle = _transform.GetWorldRotation(Transform(xform.GridUid.Value));
for (var i = 0; i < SalvageLocationPlaceAttempts; i++)
{
var randomRadius = _random.NextFloat(component.OffsetRadiusMax);
var randomOffset = _random.NextAngle().ToVec() * randomRadius;
var finalCoords = new MapCoordinates(coords.Position + randomOffset, coords.MapId);
var box2 = Box2.CenteredAround(finalCoords.Position, bounds.Size);
var box2Rot = new Box2Rotated(box2, angle, finalCoords.Position);
// This doesn't stop it from spawning on top of random things in space
// Might be better like this, ghosts could stop it before
if (_mapManager.FindGridsIntersecting(finalCoords.MapId, box2Rot).Any())
continue;
coords = finalCoords;
return true;
}
return false;
}
private bool SpawnSalvage(EntityUid uid, SalvageMagnetComponent component)
{
var salvMap = _mapManager.CreateMap();
EntityUid? salvageEnt;
if (_random.Prob(component.AsteroidChance))
{
var asteroidProto = _prototypeManager.Index<WeightedRandomEntityPrototype>(component.AsteroidPool).Pick(_random);
salvageEnt = Spawn(asteroidProto, new MapCoordinates(0, 0, salvMap));
}
else
{
var forcedSalvage = _configurationManager.GetCVar(CCVars.SalvageForced);
var salvageProto = string.IsNullOrWhiteSpace(forcedSalvage)
? _random.Pick(_prototypeManager.EnumeratePrototypes<SalvageMapPrototype>().ToList())
: _prototypeManager.Index<SalvageMapPrototype>(forcedSalvage);
var opts = new MapLoadOptions
{
Offset = new Vector2(0, 0)
};
if (!_map.TryLoad(salvMap, salvageProto.MapPath.ToString(), out var roots, opts) ||
roots.FirstOrNull() is not { } root)
{
Report(uid, component.SalvageChannel, "salvage-system-announcement-spawn-debris-disintegrated");
_mapManager.DeleteMap(salvMap);
return false;
}
salvageEnt = root;
}
var bounds = Comp<MapGridComponent>(salvageEnt.Value).LocalAABB;
if (!TryGetSalvagePlacementLocation(uid, component, bounds, out var spawnLocation, out var spawnAngle))
{
Report(uid, component.SalvageChannel, "salvage-system-announcement-spawn-no-debris-available");
_mapManager.DeleteMap(salvMap);
return false;
}
var salvXForm = Transform(salvageEnt.Value);
_transform.SetParent(salvageEnt.Value, salvXForm, _mapManager.GetMapEntityId(spawnLocation.MapId));
_transform.SetWorldPosition(salvXForm, spawnLocation.Position);
component.AttachedEntity = salvageEnt;
var gridcomp = EnsureComp<SalvageGridComponent>(salvageEnt.Value);
gridcomp.SpawnerMagnet = uid;
_transform.SetWorldRotation(salvageEnt.Value, spawnAngle);
Report(uid, component.SalvageChannel, "salvage-system-announcement-arrived", ("timeLeft", component.HoldTime.TotalSeconds));
_mapManager.DeleteMap(salvMap);
return true;
}
private void Report(EntityUid source, string channelName, string messageKey, params (string, object)[] args)
{
var message = args.Length == 0 ? Loc.GetString(messageKey) : Loc.GetString(messageKey, args);
@@ -416,87 +86,12 @@ namespace Content.Server.Salvage
_radioSystem.SendRadioMessage(source, message, channel, source);
}
private void Transition(EntityUid uid, SalvageMagnetComponent magnet, TimeSpan currentTime)
{
switch (magnet.MagnetState.StateType)
{
case MagnetStateType.Attaching:
if (SpawnSalvage(uid, magnet))
{
magnet.MagnetState = new MagnetState(MagnetStateType.Holding, currentTime + magnet.HoldTime);
}
else
{
magnet.MagnetState = new MagnetState(MagnetStateType.CoolingDown, currentTime + magnet.CooldownTime);
}
break;
case MagnetStateType.Holding:
Report(uid, magnet.SalvageChannel, "salvage-system-announcement-losing", ("timeLeft", magnet.DetachingTime.TotalSeconds));
magnet.MagnetState = new MagnetState(MagnetStateType.Detaching, currentTime + magnet.DetachingTime);
break;
case MagnetStateType.Detaching:
if (magnet.AttachedEntity.HasValue)
{
SafeDeleteSalvage(magnet.AttachedEntity.Value);
}
else
{
Log.Error("Salvage detaching was expecting attached entity but it was null");
}
Report(uid, magnet.SalvageChannel, "salvage-system-announcement-lost");
magnet.MagnetState = new MagnetState(MagnetStateType.CoolingDown, currentTime + magnet.CooldownTime);
break;
case MagnetStateType.CoolingDown:
magnet.MagnetState = MagnetState.Inactive;
break;
}
UpdateAppearance(uid, magnet);
UpdateChargeStateAppearance(uid, currentTime, magnet);
}
public override void Update(float frameTime)
{
var secondsPassed = TimeSpan.FromSeconds(frameTime);
// Keep track of time, and state per grid
foreach (var (uid, state) in _salvageGridStates)
{
if (state.ActiveMagnets.Count == 0) continue;
// Not handling the case where the salvage we spawned got paused
// They both need to be paused, or it doesn't make sense
if (MetaData(uid).EntityPaused) continue;
state.CurrentTime += secondsPassed;
var deleteQueue = new RemQueue<EntityUid>();
foreach(var magnet in state.ActiveMagnets)
{
if (!TryComp<SalvageMagnetComponent>(magnet, out var magnetComp))
continue;
UpdateChargeStateAppearance(magnet, state.CurrentTime, magnetComp);
if (magnetComp.MagnetState.Until > state.CurrentTime) continue;
Transition(magnet, magnetComp, state.CurrentTime);
if (magnetComp.MagnetState.StateType == MagnetStateType.Inactive)
{
deleteQueue.Add(magnet);
}
}
foreach(var magnet in deleteQueue)
{
state.ActiveMagnets.Remove(magnet);
}
}
UpdateExpeditions();
UpdateMagnet();
UpdateRunner();
}
}
public sealed class SalvageGridState
{
public TimeSpan CurrentTime { get; set; }
public List<EntityUid> ActiveMagnets { get; } = new();
}
}