Atmos pipe rework (#3833)
* Initial * Cleanup a bunch of things * some changes dunno * RequireAnchored * a * stuff * more work * Lots of progress * delete pipe visualizer * a * b * pipenet and pipenode cleanup * Fixes * Adds GasValve * Adds GasMiner * Fix stuff, maybe? * More fixes * Ignored components on the client * Adds thermomachine behavior, change a bunch of stuff * Remove Anchored * some work, but it's shitcode * significantly more ECS * ECS AtmosDevices * Cleanup * fix appearance * when the pipe direction is sus * Gas tanks and canisters * pipe anchoring and stuff * coding is my passion * Unsafe pipes take longer to unanchor * turns out we're no longer using eris canisters * Gas canister inserted tank appearance, improvements * Work on a bunch of appearances * Scrubber appearance * Reorganize AtmosphereSystem.Piping into a bunch of different systems * Appearance for vent/scrubber/pump turns off when leaving atmosphere * ThermoMachine appearance * Cleanup gas tanks * Remove passive gate unused imports * remove old canister UI functionality * PipeNode environment air, make everything use AssumeAir instead of merging manually * a * Reorganize atmos to follow new structure * ????? * Canister UI, restructure client * Restructure shared * Fix build tho * listen, at least the canister UI works entirely... * fix build : ) * Atmos device prototypes have names and descriptions * gas canister ui slider doesn't jitter * trinary prototypes * sprite for miners * ignore components * fix YAML * Fix port system doing useless thing * Fix build * fix thinking moment * fix build again because * canister direction * pipenode is a word * GasTank Air will throw on invalid states * fix build.... * Unhardcode volume pump thresholds * Volume pump and filter take time into account * Rename Join/Leave atmosphere events to AtmosDeviceEnabled/Disabled Event * Gas tank node volume is set by initial mixtuer * I love node container
This commit is contained in:
committed by
GitHub
parent
cfc3f2e7fc
commit
a2b737d945
26
Content.Server/Atmos/EntitySystems/AirtightSystem.cs
Normal file
26
Content.Server/Atmos/EntitySystems/AirtightSystem.cs
Normal file
@@ -0,0 +1,26 @@
|
||||
using Content.Server.Atmos.Components;
|
||||
using JetBrains.Annotations;
|
||||
using Robust.Shared.GameObjects;
|
||||
|
||||
namespace Content.Server.Atmos.EntitySystems
|
||||
{
|
||||
[UsedImplicitly]
|
||||
public class AirtightSystem : EntitySystem
|
||||
{
|
||||
public override void Initialize()
|
||||
{
|
||||
SubscribeLocalEvent<AirtightComponent, SnapGridPositionChangedEvent>(OnAirtightPositionChanged);
|
||||
SubscribeLocalEvent<AirtightComponent, RotateEvent>(OnAirtightRotated);
|
||||
}
|
||||
|
||||
private void OnAirtightPositionChanged(EntityUid uid, AirtightComponent component, SnapGridPositionChangedEvent args)
|
||||
{
|
||||
component.OnSnapGridMove(args);
|
||||
}
|
||||
|
||||
private void OnAirtightRotated(EntityUid uid, AirtightComponent airtight, RotateEvent ev)
|
||||
{
|
||||
airtight.RotateEvent(ev);
|
||||
}
|
||||
}
|
||||
}
|
||||
169
Content.Server/Atmos/EntitySystems/AtmosDebugOverlaySystem.cs
Normal file
169
Content.Server/Atmos/EntitySystems/AtmosDebugOverlaySystem.cs
Normal file
@@ -0,0 +1,169 @@
|
||||
#nullable enable
|
||||
using System.Collections.Generic;
|
||||
using Content.Server.Atmos.Components;
|
||||
using Content.Shared.Atmos;
|
||||
using Content.Shared.Atmos.EntitySystems;
|
||||
using Content.Shared.CCVar;
|
||||
using JetBrains.Annotations;
|
||||
using Robust.Server.Player;
|
||||
using Robust.Shared.Configuration;
|
||||
using Robust.Shared.Enums;
|
||||
using Robust.Shared.IoC;
|
||||
using Robust.Shared.Map;
|
||||
using Robust.Shared.Maths;
|
||||
using Robust.Shared.Timing;
|
||||
|
||||
namespace Content.Server.Atmos.EntitySystems
|
||||
{
|
||||
[UsedImplicitly]
|
||||
public sealed class AtmosDebugOverlaySystem : SharedAtmosDebugOverlaySystem
|
||||
{
|
||||
[Dependency] private readonly IGameTiming _gameTiming = default!;
|
||||
[Dependency] private readonly IPlayerManager _playerManager = default!;
|
||||
[Dependency] private readonly IMapManager _mapManager = default!;
|
||||
[Dependency] private readonly IConfigurationManager _configManager = default!;
|
||||
|
||||
/// <summary>
|
||||
/// Players allowed to see the atmos debug overlay.
|
||||
/// To modify it see <see cref="AddObserver"/> and
|
||||
/// <see cref="RemoveObserver"/>.
|
||||
/// </summary>
|
||||
private readonly HashSet<IPlayerSession> _playerObservers = new();
|
||||
|
||||
/// <summary>
|
||||
/// Overlay update ticks per second.
|
||||
/// </summary>
|
||||
private float _updateCooldown;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
base.Initialize();
|
||||
_playerManager.PlayerStatusChanged += OnPlayerStatusChanged;
|
||||
}
|
||||
|
||||
public override void Shutdown()
|
||||
{
|
||||
base.Shutdown();
|
||||
_playerManager.PlayerStatusChanged -= OnPlayerStatusChanged;
|
||||
}
|
||||
|
||||
public bool AddObserver(IPlayerSession observer)
|
||||
{
|
||||
return _playerObservers.Add(observer);
|
||||
}
|
||||
|
||||
public bool HasObserver(IPlayerSession observer)
|
||||
{
|
||||
return _playerObservers.Contains(observer);
|
||||
}
|
||||
|
||||
public bool RemoveObserver(IPlayerSession observer)
|
||||
{
|
||||
if (!_playerObservers.Remove(observer))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var message = new AtmosDebugOverlayDisableMessage();
|
||||
RaiseNetworkEvent(message, observer.ConnectedClient);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the given observer if it doesn't exist, removes it otherwise.
|
||||
/// </summary>
|
||||
/// <param name="observer">The observer to toggle.</param>
|
||||
/// <returns>true if added, false if removed.</returns>
|
||||
public bool ToggleObserver(IPlayerSession observer)
|
||||
{
|
||||
if (HasObserver(observer))
|
||||
{
|
||||
RemoveObserver(observer);
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
AddObserver(observer);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnPlayerStatusChanged(object? sender, SessionStatusEventArgs e)
|
||||
{
|
||||
if (e.NewStatus != SessionStatus.InGame)
|
||||
{
|
||||
RemoveObserver(e.Session);
|
||||
}
|
||||
}
|
||||
|
||||
private AtmosDebugOverlayData ConvertTileToData(TileAtmosphere? tile)
|
||||
{
|
||||
var gases = new float[Atmospherics.TotalNumberOfGases];
|
||||
if (tile?.Air == null)
|
||||
{
|
||||
return new AtmosDebugOverlayData(0, gases, AtmosDirection.Invalid, false, tile?.BlockedAirflow ?? AtmosDirection.Invalid);
|
||||
}
|
||||
else
|
||||
{
|
||||
for (var i = 0; i < Atmospherics.TotalNumberOfGases; i++)
|
||||
{
|
||||
gases[i] = tile.Air.GetMoles(i);
|
||||
}
|
||||
return new AtmosDebugOverlayData(tile.Air.Temperature, gases, tile.PressureDirectionForDebugOverlay, tile.ExcitedGroup != null, tile.BlockedAirflow);
|
||||
}
|
||||
}
|
||||
|
||||
public override void Update(float frameTime)
|
||||
{
|
||||
AccumulatedFrameTime += frameTime;
|
||||
_updateCooldown = 1 / _configManager.GetCVar(CCVars.NetAtmosDebugOverlayTickRate);
|
||||
|
||||
if (AccumulatedFrameTime < _updateCooldown)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// This is the timer from GasTileOverlaySystem
|
||||
AccumulatedFrameTime -= _updateCooldown;
|
||||
|
||||
var currentTick = _gameTiming.CurTick;
|
||||
|
||||
// Now we'll go through each player, then through each chunk in range of that player checking if the player is still in range
|
||||
// If they are, check if they need the new data to send (i.e. if there's an overlay for the gas).
|
||||
// Afterwards we reset all the chunk data for the next time we tick.
|
||||
foreach (var session in _playerObservers)
|
||||
{
|
||||
if (session.AttachedEntity == null) continue;
|
||||
|
||||
var entity = session.AttachedEntity;
|
||||
|
||||
var worldBounds = Box2.CenteredAround(entity.Transform.WorldPosition,
|
||||
new Vector2(LocalViewRange, LocalViewRange));
|
||||
|
||||
foreach (var grid in _mapManager.FindGridsIntersecting(entity.Transform.MapID, worldBounds))
|
||||
{
|
||||
if (!EntityManager.TryGetEntity(grid.GridEntityId, out var gridEnt)) continue;
|
||||
|
||||
if (!gridEnt.TryGetComponent<GridAtmosphereComponent>(out var gam)) continue;
|
||||
|
||||
var entityTile = grid.GetTileRef(entity.Transform.Coordinates).GridIndices;
|
||||
var baseTile = new Vector2i(entityTile.X - (LocalViewRange / 2), entityTile.Y - (LocalViewRange / 2));
|
||||
var debugOverlayContent = new AtmosDebugOverlayData[LocalViewRange * LocalViewRange];
|
||||
|
||||
var index = 0;
|
||||
for (var y = 0; y < LocalViewRange; y++)
|
||||
{
|
||||
for (var x = 0; x < LocalViewRange; x++)
|
||||
{
|
||||
var Vector2i = new Vector2i(baseTile.X + x, baseTile.Y + y);
|
||||
debugOverlayContent[index++] = ConvertTileToData(gam.GetTile(Vector2i));
|
||||
}
|
||||
}
|
||||
|
||||
RaiseNetworkEvent(new AtmosDebugOverlayMessage(grid.Index, baseTile, debugOverlayContent), session.ConnectedClient);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
24
Content.Server/Atmos/EntitySystems/AtmosphereSystem.CVars.cs
Normal file
24
Content.Server/Atmos/EntitySystems/AtmosphereSystem.CVars.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
using Content.Shared.CCVar;
|
||||
|
||||
namespace Content.Server.Atmos.EntitySystems
|
||||
{
|
||||
public partial class AtmosphereSystem
|
||||
{
|
||||
public bool SpaceWind { get; private set; }
|
||||
public bool MonstermosEqualization { get; private set; }
|
||||
public bool Superconduction { get; private set; }
|
||||
public bool ExcitedGroupsSpaceIsAllConsuming { get; private set; }
|
||||
public float AtmosMaxProcessTime { get; private set; }
|
||||
public float AtmosTickRate { get; private set; }
|
||||
|
||||
private void InitializeCVars()
|
||||
{
|
||||
_cfg.OnValueChanged(CCVars.SpaceWind, value => SpaceWind = value, true);
|
||||
_cfg.OnValueChanged(CCVars.MonstermosEqualization, value => MonstermosEqualization = value, true);
|
||||
_cfg.OnValueChanged(CCVars.Superconduction, value => Superconduction = value, true);
|
||||
_cfg.OnValueChanged(CCVars.AtmosMaxProcessTime, value => AtmosMaxProcessTime = value, true);
|
||||
_cfg.OnValueChanged(CCVars.AtmosTickRate, value => AtmosTickRate = value, true);
|
||||
_cfg.OnValueChanged(CCVars.ExcitedGroupsSpaceIsAllConsuming, value => ExcitedGroupsSpaceIsAllConsuming = value, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
34
Content.Server/Atmos/EntitySystems/AtmosphereSystem.Gases.cs
Normal file
34
Content.Server/Atmos/EntitySystems/AtmosphereSystem.Gases.cs
Normal file
@@ -0,0 +1,34 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Content.Server.Atmos.Reactions;
|
||||
using Content.Shared.Atmos;
|
||||
using Robust.Shared.Maths;
|
||||
|
||||
namespace Content.Server.Atmos.EntitySystems
|
||||
{
|
||||
public partial class AtmosphereSystem
|
||||
{
|
||||
private GasReactionPrototype[] _gasReactions = Array.Empty<GasReactionPrototype>();
|
||||
private float[] _gasSpecificHeats = new float[Atmospherics.TotalNumberOfGases];
|
||||
|
||||
/// <summary>
|
||||
/// List of gas reactions ordered by priority.
|
||||
/// </summary>
|
||||
public IEnumerable<GasReactionPrototype> GasReactions => _gasReactions!;
|
||||
public float[] GasSpecificHeats => _gasSpecificHeats;
|
||||
|
||||
private void InitializeGases()
|
||||
{
|
||||
_gasReactions = _protoMan.EnumeratePrototypes<GasReactionPrototype>().ToArray();
|
||||
Array.Sort(_gasReactions, (a, b) => b.Priority.CompareTo(a.Priority));
|
||||
|
||||
Array.Resize(ref _gasSpecificHeats, MathHelper.NextMultipleOf(Atmospherics.TotalNumberOfGases, 4));
|
||||
|
||||
for (var i = 0; i < GasPrototypes.Length; i++)
|
||||
{
|
||||
_gasSpecificHeats[i] = GasPrototypes[i].SpecificHeat;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
174
Content.Server/Atmos/EntitySystems/AtmosphereSystem.cs
Normal file
174
Content.Server/Atmos/EntitySystems/AtmosphereSystem.cs
Normal file
@@ -0,0 +1,174 @@
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using Content.Server.Atmos.Components;
|
||||
using Content.Shared.Atmos.EntitySystems;
|
||||
using Content.Shared.Maps;
|
||||
using JetBrains.Annotations;
|
||||
using Robust.Server.GameObjects;
|
||||
using Robust.Shared.Configuration;
|
||||
using Robust.Shared.GameObjects;
|
||||
using Robust.Shared.IoC;
|
||||
using Robust.Shared.Map;
|
||||
using Robust.Shared.Prototypes;
|
||||
using Robust.Shared.Timing;
|
||||
|
||||
namespace Content.Server.Atmos.EntitySystems
|
||||
{
|
||||
[UsedImplicitly]
|
||||
public partial class AtmosphereSystem : SharedAtmosphereSystem
|
||||
{
|
||||
[Dependency] private readonly IPrototypeManager _protoMan = default!;
|
||||
[Dependency] private readonly IMapManager _mapManager = default!;
|
||||
[Dependency] private readonly IPauseManager _pauseManager = default!;
|
||||
[Dependency] private readonly IConfigurationManager _cfg = default!;
|
||||
|
||||
private GridTileLookupSystem? _gridTileLookup = null;
|
||||
|
||||
private const float ExposedUpdateDelay = 1f;
|
||||
private float _exposedTimer = 0f;
|
||||
|
||||
public GridTileLookupSystem GridTileLookupSystem => _gridTileLookup ??= Get<GridTileLookupSystem>();
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
base.Initialize();
|
||||
|
||||
InitializeGases();
|
||||
InitializeCVars();
|
||||
|
||||
#region Events
|
||||
|
||||
// Map events.
|
||||
_mapManager.MapCreated += OnMapCreated;
|
||||
_mapManager.TileChanged += OnTileChanged;
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
public override void Shutdown()
|
||||
{
|
||||
base.Shutdown();
|
||||
|
||||
_mapManager.MapCreated -= OnMapCreated;
|
||||
_mapManager.TileChanged -= OnTileChanged;
|
||||
}
|
||||
|
||||
private void OnTileChanged(object? sender, TileChangedEventArgs eventArgs)
|
||||
{
|
||||
// When a tile changes, we want to update it only if it's gone from
|
||||
// space -> not space or vice versa. So if the old tile is the
|
||||
// same as the new tile in terms of space-ness, ignore the change
|
||||
|
||||
if (eventArgs.NewTile.IsSpace() == eventArgs.OldTile.IsSpace())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
GetGridAtmosphere(eventArgs.NewTile.GridIndex)?.Invalidate(eventArgs.NewTile.GridIndices);
|
||||
}
|
||||
|
||||
private void OnMapCreated(object? sender, MapEventArgs e)
|
||||
{
|
||||
if (e.Map == MapId.Nullspace)
|
||||
return;
|
||||
|
||||
var map = _mapManager.GetMapEntity(e.Map);
|
||||
|
||||
if (!map.HasComponent<IGridAtmosphereComponent>())
|
||||
map.AddComponent<SpaceGridAtmosphereComponent>();
|
||||
}
|
||||
|
||||
#region Helper Methods
|
||||
public IGridAtmosphereComponent? GetGridAtmosphere(GridId gridId)
|
||||
{
|
||||
if (!gridId.IsValid())
|
||||
return null;
|
||||
|
||||
if (!_mapManager.TryGetGrid(gridId, out var grid))
|
||||
return null;
|
||||
|
||||
return ComponentManager.TryGetComponent(grid.GridEntityId, out IGridAtmosphereComponent? gridAtmosphere)
|
||||
? gridAtmosphere : null;
|
||||
}
|
||||
|
||||
public IGridAtmosphereComponent GetGridAtmosphere(EntityCoordinates coordinates)
|
||||
{
|
||||
return GetGridAtmosphere(coordinates.ToMap(EntityManager));
|
||||
}
|
||||
|
||||
public IGridAtmosphereComponent GetGridAtmosphere(MapCoordinates coordinates)
|
||||
{
|
||||
if (coordinates.MapId == MapId.Nullspace)
|
||||
{
|
||||
throw new ArgumentException($"Coordinates cannot be in nullspace!", nameof(coordinates));
|
||||
}
|
||||
|
||||
if (_mapManager.TryFindGridAt(coordinates, out var grid))
|
||||
{
|
||||
if (ComponentManager.TryGetComponent(grid.GridEntityId, out IGridAtmosphereComponent? atmos))
|
||||
{
|
||||
return atmos;
|
||||
}
|
||||
}
|
||||
|
||||
return _mapManager.GetMapEntity(coordinates.MapId).GetComponent<IGridAtmosphereComponent>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unlike <see cref="GetGridAtmosphere"/>, this doesn't return space grid when not found.
|
||||
/// </summary>
|
||||
public bool TryGetSimulatedGridAtmosphere(MapCoordinates coordinates, [NotNullWhen(true)] out IGridAtmosphereComponent? atmosphere)
|
||||
{
|
||||
if (coordinates.MapId == MapId.Nullspace)
|
||||
{
|
||||
atmosphere = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (_mapManager.TryFindGridAt(coordinates, out var mapGrid)
|
||||
&& ComponentManager.TryGetComponent(mapGrid.GridEntityId, out IGridAtmosphereComponent? atmosGrid)
|
||||
&& atmosGrid.Simulated)
|
||||
{
|
||||
atmosphere = atmosGrid;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (_mapManager.GetMapEntity(coordinates.MapId).TryGetComponent(out IGridAtmosphereComponent? atmosMap)
|
||||
&& atmosMap.Simulated)
|
||||
{
|
||||
atmosphere = atmosMap;
|
||||
return true;
|
||||
}
|
||||
|
||||
atmosphere = null;
|
||||
return false;
|
||||
}
|
||||
#endregion
|
||||
|
||||
public override void Update(float frameTime)
|
||||
{
|
||||
base.Update(frameTime);
|
||||
|
||||
_exposedTimer += frameTime;
|
||||
|
||||
foreach (var (mapGridComponent, gridAtmosphereComponent) in EntityManager.ComponentManager.EntityQuery<IMapGridComponent, IGridAtmosphereComponent>(true))
|
||||
{
|
||||
if (_pauseManager.IsGridPaused(mapGridComponent.GridIndex)) continue;
|
||||
|
||||
gridAtmosphereComponent.Update(frameTime);
|
||||
}
|
||||
|
||||
if (_exposedTimer >= ExposedUpdateDelay)
|
||||
{
|
||||
foreach (var exposed in EntityManager.ComponentManager.EntityQuery<AtmosExposedComponent>(true))
|
||||
{
|
||||
var tile = exposed.Owner.Transform.Coordinates.GetTileAtmosphere();
|
||||
if (tile == null) continue;
|
||||
exposed.Update(tile, _exposedTimer);
|
||||
}
|
||||
|
||||
_exposedTimer = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using Content.Shared.Interaction;
|
||||
using Content.Server.GameObjects.Components;
|
||||
using Robust.Shared.GameObjects;
|
||||
using JetBrains.Annotations;
|
||||
|
||||
namespace Content.Server.GameObjects.EntitySystems
|
||||
{
|
||||
[UsedImplicitly]
|
||||
internal sealed class ComputerUIActivatorSystem : EntitySystem
|
||||
{
|
||||
public override void Initialize()
|
||||
{
|
||||
base.Initialize();
|
||||
SubscribeLocalEvent<BaseComputerUserInterfaceComponent, ActivateInWorldEvent>(HandleActivate);
|
||||
}
|
||||
|
||||
private void HandleActivate(EntityUid uid, BaseComputerUserInterfaceComponent component, ActivateInWorldEvent args)
|
||||
{
|
||||
component.ActivateThunk(args);
|
||||
}
|
||||
}
|
||||
}
|
||||
18
Content.Server/Atmos/EntitySystems/GasAnalyzerSystem.cs
Normal file
18
Content.Server/Atmos/EntitySystems/GasAnalyzerSystem.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
using Content.Server.Atmos.Components;
|
||||
using JetBrains.Annotations;
|
||||
using Robust.Shared.GameObjects;
|
||||
|
||||
namespace Content.Server.Atmos.EntitySystems
|
||||
{
|
||||
[UsedImplicitly]
|
||||
public class GasAnalyzerSystem : EntitySystem
|
||||
{
|
||||
public override void Update(float frameTime)
|
||||
{
|
||||
foreach (var analyzer in ComponentManager.EntityQuery<GasAnalyzerComponent>(true))
|
||||
{
|
||||
analyzer.Update(frameTime);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
28
Content.Server/Atmos/EntitySystems/GasTankSystem.cs
Normal file
28
Content.Server/Atmos/EntitySystems/GasTankSystem.cs
Normal file
@@ -0,0 +1,28 @@
|
||||
using Content.Server.Atmos.Components;
|
||||
using JetBrains.Annotations;
|
||||
using Robust.Shared.GameObjects;
|
||||
|
||||
namespace Content.Server.Atmos.EntitySystems
|
||||
{
|
||||
[UsedImplicitly]
|
||||
public class GasTankSystem : EntitySystem
|
||||
{
|
||||
private float _timer = 0f;
|
||||
private const float Interval = 0.5f;
|
||||
|
||||
public override void Update(float frameTime)
|
||||
{
|
||||
base.Update(frameTime);
|
||||
|
||||
_timer += frameTime;
|
||||
|
||||
if (_timer < Interval) return;
|
||||
_timer = 0f;
|
||||
|
||||
foreach (var gasTank in EntityManager.ComponentManager.EntityQuery<GasTankComponent>(true))
|
||||
{
|
||||
gasTank.Update();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
490
Content.Server/Atmos/EntitySystems/GasTileOverlaySystem.cs
Normal file
490
Content.Server/Atmos/EntitySystems/GasTileOverlaySystem.cs
Normal file
@@ -0,0 +1,490 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.CompilerServices;
|
||||
using Content.Server.Atmos.Components;
|
||||
using Content.Shared.Atmos;
|
||||
using Content.Shared.Atmos.EntitySystems;
|
||||
using Content.Shared.CCVar;
|
||||
using Content.Shared.GameTicking;
|
||||
using JetBrains.Annotations;
|
||||
using Robust.Server.Player;
|
||||
using Robust.Shared;
|
||||
using Robust.Shared.Configuration;
|
||||
using Robust.Shared.Enums;
|
||||
using Robust.Shared.GameObjects;
|
||||
using Robust.Shared.IoC;
|
||||
using Robust.Shared.Map;
|
||||
using Robust.Shared.Maths;
|
||||
using Robust.Shared.Timing;
|
||||
// ReSharper disable once RedundantUsingDirective
|
||||
using Dependency = Robust.Shared.IoC.DependencyAttribute;
|
||||
|
||||
namespace Content.Server.Atmos.EntitySystems
|
||||
{
|
||||
[UsedImplicitly]
|
||||
internal sealed class GasTileOverlaySystem : SharedGasTileOverlaySystem, IResettingEntitySystem
|
||||
{
|
||||
[Dependency] private readonly IGameTiming _gameTiming = default!;
|
||||
[Dependency] private readonly IPlayerManager _playerManager = default!;
|
||||
[Dependency] private readonly IMapManager _mapManager = default!;
|
||||
[Dependency] private readonly IConfigurationManager _configManager = default!;
|
||||
|
||||
/// <summary>
|
||||
/// The tiles that have had their atmos data updated since last tick
|
||||
/// </summary>
|
||||
private readonly Dictionary<GridId, HashSet<Vector2i>> _invalidTiles = new();
|
||||
|
||||
private readonly Dictionary<IPlayerSession, PlayerGasOverlay> _knownPlayerChunks =
|
||||
new();
|
||||
|
||||
/// <summary>
|
||||
/// Gas data stored in chunks to make PVS / bubbling easier.
|
||||
/// </summary>
|
||||
private readonly Dictionary<GridId, Dictionary<Vector2i, GasOverlayChunk>> _overlay =
|
||||
new();
|
||||
|
||||
/// <summary>
|
||||
/// How far away do we update gas overlays (minimum; due to chunking further away tiles may also be updated).
|
||||
/// </summary>
|
||||
private float _updateRange;
|
||||
// Because the gas overlay updates aren't run every tick we need to avoid the pop-in that might occur with
|
||||
// the regular PVS range.
|
||||
private const float RangeOffset = 6.0f;
|
||||
|
||||
/// <summary>
|
||||
/// Overlay update ticks per second.
|
||||
/// </summary>
|
||||
private float _updateCooldown;
|
||||
|
||||
private AtmosphereSystem _atmosphereSystem = default!;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
base.Initialize();
|
||||
|
||||
_atmosphereSystem = Get<AtmosphereSystem>();
|
||||
_playerManager.PlayerStatusChanged += OnPlayerStatusChanged;
|
||||
_mapManager.OnGridRemoved += OnGridRemoved;
|
||||
}
|
||||
|
||||
public override void Shutdown()
|
||||
{
|
||||
base.Shutdown();
|
||||
_playerManager.PlayerStatusChanged -= OnPlayerStatusChanged;
|
||||
_mapManager.OnGridRemoved -= OnGridRemoved;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public void Invalidate(GridId gridIndex, Vector2i indices)
|
||||
{
|
||||
if (!_invalidTiles.TryGetValue(gridIndex, out var existing))
|
||||
{
|
||||
existing = new HashSet<Vector2i>();
|
||||
_invalidTiles[gridIndex] = existing;
|
||||
}
|
||||
|
||||
existing.Add(indices);
|
||||
}
|
||||
|
||||
private GasOverlayChunk GetOrCreateChunk(GridId gridIndex, Vector2i indices)
|
||||
{
|
||||
if (!_overlay.TryGetValue(gridIndex, out var chunks))
|
||||
{
|
||||
chunks = new Dictionary<Vector2i, GasOverlayChunk>();
|
||||
_overlay[gridIndex] = chunks;
|
||||
}
|
||||
|
||||
var chunkIndices = GetGasChunkIndices(indices);
|
||||
|
||||
if (!chunks.TryGetValue(chunkIndices, out var chunk))
|
||||
{
|
||||
chunk = new GasOverlayChunk(gridIndex, chunkIndices);
|
||||
chunks[chunkIndices] = chunk;
|
||||
}
|
||||
|
||||
return chunk;
|
||||
}
|
||||
|
||||
private void OnGridRemoved(MapId mapId, GridId gridId)
|
||||
{
|
||||
if (_overlay.ContainsKey(gridId))
|
||||
{
|
||||
_overlay.Remove(gridId);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnPlayerStatusChanged(object? sender, SessionStatusEventArgs e)
|
||||
{
|
||||
if (e.NewStatus != SessionStatus.InGame)
|
||||
{
|
||||
if (_knownPlayerChunks.ContainsKey(e.Session))
|
||||
{
|
||||
_knownPlayerChunks.Remove(e.Session);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_knownPlayerChunks.ContainsKey(e.Session))
|
||||
{
|
||||
_knownPlayerChunks[e.Session] = new PlayerGasOverlay();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether the overlay-relevant data for a gas tile has been updated.
|
||||
/// </summary>
|
||||
/// <param name="gam"></param>
|
||||
/// <param name="oldTile"></param>
|
||||
/// <param name="indices"></param>
|
||||
/// <param name="overlayData"></param>
|
||||
/// <returns>true if updated</returns>
|
||||
private bool TryRefreshTile(GridAtmosphereComponent gam, GasOverlayData oldTile, Vector2i indices, out GasOverlayData overlayData)
|
||||
{
|
||||
var tile = gam.GetTile(indices);
|
||||
|
||||
if (tile == null)
|
||||
{
|
||||
overlayData = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
var tileData = new List<GasData>();
|
||||
|
||||
if(tile.Air != null)
|
||||
for (byte i = 0; i < Atmospherics.TotalNumberOfGases; i++)
|
||||
{
|
||||
var gas = _atmosphereSystem.GetGas(i);
|
||||
var overlay = _atmosphereSystem.GetOverlay(i);
|
||||
if (overlay == null) continue;
|
||||
|
||||
var moles = tile.Air.Gases[i];
|
||||
|
||||
if (moles < gas.GasMolesVisible) continue;
|
||||
|
||||
var data = new GasData(i, (byte) (MathHelper.Clamp01(moles / gas.GasMolesVisibleMax) * 255));
|
||||
tileData.Add(data);
|
||||
}
|
||||
|
||||
overlayData = new GasOverlayData(tile!.Hotspot.State, tile.Hotspot.Temperature, tileData.Count == 0 ? Array.Empty<GasData>() : tileData.ToArray());
|
||||
|
||||
if (overlayData.Equals(oldTile))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get every chunk in range of our entity that exists, including on other grids.
|
||||
/// </summary>
|
||||
/// <param name="entity"></param>
|
||||
/// <returns></returns>
|
||||
private List<GasOverlayChunk> GetChunksInRange(IEntity entity)
|
||||
{
|
||||
var inRange = new List<GasOverlayChunk>();
|
||||
|
||||
// This is the max in any direction that we can get a chunk (e.g. max 2 chunks away of data).
|
||||
var (maxXDiff, maxYDiff) = ((int) (_updateRange / ChunkSize) + 1, (int) (_updateRange / ChunkSize) + 1);
|
||||
|
||||
var worldBounds = Box2.CenteredAround(entity.Transform.WorldPosition,
|
||||
new Vector2(_updateRange, _updateRange));
|
||||
|
||||
foreach (var grid in _mapManager.FindGridsIntersecting(entity.Transform.MapID, worldBounds))
|
||||
{
|
||||
if (!_overlay.TryGetValue(grid.Index, out var chunks))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var entityTile = grid.GetTileRef(entity.Transform.Coordinates).GridIndices;
|
||||
|
||||
for (var x = -maxXDiff; x <= maxXDiff; x++)
|
||||
{
|
||||
for (var y = -maxYDiff; y <= maxYDiff; y++)
|
||||
{
|
||||
var chunkIndices = GetGasChunkIndices(new Vector2i(entityTile.X + x * ChunkSize, entityTile.Y + y * ChunkSize));
|
||||
|
||||
if (!chunks.TryGetValue(chunkIndices, out var chunk)) continue;
|
||||
|
||||
// Now we'll check if it's in range and relevant for us
|
||||
// (e.g. if we're on the very edge of a chunk we may need more chunks).
|
||||
|
||||
var (xDiff, yDiff) = (chunkIndices.X - entityTile.X, chunkIndices.Y - entityTile.Y);
|
||||
if (xDiff > 0 && xDiff > _updateRange ||
|
||||
yDiff > 0 && yDiff > _updateRange ||
|
||||
xDiff < 0 && Math.Abs(xDiff + ChunkSize) > _updateRange ||
|
||||
yDiff < 0 && Math.Abs(yDiff + ChunkSize) > _updateRange) continue;
|
||||
|
||||
inRange.Add(chunk);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return inRange;
|
||||
}
|
||||
|
||||
public override void Update(float frameTime)
|
||||
{
|
||||
AccumulatedFrameTime += frameTime;
|
||||
_updateCooldown = 1 / _configManager.GetCVar(CCVars.NetGasOverlayTickRate);
|
||||
|
||||
if (AccumulatedFrameTime < _updateCooldown)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_updateRange = _configManager.GetCVar(CVars.NetMaxUpdateRange) + RangeOffset;
|
||||
|
||||
// TODO: So in the worst case scenario we still have to send a LOT of tile data per tick if there's a fire.
|
||||
// If we go with say 15 tile radius then we have up to 900 tiles to update per tick.
|
||||
// In a saltern fire the worst you'll normally see is around 650 at the moment.
|
||||
// Need a way to fake this more because sending almost 2,000 tile updates per second to even 50 players is... yikes
|
||||
// I mean that's as big as it gets so larger maps will have the same but still, that's a lot of data.
|
||||
|
||||
// Some ways to do this are potentially: splitting fire and gas update data so they don't update at the same time
|
||||
// (gives the illusion of more updates happening), e.g. if gas updates are 3 times a second and fires are 1.6 times a second or something.
|
||||
// Could also look at updating tiles close to us more frequently (e.g. within 1 chunk every tick).
|
||||
// Stuff just out of our viewport we need so when we move it doesn't pop in but it doesn't mean we need to update it every tick.
|
||||
|
||||
AccumulatedFrameTime -= _updateCooldown;
|
||||
|
||||
var gridAtmosComponents = new Dictionary<GridId, GridAtmosphereComponent>();
|
||||
var updatedTiles = new Dictionary<GasOverlayChunk, HashSet<Vector2i>>();
|
||||
|
||||
// So up to this point we've been caching the updated tiles for multiple ticks.
|
||||
// Now we'll go through and check whether the update actually matters for the overlay or not,
|
||||
// and if not then we won't bother sending the data.
|
||||
foreach (var (gridId, indices) in _invalidTiles)
|
||||
{
|
||||
if (!_mapManager.TryGetGrid(gridId, out var grid))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var gridEntityId = grid.GridEntityId;
|
||||
|
||||
if (!EntityManager.GetEntity(gridEntityId).TryGetComponent(out GridAtmosphereComponent? gam))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// If it's being invalidated it should have this right?
|
||||
// At any rate we'll cache it for here + the AddChunk
|
||||
if (!gridAtmosComponents.ContainsKey(gridId))
|
||||
{
|
||||
gridAtmosComponents[gridId] = gam;
|
||||
}
|
||||
|
||||
foreach (var invalid in indices.ToArray())
|
||||
{
|
||||
var chunk = GetOrCreateChunk(gridId, invalid);
|
||||
|
||||
if (!TryRefreshTile(gam, chunk.GetData(invalid), invalid, out var data)) continue;
|
||||
|
||||
if (!updatedTiles.TryGetValue(chunk, out var tiles))
|
||||
{
|
||||
tiles = new HashSet<Vector2i>();
|
||||
updatedTiles[chunk] = tiles;
|
||||
}
|
||||
|
||||
updatedTiles[chunk].Add(invalid);
|
||||
chunk.Update(data, invalid);
|
||||
}
|
||||
}
|
||||
|
||||
var currentTick = _gameTiming.CurTick;
|
||||
|
||||
// Set the LastUpdate for chunks.
|
||||
foreach (var (chunk, _) in updatedTiles)
|
||||
{
|
||||
chunk.Dirty(currentTick);
|
||||
}
|
||||
|
||||
// Now we'll go through each player, then through each chunk in range of that player checking if the player is still in range
|
||||
// If they are, check if they need the new data to send (i.e. if there's an overlay for the gas).
|
||||
// Afterwards we reset all the chunk data for the next time we tick.
|
||||
foreach (var (session, overlay) in _knownPlayerChunks)
|
||||
{
|
||||
if (session.AttachedEntity == null) continue;
|
||||
|
||||
// Get chunks in range and update if we've moved around or the chunks have new overlay data
|
||||
var chunksInRange = GetChunksInRange(session.AttachedEntity);
|
||||
var knownChunks = overlay.GetKnownChunks();
|
||||
var chunksToRemove = new List<GasOverlayChunk>();
|
||||
var chunksToAdd = new List<GasOverlayChunk>();
|
||||
|
||||
foreach (var chunk in chunksInRange)
|
||||
{
|
||||
if (!knownChunks.Contains(chunk))
|
||||
{
|
||||
chunksToAdd.Add(chunk);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var chunk in knownChunks)
|
||||
{
|
||||
if (!chunksInRange.Contains(chunk))
|
||||
{
|
||||
chunksToRemove.Add(chunk);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var chunk in chunksToAdd)
|
||||
{
|
||||
var message = overlay.AddChunk(currentTick, chunk);
|
||||
if (message != null)
|
||||
{
|
||||
RaiseNetworkEvent(message, session.ConnectedClient);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var chunk in chunksToRemove)
|
||||
{
|
||||
overlay.RemoveChunk(chunk);
|
||||
}
|
||||
|
||||
var clientInvalids = new Dictionary<GridId, List<(Vector2i, GasOverlayData)>>();
|
||||
|
||||
// Check for any dirty chunks in range and bundle the data to send to the client.
|
||||
foreach (var chunk in chunksInRange)
|
||||
{
|
||||
if (!updatedTiles.TryGetValue(chunk, out var invalids)) continue;
|
||||
|
||||
if (!clientInvalids.TryGetValue(chunk.GridIndices, out var existingData))
|
||||
{
|
||||
existingData = new List<(Vector2i, GasOverlayData)>();
|
||||
clientInvalids[chunk.GridIndices] = existingData;
|
||||
}
|
||||
|
||||
chunk.GetData(existingData, invalids);
|
||||
}
|
||||
|
||||
foreach (var (grid, data) in clientInvalids)
|
||||
{
|
||||
RaiseNetworkEvent(overlay.UpdateClient(grid, data), session.ConnectedClient);
|
||||
}
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
_invalidTiles.Clear();
|
||||
}
|
||||
private sealed class PlayerGasOverlay
|
||||
{
|
||||
private readonly Dictionary<GridId, Dictionary<Vector2i, GasOverlayChunk>> _data =
|
||||
new();
|
||||
|
||||
private readonly Dictionary<GasOverlayChunk, GameTick> _lastSent =
|
||||
new();
|
||||
|
||||
public GasOverlayMessage UpdateClient(GridId grid, List<(Vector2i, GasOverlayData)> data)
|
||||
{
|
||||
return new(grid, data);
|
||||
}
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
_data.Clear();
|
||||
_lastSent.Clear();
|
||||
}
|
||||
|
||||
public List<GasOverlayChunk> GetKnownChunks()
|
||||
{
|
||||
var known = new List<GasOverlayChunk>();
|
||||
|
||||
foreach (var (_, chunks) in _data)
|
||||
{
|
||||
foreach (var (_, chunk) in chunks)
|
||||
{
|
||||
known.Add(chunk);
|
||||
}
|
||||
}
|
||||
|
||||
return known;
|
||||
}
|
||||
|
||||
public GasOverlayMessage? AddChunk(GameTick currentTick, GasOverlayChunk chunk)
|
||||
{
|
||||
if (!_data.TryGetValue(chunk.GridIndices, out var chunks))
|
||||
{
|
||||
chunks = new Dictionary<Vector2i, GasOverlayChunk>();
|
||||
_data[chunk.GridIndices] = chunks;
|
||||
}
|
||||
|
||||
if (_lastSent.TryGetValue(chunk, out var last) && last >= chunk.LastUpdate)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
_lastSent[chunk] = currentTick;
|
||||
var message = ChunkToMessage(chunk);
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
public void RemoveChunk(GasOverlayChunk chunk)
|
||||
{
|
||||
// Don't need to sync to client as they can manage it themself.
|
||||
if (!_data.TryGetValue(chunk.GridIndices, out var chunks))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (chunks.ContainsKey(chunk.Vector2i))
|
||||
{
|
||||
chunks.Remove(chunk.Vector2i);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieve a whole chunk as a message, only getting the relevant tiles for the gas overlay.
|
||||
/// </summary>
|
||||
/// <param name="chunk"></param>
|
||||
/// <returns></returns>
|
||||
private GasOverlayMessage? ChunkToMessage(GasOverlayChunk chunk)
|
||||
{
|
||||
// Chunk data should already be up to date.
|
||||
// Only send relevant tiles to client.
|
||||
|
||||
var tileData = new List<(Vector2i, GasOverlayData)>();
|
||||
|
||||
for (var x = 0; x < ChunkSize; x++)
|
||||
{
|
||||
for (var y = 0; y < ChunkSize; y++)
|
||||
{
|
||||
// TODO: Check could be more robust I think.
|
||||
var data = chunk.TileData[x, y];
|
||||
if ((data.Gas == null || data.Gas.Length == 0) && data.FireState == 0 && data.FireTemperature == 0.0f)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var indices = new Vector2i(chunk.Vector2i.X + x, chunk.Vector2i.Y + y);
|
||||
tileData.Add((indices, data));
|
||||
}
|
||||
}
|
||||
|
||||
if (tileData.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new GasOverlayMessage(chunk.GridIndices, tileData);
|
||||
}
|
||||
}
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
_invalidTiles.Clear();
|
||||
_overlay.Clear();
|
||||
|
||||
foreach (var (_, data) in _knownPlayerChunks)
|
||||
{
|
||||
data.Reset();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user