From f560f88eb58080a8130f812bd0bb65b39ca8a071 Mon Sep 17 00:00:00 2001 From: DrSmugleaf Date: Thu, 19 Oct 2023 12:34:31 -0700 Subject: [PATCH] Remove 700 usages of Component.Owner (#21100) --- .../SpawnExplosion/ExplosionDebugOverlay.cs | 25 +-- .../UI/Tabs/AtmosTab/AddAtmosWindow.xaml.cs | 39 ++-- .../UI/Tabs/ObjectsTab/ObjectsTab.xaml.cs | 34 +++- Content.Client/Alerts/ClientAlertsSystem.cs | 10 +- .../Atmos/Overlays/AtmosDebugOverlay.cs | 29 ++- Content.Client/Audio/AmbientSoundOverlay.cs | 2 +- Content.Client/Audio/AmbientSoundSystem.cs | 36 ++-- .../CardboardBox/CardboardBoxSystem.cs | 10 +- .../Chasm/ChasmFallingVisualsSystem.cs | 2 +- .../Commands/HideMechanismsCommand.cs | 8 +- .../Commands/ShowMechanismsCommand.cs | 9 +- .../Decals/Overlays/DecalOverlay.cs | 4 +- Content.Client/Doors/DoorSystem.cs | 3 +- .../Effects/ColorFlashEffectSystem.cs | 2 +- Content.Client/Explosion/ExplosionOverlay.cs | 5 +- Content.Client/Fluids/PuddleOverlay.cs | 12 +- .../GPS/Systems/HandheldGpsSystem.cs | 4 +- .../GPS/UI/HandheldGpsStatusControl.cs | 10 +- .../Controls/GuideEntityEmbed.xaml.cs | 7 +- Content.Client/Hands/Systems/HandsSystem.cs | 13 +- .../HealthOverlay/HealthOverlaySystem.cs | 8 +- .../HealthOverlay/UI/HealthOverlayGui.cs | 10 +- .../IconSmoothing/IconSmoothSystem.cs | 29 +-- .../Components/InteractionOutlineComponent.cs | 12 +- .../Inventory/ClientInventorySystem.cs | 2 +- .../Components/LightBehaviourComponent.cs | 8 +- .../Light/RgbLightControllerSystem.cs | 16 +- Content.Client/NPC/NPCSteeringSystem.cs | 5 +- Content.Client/NPC/PathfindingSystem.cs | 58 ++++-- .../NetworkConfiguratorLinkOverlay.cs | 20 +- .../Systems/NetworkConfiguratorSystem.cs | 7 +- .../NodeContainer/NodeVisualizationOverlay.cs | 15 +- .../Outline/InteractionOutlineSystem.cs | 10 +- Content.Client/Pinpointer/NavMapSystem.cs | 16 +- .../Overlays/RadiationPulseOverlay.cs | 8 +- .../ReplaySpectatorSystem.Position.cs | 18 +- .../RevenantOverloadedLightsSystem.cs | 2 +- .../Rotation/RotationVisualizerSystem.cs | 2 +- Content.Client/Shuttles/UI/DockingControl.cs | 15 +- Content.Client/Shuttles/UI/RadarControl.cs | 13 +- Content.Client/Sprite/SpriteFadeSystem.cs | 7 +- .../Storage/Systems/ItemMapperSystem.cs | 18 +- Content.Client/SubFloor/TrayScannerSystem.cs | 16 +- .../UserInterface/Controls/SlotControl.cs | 4 +- Content.Client/Weather/WeatherOverlay.cs | 16 +- Content.Client/Weather/WeatherSystem.cs | 6 +- .../Pair/TestPair.Helpers.cs | 5 +- .../Tests/Fluids/FluidSpillTest.cs | 20 +- .../Interaction/InteractionTest.Helpers.cs | 7 +- .../Tests/PostMapInitTest.cs | 9 +- Content.Server/Access/Systems/IdCardSystem.cs | 8 +- .../Commands/RemoveEntityStorageCommand.cs | 2 +- .../Systems/AdminVerbSystem.Smites.cs | 2 +- .../Administration/Systems/BufferingSystem.cs | 9 +- .../AlertLevel/AlertLevelDisplaySystem.cs | 6 +- Content.Server/AlertLevel/AlertLevelSystem.cs | 6 +- Content.Server/Animals/Systems/UdderSystem.cs | 13 +- .../Anomaly/Effects/BluespaceAnomalySystem.cs | 10 +- .../Effects/ElectricityAnomalySystem.cs | 16 +- .../Anomaly/Effects/InjectionAnomalySystem.cs | 4 +- .../Effects/PyroclasticAnomalySystem.cs | 5 +- .../Atmos/Commands/FillGasCommand.cs | 7 +- .../Commands/SetAtmosTemperatureCommand.cs | 7 +- .../Atmos/Commands/SetTemperatureCommand.cs | 10 +- .../Components/GridAtmosphereComponent.cs | 4 +- .../Atmos/EntitySystems/AirtightSystem.cs | 66 +++---- .../EntitySystems/AtmosDebugOverlaySystem.cs | 14 +- .../AtmosphereSystem.BreathTool.cs | 2 +- .../AtmosphereSystem.Commands.cs | 8 +- .../AtmosphereSystem.GridAtmosphere.cs | 29 ++- .../AtmosphereSystem.HighPressureDelta.cs | 38 ++-- .../AtmosphereSystem.Monstermos.cs | 34 ++-- .../AtmosphereSystem.Processing.cs | 117 +++++++----- .../Atmos/EntitySystems/AtmosphereSystem.cs | 8 +- .../Atmos/EntitySystems/FlammableSystem.cs | 17 +- .../Atmos/EntitySystems/GasTankSystem.cs | 125 ++++++------ .../Monitor/Systems/AtmosMonitoringSystem.cs | 38 ++-- .../EntitySystems/GasPassiveGateSystem.cs | 6 +- .../Binary/EntitySystems/GasRecyclerSystem.cs | 20 +- .../Binary/EntitySystems/GasValveSystem.cs | 14 +- .../Piping/EntitySystems/AtmosDeviceSystem.cs | 46 ++--- .../Other/EntitySystems/GasMinerSystem.cs | 12 +- .../Trinary/EntitySystems/GasFilterSystem.cs | 15 +- .../PressureControlledValveSystem.cs | 11 +- .../EntitySystems/GasOutletInjectorSystem.cs | 3 +- Content.Server/Bed/BedSystem.cs | 8 +- Content.Server/Bible/BibleSystem.cs | 33 ++-- .../Body/Commands/DestroyMechanismCommand.cs | 2 +- .../Body/Systems/InternalsSystem.cs | 43 +++-- Content.Server/Body/Systems/LungSystem.cs | 2 +- .../Body/Systems/RespiratorSystem.cs | 10 +- Content.Server/Body/Systems/StomachSystem.cs | 7 +- .../Body/Systems/ThermalRegulatorSystem.cs | 5 +- Content.Server/Botany/Systems/LogSystem.cs | 3 +- .../Botany/Systems/PlantHolderSystem.cs | 5 +- .../Cargo/Systems/CargoSystem.Orders.cs | 7 +- Content.Server/Cargo/Systems/PricingSystem.cs | 5 +- .../Chat/Systems/AutoEmoteSystem.cs | 11 +- .../EntitySystems/ChemMasterSystem.cs | 74 ++++---- .../EntitySystems/ReagentDispenserSystem.cs | 50 ++--- .../SolutionInjectOnCollideSystem.cs | 11 +- .../Chemistry/EntitySystems/VaporSystem.cs | 32 ++-- .../Chemistry/ReagentEffects/Oxygenate.cs | 2 +- Content.Server/Chunking/ChunkingSystem.cs | 11 +- .../Cloning/CloningConsoleSystem.cs | 2 +- Content.Server/Cloning/CloningSystem.cs | 16 +- Content.Server/Clothing/MaskSystem.cs | 11 +- .../CommunicationsConsoleSystem.cs | 2 +- .../Commands/FixRotationsCommand.cs | 9 +- .../Commands/TileReplaceCommand.cs | 6 +- .../Construction/Commands/TileWallsCommand.cs | 12 +- .../ConstructionSystem.Computer.cs | 17 +- .../Construction/ConstructionSystem.cs | 15 +- .../CrewManifest/CrewManifestSystem.cs | 15 +- .../Decals/Commands/AddDecalCommand.cs | 10 +- Content.Server/Decals/DecalSystem.cs | 7 +- .../DeviceLinking/Systems/AutoLinkSystem.cs | 7 +- Content.Server/Doors/Systems/DoorSystem.cs | 12 +- .../Doors/Systems/FirelockSystem.cs | 17 +- .../DisassembleOnAltVerbSystem.cs | 7 +- .../EntitySystems/SpawnAfterInteractSystem.cs | 8 +- .../EntitySystems/ClusterGrenadeSystem.cs | 32 ++-- .../EntitySystems/ExplosionSystem.GridMap.cs | 12 +- .../EntitySystems/TriggerSystem.Voice.cs | 44 +++-- .../Fluids/EntitySystems/DrainSystem.cs | 46 ++--- .../PuddleDebugDebugOverlaySystem.cs | 10 +- .../Fluids/EntitySystems/PuddleSystem.cs | 23 ++- .../Fluids/EntitySystems/SpraySystem.cs | 5 +- .../Systems/ForensicScannerSystem.cs | 19 +- .../GameTicking/GameTicker.Spawning.cs | 30 ++- .../GameTicking/Rules/NukeopsRuleSystem.cs | 16 +- Content.Server/Ghost/Roles/GhostRoleSystem.cs | 82 ++++---- .../Gravity/GravityGeneratorSystem.cs | 68 ++++--- Content.Server/Hands/Systems/HandsSystem.cs | 5 +- .../Holiday/Christmas/RandomGiftSystem.cs | 2 +- .../IdentityManagement/IdentitySystem.cs | 6 +- .../IgnitionSource/IgnitionSourceSystem.cs | 4 +- .../EntitySystems/ReagentGrinderSystem.cs | 6 +- .../EntitySystems/ExpendableLightSystem.cs | 86 +++++---- .../EntitySystems/HandheldLightSystem.cs | 118 ++++++------ .../Light/EntitySystems/MatchboxSystem.cs | 2 +- .../Light/EntitySystems/MatchstickSystem.cs | 41 ++-- .../Light/EntitySystems/PoweredLightSystem.cs | 13 +- Content.Server/Magic/MagicSystem.cs | 4 +- .../MassMedia/Systems/NewsSystem.cs | 29 ++- .../Mech/Systems/MechSystem.Filtering.cs | 5 +- Content.Server/Mech/Systems/MechSystem.cs | 1 + .../BiomassReclaimerSystem.cs | 58 +++--- Content.Server/Medical/CryoPodSystem.cs | 16 +- .../Medical/SuitSensors/SuitSensorSystem.cs | 8 +- Content.Server/Mind/Commands/RenameCommand.cs | 4 +- Content.Server/Morgue/CrematoriumSystem.cs | 5 +- Content.Server/Morgue/MorgueSystem.cs | 10 +- .../Movement/Systems/JetpackSystem.cs | 3 +- .../NPC/Pathfinding/PathfindingSystem.Grid.cs | 36 ++-- .../NPC/Pathfinding/PathfindingSystem.cs | 11 +- .../NPCPerceptionSystem.RecentlyInjected.cs | 5 +- .../NPC/Systems/NPCUtilitySystem.cs | 2 +- .../NPC/Systems/NpcFactionSystem.cs | 12 +- .../EntitySystems/NodeContainerSystem.cs | 6 +- .../Nuke/Commands/SendNukeCodesCommand.cs | 18 +- Content.Server/Nuke/NukeCodePaperSystem.cs | 16 +- .../EntitySystems/AnimalHusbandrySystem.cs | 4 +- .../EntitySystems/SliceableFoodSystem.cs | 7 +- .../Payload/EntitySystems/PayloadSystem.cs | 2 - .../Controllers/RandomWalkController.cs | 20 +- .../Pinpointer/ProximityBeeperSystem.cs | 5 +- .../PneumaticCannon/PneumaticCannonSystem.cs | 17 +- .../Pointing/EntitySystems/PointingSystem.cs | 16 +- .../EntitySystems/RoguePointingSystem.cs | 23 +-- .../Polymorph/Systems/PolymorphSystem.cs | 4 +- .../Power/EntitySystems/CableSystem.Placer.cs | 13 +- .../EntitySystems/ExtensionCableSystem.cs | 55 +++--- .../Power/EntitySystems/PowerNetSystem.cs | 8 +- .../EntitySystems/PowerReceiverSystem.cs | 27 +-- .../Radiation/Systems/GeigerSystem.cs | 61 +++--- .../Systems/RadiationSystem.GridCast.cs | 35 ++-- .../Research/Systems/ResearchSystem.Client.cs | 13 +- .../Systems/ResearchSystem.PointSource.cs | 10 +- .../Research/Systems/ResearchSystem.cs | 11 +- .../Resist/EscapeInventorySystem.cs | 14 +- .../Revenant/EntitySystems/CorporealSystem.cs | 12 +- .../RevenantOverloadedLightsSystem.cs | 7 +- .../Revenant/EntitySystems/RevenantSystem.cs | 24 +-- Content.Server/Salvage/SalvageRulerCommand.cs | 9 +- .../SalvageSystem.ExpeditionConsole.cs | 24 +-- .../Shuttles/Components/ThrusterComponent.cs | 27 +-- .../Systems/DockingSystem.AutoDock.cs | 8 +- .../Shuttles/Systems/DockingSystem.Shuttle.cs | 7 +- .../Shuttles/Systems/DockingSystem.cs | 17 +- .../Systems/EmergencyShuttleSystem.Console.cs | 12 +- .../Systems/ShuttleSystem.FasterThanLight.cs | 46 ++--- .../Shuttles/Systems/ShuttleSystem.IFF.cs | 6 +- .../Shuttles/Systems/ThrusterSystem.cs | 9 + .../ContainmentFieldGeneratorSystem.cs | 178 +++++++++--------- .../EntitySystems/ContainmentFieldSystem.cs | 8 +- .../EntitySystems/EventHorizonSystem.cs | 10 +- .../EntitySystems/GravityWellSystem.cs | 12 +- .../EntitySystems/SingularitySystem.cs | 46 ++--- .../Solar/EntitySystems/PowerSolarSystem.cs | 19 +- .../EntitySystems/AddAccentClothingSystem.cs | 9 +- .../Station/Systems/StationSystem.cs | 22 ++- .../Events/BluespaceLockerRule.cs | 15 +- .../StationEvents/Events/BreakerFlipRule.cs | 15 +- .../StationEvents/Events/MeteorSwarmRule.cs | 12 +- .../Events/PowerGridCheckRule.cs | 17 +- .../Events/RandomSentienceRule.cs | 25 ++- .../EntitySystems/BluespaceLockerSystem.cs | 8 +- .../CursedEntityStorageSystem.cs | 18 +- .../EntitySystems/EntityStorageSystem.cs | 6 +- .../Storage/EntitySystems/PickRandomSystem.cs | 6 +- .../EntitySystems/SpawnItemsOnUseSystem.cs | 3 +- Content.Server/Strip/StrippableSystem.cs | 59 +++--- .../SurveillanceCameraMonitorSystem.cs | 19 +- Content.Server/Tabletop/TabletopSystem.cs | 14 +- .../Temperature/Systems/TemperatureSystem.cs | 10 +- Content.Server/Tools/ToolSystem.Welder.cs | 13 +- .../SurplusBundle/SurplusBundleSystem.cs | 6 +- .../Traits/Assorted/NarcolepsySystem.cs | 5 +- .../Effects/Systems/PolyArtifactSystem.cs | 8 +- .../Effects/Systems/ShuffleArtifactSystem.cs | 4 +- .../RandomArtifactSpriteSystem.cs | 7 +- .../Systems/ArtifactDeathTriggerSystem.cs | 9 +- .../ArtifactElectricityTriggerSystem.cs | 10 +- .../Systems/ArtifactGasTriggerSystem.cs | 11 +- .../Systems/ArtifactHeatTriggerSystem.cs | 10 +- .../Systems/ArtifactMagnetTriggerSystem.cs | 12 +- .../Systems/ArtifactMusicTriggerSystem.cs | 21 ++- .../Systems/ArtifactPressureTriggerSystem.cs | 10 +- .../Systems/ArtifactTimerTriggerSystem.cs | 9 +- .../Access/Systems/SharedIdCardSystem.cs | 14 +- .../Actions/ActionContainerSystem.cs | 4 +- Content.Shared/Actions/SharedActionsSystem.cs | 6 +- Content.Shared/Alert/AlertsSystem.cs | 22 +-- .../Buckle/SharedBuckleSystem.Buckle.cs | 2 +- .../MetabolismMovespeedModifierSystem.cs | 17 +- .../Containers/ItemSlot/ItemSlotsSystem.cs | 2 +- .../EntityCoordinatesExtensions.cs | 5 - .../Doors/Systems/SharedDoorSystem.cs | 98 +++++----- Content.Shared/Examine/ExamineSystemShared.cs | 16 +- Content.Shared/Follower/FollowerSystem.cs | 4 +- .../Friction/TileFrictionController.cs | 8 +- .../Gravity/SharedFloatingVisualizerSystem.cs | 6 +- .../EntitySystems/SharedHandsSystem.Pickup.cs | 3 +- .../Hands/EntitySystems/SharedHandsSystem.cs | 4 +- .../Hands/SharedHandVirtualItemSystem.cs | 12 +- Content.Shared/Lathe/SharedLatheSystem.cs | 2 +- .../Light/SharedHandheldLightSystem.cs | 4 +- Content.Shared/Maps/TurfHelpers.cs | 7 +- .../Systems/MobStateSystem.StateMachine.cs | 4 +- .../Controllers/SharedConveyorController.cs | 2 +- Content.Shared/Random/RulesSystem.cs | 16 +- .../SharedRevenantOverloadedLightsSystem.cs | 4 +- .../ContainmentFieldGeneratorComponent.cs | 2 +- .../EntitySystems/SharedSingularitySystem.cs | 11 +- Content.Shared/Stacks/SharedStackSystem.cs | 5 +- .../StatusEffect/StatusEffectsSystem.cs | 7 +- .../Storage/EntitySystems/DumpableSystem.cs | 2 +- .../Strip/SharedStrippableSystem.cs | 4 +- Content.Shared/Weather/SharedWeatherSystem.cs | 5 +- SpaceStation14.sln.DotSettings | 7 +- 261 files changed, 2285 insertions(+), 2030 deletions(-) diff --git a/Content.Client/Administration/UI/SpawnExplosion/ExplosionDebugOverlay.cs b/Content.Client/Administration/UI/SpawnExplosion/ExplosionDebugOverlay.cs index e175f39661..eede3a6217 100644 --- a/Content.Client/Administration/UI/SpawnExplosion/ExplosionDebugOverlay.cs +++ b/Content.Client/Administration/UI/SpawnExplosion/ExplosionDebugOverlay.cs @@ -1,10 +1,12 @@ +using System.Linq; +using System.Numerics; using JetBrains.Annotations; +using Robust.Client.GameObjects; using Robust.Client.Graphics; using Robust.Client.ResourceManagement; using Robust.Shared.Enums; using Robust.Shared.Map; -using System.Linq; -using System.Numerics; +using Robust.Shared.Map.Components; namespace Content.Client.Administration.UI.SpawnExplosion; @@ -13,7 +15,6 @@ public sealed class ExplosionDebugOverlay : Overlay { [Dependency] private readonly IEntityManager _entityManager = default!; [Dependency] private readonly IEyeManager _eyeManager = default!; - [Dependency] private readonly IMapManager _mapManager = default!; public Dictionary>? SpaceTiles; public Dictionary>> Tiles = new(); @@ -61,14 +62,15 @@ public sealed class ExplosionDebugOverlay : Overlay var handle = args.ScreenHandle; Box2 gridBounds; var xformQuery = _entityManager.GetEntityQuery(); + var xformSystem = _entityManager.System(); foreach (var (gridId, tileSets) in Tiles) { - if (!_mapManager.TryGetGrid(gridId, out var grid)) + if (!_entityManager.TryGetComponent(gridId, out MapGridComponent? grid)) continue; - var gridXform = xformQuery.GetComponent(grid.Owner); - var (_, _, matrix, invMatrix) = gridXform.GetWorldPositionRotationMatrixWithInv(xformQuery); + var gridXform = xformQuery.GetComponent(gridId); + var (_, _, matrix, invMatrix) = xformSystem.GetWorldPositionRotationMatrixWithInv(gridXform, xformQuery); gridBounds = invMatrix.TransformBox(args.WorldBounds).Enlarged(grid.TileSize * 2); DrawText(handle, gridBounds, matrix, tileSets, grid.TileSize); } @@ -114,9 +116,9 @@ public sealed class ExplosionDebugOverlay : Overlay } } - if (tileSets.ContainsKey(0)) + if (tileSets.TryGetValue(0, out var set)) { - var epicenter = tileSets[0].First(); + var epicenter = set.First(); var worldCenter = transform.Transform((epicenter + Vector2Helpers.Half) * tileSize); var screenCenter = _eyeManager.WorldToScreen(worldCenter) + new Vector2(-24, -24); var text = $"{Intensity[0]:F2}\nΣ={TotalIntensity:F1}\nΔ={Slope:F1}"; @@ -129,14 +131,15 @@ public sealed class ExplosionDebugOverlay : Overlay var handle = args.WorldHandle; Box2 gridBounds; var xformQuery = _entityManager.GetEntityQuery(); + var xformSystem = _entityManager.System(); foreach (var (gridId, tileSets) in Tiles) { - if (!_mapManager.TryGetGrid(gridId, out var grid)) + if (!_entityManager.TryGetComponent(gridId, out MapGridComponent? grid)) continue; - var gridXform = xformQuery.GetComponent(grid.Owner); - var (_, _, worldMatrix, invWorldMatrix) = gridXform.GetWorldPositionRotationMatrixWithInv(xformQuery); + var gridXform = xformQuery.GetComponent(gridId); + var (_, _, worldMatrix, invWorldMatrix) = xformSystem.GetWorldPositionRotationMatrixWithInv(gridXform, xformQuery); gridBounds = invWorldMatrix.TransformBox(args.WorldBounds).Enlarged(grid.TileSize * 2); handle.SetTransform(worldMatrix); DrawTiles(handle, gridBounds, tileSets, SpaceTileSize); diff --git a/Content.Client/Administration/UI/Tabs/AtmosTab/AddAtmosWindow.xaml.cs b/Content.Client/Administration/UI/Tabs/AtmosTab/AddAtmosWindow.xaml.cs index 2f643caae2..7e2fdda3e2 100644 --- a/Content.Client/Administration/UI/Tabs/AtmosTab/AddAtmosWindow.xaml.cs +++ b/Content.Client/Administration/UI/Tabs/AtmosTab/AddAtmosWindow.xaml.cs @@ -1,14 +1,10 @@ -using System.Collections.Generic; -using System.Linq; using JetBrains.Annotations; using Robust.Client.AutoGenerated; using Robust.Client.Console; using Robust.Client.Player; using Robust.Client.UserInterface.Controls; using Robust.Client.UserInterface.CustomControls; -using Robust.Shared.GameObjects; -using Robust.Shared.IoC; -using Robust.Shared.Map; +using Robust.Client.UserInterface.XAML; using Robust.Shared.Map.Components; namespace Content.Client.Administration.UI.Tabs.AtmosTab @@ -17,16 +13,29 @@ namespace Content.Client.Administration.UI.Tabs.AtmosTab [UsedImplicitly] public sealed partial class AddAtmosWindow : DefaultWindow { - private IEnumerable? _data; + [Dependency] private readonly IPlayerManager _players = default!; + [Dependency] private readonly IEntityManager _entities = default!; + + private readonly List> _data = new(); + + public AddAtmosWindow() + { + RobustXamlLoader.Load(this); + IoCManager.InjectDependencies(this); + } protected override void EnteredTree() { - _data = IoCManager.Resolve().GetAllGrids().Where(g => (int) g.Owner != 0); - foreach (var grid in _data) + _data.Clear(); + + var player = _players.LocalPlayer?.ControlledEntity; + var playerGrid = _entities.GetComponentOrNull(player)?.GridUid; + var query = IoCManager.Resolve().AllEntityQueryEnumerator(); + + while (query.MoveNext(out var uid, out var grid)) { - var player = IoCManager.Resolve().LocalPlayer?.ControlledEntity; - var playerGrid = IoCManager.Resolve().GetComponentOrNull(player)?.GridUid; - GridOptions.AddItem($"{grid.Owner} {(playerGrid == grid.Owner ? " (Current)" : "")}"); + _data.Add((uid, grid)); + GridOptions.AddItem($"{uid} {(playerGrid == uid ? " (Current)" : "")}"); } GridOptions.OnItemSelected += eventArgs => GridOptions.SelectId(eventArgs.Id); @@ -35,12 +44,8 @@ namespace Content.Client.Administration.UI.Tabs.AtmosTab private void SubmitButtonOnOnPressed(BaseButton.ButtonEventArgs obj) { - if (_data == null) - return; - var dataList = _data.ToList(); - var entManager = IoCManager.Resolve(); - var selectedGrid = dataList[GridOptions.SelectedId].Owner; - IoCManager.Resolve().ExecuteCommand($"addatmos {entManager.GetNetEntity(selectedGrid)}"); + var selectedGrid = _data[GridOptions.SelectedId].Owner; + IoCManager.Resolve().ExecuteCommand($"addatmos {_entities.GetNetEntity(selectedGrid)}"); } } } diff --git a/Content.Client/Administration/UI/Tabs/ObjectsTab/ObjectsTab.xaml.cs b/Content.Client/Administration/UI/Tabs/ObjectsTab/ObjectsTab.xaml.cs index 9ad0ca8cc6..3f5df2cf00 100644 --- a/Content.Client/Administration/UI/Tabs/ObjectsTab/ObjectsTab.xaml.cs +++ b/Content.Client/Administration/UI/Tabs/ObjectsTab/ObjectsTab.xaml.cs @@ -1,4 +1,3 @@ -using System.Linq; using Content.Client.Station; using Robust.Client.AutoGenerated; using Robust.Client.UserInterface; @@ -40,13 +39,34 @@ public sealed partial class ObjectsTab : Control private void RefreshObjectList(ObjectsTabSelection selection) { - var entities = selection switch + var entities = new List(); + switch (selection) { - ObjectsTabSelection.Stations => _entityManager.EntitySysManager.GetEntitySystem().Stations.ToList(), - ObjectsTabSelection.Grids => _entityManager.EntityQuery(true).Select(x => x.Owner).ToList(), - ObjectsTabSelection.Maps => _entityManager.EntityQuery(true).Select(x => x.Owner).ToList(), - _ => throw new ArgumentOutOfRangeException(nameof(selection), selection, null), - }; + case ObjectsTabSelection.Stations: + entities.AddRange(_entityManager.EntitySysManager.GetEntitySystem().Stations); + break; + case ObjectsTabSelection.Grids: + { + var query = _entityManager.AllEntityQueryEnumerator(); + while (query.MoveNext(out var uid, out _)) + { + entities.Add(uid); + } + + break; + } + case ObjectsTabSelection.Maps: + { + var query = _entityManager.AllEntityQueryEnumerator(); + while (query.MoveNext(out var uid, out _)) + { + entities.Add(uid); + } + break; + } + default: + throw new ArgumentOutOfRangeException(nameof(selection), selection, null); + } foreach (var control in _objects) { diff --git a/Content.Client/Alerts/ClientAlertsSystem.cs b/Content.Client/Alerts/ClientAlertsSystem.cs index cfdae7bc93..bb6d2d4df4 100644 --- a/Content.Client/Alerts/ClientAlertsSystem.cs +++ b/Content.Client/Alerts/ClientAlertsSystem.cs @@ -47,20 +47,20 @@ public sealed class ClientAlertsSystem : AlertsSystem } } - protected override void AfterShowAlert(AlertsComponent alertsComponent) + protected override void AfterShowAlert(Entity alerts) { - if (_playerManager.LocalPlayer?.ControlledEntity != alertsComponent.Owner) + if (_playerManager.LocalPlayer?.ControlledEntity != alerts.Owner) return; - SyncAlerts?.Invoke(this, alertsComponent.Alerts); + SyncAlerts?.Invoke(this, alerts.Comp.Alerts); } - protected override void AfterClearAlert(AlertsComponent alertsComponent) + protected override void AfterClearAlert(Entity alertsComponent) { if (_playerManager.LocalPlayer?.ControlledEntity != alertsComponent.Owner) return; - SyncAlerts?.Invoke(this, alertsComponent.Alerts); + SyncAlerts?.Invoke(this, alertsComponent.Comp.Alerts); } private void ClientAlertsHandleState(EntityUid uid, AlertsComponent component, ref AfterAutoHandleStateEvent args) diff --git a/Content.Client/Atmos/Overlays/AtmosDebugOverlay.cs b/Content.Client/Atmos/Overlays/AtmosDebugOverlay.cs index 6d1752a8c9..72adf276bf 100644 --- a/Content.Client/Atmos/Overlays/AtmosDebugOverlay.cs +++ b/Content.Client/Atmos/Overlays/AtmosDebugOverlay.cs @@ -4,10 +4,8 @@ using Content.Shared.Atmos; using Content.Shared.Atmos.EntitySystems; using Robust.Client.Graphics; using Robust.Shared.Enums; -using Robust.Shared.GameObjects; -using Robust.Shared.IoC; using Robust.Shared.Map; -using Robust.Shared.Maths; +using Robust.Shared.Map.Components; namespace Content.Client.Atmos.Overlays { @@ -19,6 +17,7 @@ namespace Content.Client.Atmos.Overlays [Dependency] private readonly IMapManager _mapManager = default!; public override OverlaySpace Space => OverlaySpace.WorldSpace; + private List> _grids = new(); internal AtmosDebugOverlay(AtmosDebugOverlaySystem system) { @@ -41,10 +40,19 @@ namespace Content.Client.Atmos.Overlays // 3. "Is this going to make it harder for atmos programmers to add data that may not be chunk-friendly into the atmos debugger?" // Nanotrasen needs YOU! to avoid premature optimization in critical debugging tools - 20kdc - foreach (var mapGrid in _mapManager.FindGridsIntersecting(mapId, worldBounds)) + _grids.Clear(); + + _mapManager.FindGridsIntersecting(mapId, worldBounds, ref _grids, (EntityUid uid, MapGridComponent grid, + ref List> state) => + { + state.Add((uid, grid)); + return true; + }); + + foreach (var (uid, mapGrid) in _grids) { - if (!_atmosDebugOverlaySystem.HasData(mapGrid.Owner) || - !_entManager.TryGetComponent(mapGrid.Owner, out var xform)) + if (!_atmosDebugOverlaySystem.HasData(uid) || + !_entManager.TryGetComponent(uid, out var xform)) continue; drawHandle.SetTransform(xform.WorldMatrix); @@ -53,7 +61,7 @@ namespace Content.Client.Atmos.Overlays { foreach (var tile in mapGrid.GetTilesIntersecting(worldBounds)) { - var dataMaybeNull = _atmosDebugOverlaySystem.GetData(mapGrid.Owner, tile.GridIndices); + var dataMaybeNull = _atmosDebugOverlaySystem.GetData(uid, tile.GridIndices); if (dataMaybeNull != null) { var data = (SharedAtmosDebugOverlaySystem.AtmosDebugOverlayData) dataMaybeNull; @@ -61,9 +69,10 @@ namespace Content.Client.Atmos.Overlays { // -- Mole Count -- float total = 0; - switch (_atmosDebugOverlaySystem.CfgMode) { + switch (_atmosDebugOverlaySystem.CfgMode) + { case AtmosDebugOverlayMode.TotalMoles: - foreach (float f in data.Moles) + foreach (var f in data.Moles) { total += f; } @@ -75,7 +84,7 @@ namespace Content.Client.Atmos.Overlays total = data.Temperature; break; } - var interp = ((total - _atmosDebugOverlaySystem.CfgBase) / _atmosDebugOverlaySystem.CfgScale); + var interp = (total - _atmosDebugOverlaySystem.CfgBase) / _atmosDebugOverlaySystem.CfgScale; Color res; if (_atmosDebugOverlaySystem.CfgCBM) { diff --git a/Content.Client/Audio/AmbientSoundOverlay.cs b/Content.Client/Audio/AmbientSoundOverlay.cs index 3110d81384..703430df9e 100644 --- a/Content.Client/Audio/AmbientSoundOverlay.cs +++ b/Content.Client/Audio/AmbientSoundOverlay.cs @@ -39,7 +39,7 @@ public sealed class AmbientSoundOverlay : Overlay if (ambientSound.Enabled) { - if (_ambient.IsActive(ambientSound)) + if (_ambient.IsActive((ent, ambientSound))) { worldHandle.DrawCircle(xformSystem.GetWorldPosition(xform), Size, Color.LightGreen.WithAlpha(Alpha * 2f)); } diff --git a/Content.Client/Audio/AmbientSoundSystem.cs b/Content.Client/Audio/AmbientSoundSystem.cs index 8fe331119a..aebacb94f6 100644 --- a/Content.Client/Audio/AmbientSoundSystem.cs +++ b/Content.Client/Audio/AmbientSoundSystem.cs @@ -1,18 +1,16 @@ +using System.Linq; +using System.Numerics; using Content.Shared.Audio; using Content.Shared.CCVar; +using Robust.Client.GameObjects; using Robust.Client.Graphics; using Robust.Client.Player; using Robust.Shared.Audio; -using Robust.Shared.Log; using Robust.Shared.Configuration; -using Robust.Shared.Map; using Robust.Shared.Physics; using Robust.Shared.Random; using Robust.Shared.Timing; using Robust.Shared.Utility; -using System.Linq; -using System.Numerics; -using Robust.Client.GameObjects; namespace Content.Client.Audio; //TODO: This is using a incomplete version of the whole "only play nearest sounds" algo, that breaks down a bit should the ambient sound cap get hit. @@ -50,7 +48,7 @@ public sealed class AmbientSoundSystem : SharedAmbientSoundSystem /// private int MaxSingleSound => (int) (_maxAmbientCount / (16.0f / 6.0f)); - private readonly Dictionary _playingSounds = new(); + private readonly Dictionary, (IPlayingAudioStream? Stream, SoundSpecifier Sound, string Path)> _playingSounds = new(); private readonly Dictionary _playingCount = new(); public bool OverlayEnabled @@ -80,7 +78,7 @@ public sealed class AmbientSoundSystem : SharedAmbientSoundSystem /// /// /// - public bool IsActive(AmbientSoundComponent component) + public bool IsActive(Entity component) { return _playingSounds.ContainsKey(component); } @@ -100,7 +98,7 @@ public sealed class AmbientSoundSystem : SharedAmbientSoundSystem private void OnShutdown(EntityUid uid, AmbientSoundComponent component, ComponentShutdown args) { - if (!_playingSounds.Remove(component, out var sound)) + if (!_playingSounds.Remove((uid, component), out var sound)) return; sound.Stream?.Stop(); @@ -113,7 +111,7 @@ public sealed class AmbientSoundSystem : SharedAmbientSoundSystem { _ambienceVolume = value; - foreach (var (comp, values) in _playingSounds) + foreach (var ((_, comp), values) in _playingSounds) { if (values.Stream == null) continue; @@ -188,7 +186,7 @@ public sealed class AmbientSoundSystem : SharedAmbientSoundSystem private readonly struct QueryState { - public readonly Dictionary> SourceDict = new(); + public readonly Dictionary)>> SourceDict = new(); public readonly Vector2 MapPos; public readonly TransformComponent Player; public readonly EntityQuery Query; @@ -226,7 +224,7 @@ public sealed class AmbientSoundSystem : SharedAmbientSoundSystem // Prioritize far away & loud sounds. var importance = range * (ambientComp.Volume + 32); - state.SourceDict.GetOrNew(key).Add((importance, ambientComp)); + state.SourceDict.GetOrNew(key).Add((importance, (ambientComp.Owner, ambientComp))); return true; } @@ -240,9 +238,10 @@ public sealed class AmbientSoundSystem : SharedAmbientSoundSystem var mapPos = playerXform.MapPosition; // Remove out-of-range ambiences - foreach (var (comp, sound) in _playingSounds) + foreach (var (ent, sound) in _playingSounds) { - var entity = comp.Owner; + var entity = ent.Owner; + var comp = ent.Comp; if (comp.Enabled && // Don't keep playing sounds that have changed since. @@ -260,7 +259,7 @@ public sealed class AmbientSoundSystem : SharedAmbientSoundSystem } sound.Stream?.Stop(); - _playingSounds.Remove(comp); + _playingSounds.Remove((entity, comp)); _playingCount[sound.Path] -= 1; if (_playingCount[sound.Path] == 0) _playingCount.Remove(sound.Path); @@ -285,11 +284,12 @@ public sealed class AmbientSoundSystem : SharedAmbientSoundSystem sources.Sort(static (a, b) => b.Importance.CompareTo(a.Importance)); - foreach (var (_, comp) in sources) + foreach (var (_, ent) in sources) { - var uid = comp.Owner; + var uid = ent.Owner; + var comp = ent.Comp; - if (_playingSounds.ContainsKey(comp) || + if (_playingSounds.ContainsKey(ent) || metaQuery.GetComponent(uid).EntityPaused) continue; @@ -303,7 +303,7 @@ public sealed class AmbientSoundSystem : SharedAmbientSoundSystem if (stream == null) continue; - _playingSounds[comp] = (stream, comp.Sound, key); + _playingSounds[ent] = (stream, comp.Sound, key); playingCount++; if (_playingSounds.Count >= _maxAmbientCount) diff --git a/Content.Client/CardboardBox/CardboardBoxSystem.cs b/Content.Client/CardboardBox/CardboardBoxSystem.cs index 3c870f6e6e..5e479409cf 100644 --- a/Content.Client/CardboardBox/CardboardBoxSystem.cs +++ b/Content.Client/CardboardBox/CardboardBoxSystem.cs @@ -38,12 +38,16 @@ public sealed class CardboardBoxSystem : SharedCardboardBoxSystem var mover = GetEntity(msg.Mover); //Filter out entities in range to see that they're a mob and add them to the mobMoverEntities hash for faster lookup - foreach (var moverComp in _entityLookup.GetComponentsInRange(xform.Coordinates, box.Distance)) + var movers = new HashSet>(); + _entityLookup.GetEntitiesInRange(xform.Coordinates, box.Distance, movers); + + foreach (var moverComp in movers) { - if (moverComp.Owner == mover) + var uid = moverComp.Owner; + if (uid == mover) continue; - mobMoverEntities.Add(moverComp.Owner); + mobMoverEntities.Add(uid); } //Play the effect for the mobs as long as they can see the box and are in range. diff --git a/Content.Client/Chasm/ChasmFallingVisualsSystem.cs b/Content.Client/Chasm/ChasmFallingVisualsSystem.cs index a22ea945ef..4b04aa9dd7 100644 --- a/Content.Client/Chasm/ChasmFallingVisualsSystem.cs +++ b/Content.Client/Chasm/ChasmFallingVisualsSystem.cs @@ -33,7 +33,7 @@ public sealed class ChasmFallingVisualsSystem : EntitySystem if (_anim.HasRunningAnimation(player, _chasmFallAnimationKey)) return; - _anim.Play(player, GetFallingAnimation(component), _chasmFallAnimationKey); + _anim.Play((uid, player), GetFallingAnimation(component), _chasmFallAnimationKey); } private void OnComponentRemove(EntityUid uid, ChasmFallingComponent component, ComponentRemove args) diff --git a/Content.Client/Commands/HideMechanismsCommand.cs b/Content.Client/Commands/HideMechanismsCommand.cs index e9c2073b20..28433d2337 100644 --- a/Content.Client/Commands/HideMechanismsCommand.cs +++ b/Content.Client/Commands/HideMechanismsCommand.cs @@ -16,18 +16,18 @@ namespace Content.Client.Commands { var entityManager = IoCManager.Resolve(); var containerSys = entityManager.System(); - var organs = entityManager.EntityQuery(true); + var query = entityManager.AllEntityQueryEnumerator(); - foreach (var part in organs) + while (query.MoveNext(out var uid, out _)) { - if (!entityManager.TryGetComponent(part.Owner, out SpriteComponent? sprite)) + if (!entityManager.TryGetComponent(uid, out SpriteComponent? sprite)) { continue; } sprite.ContainerOccluded = false; - var tempParent = part.Owner; + var tempParent = uid; while (containerSys.TryGetContainingContainer(tempParent, out var container)) { if (!container.ShowContents) diff --git a/Content.Client/Commands/ShowMechanismsCommand.cs b/Content.Client/Commands/ShowMechanismsCommand.cs index f86aee8714..b94278f8c9 100644 --- a/Content.Client/Commands/ShowMechanismsCommand.cs +++ b/Content.Client/Commands/ShowMechanismsCommand.cs @@ -17,14 +17,11 @@ namespace Content.Client.Commands public void Execute(IConsoleShell shell, string argStr, string[] args) { var entityManager = IoCManager.Resolve(); - var organs = entityManager.EntityQuery(true); + var query = entityManager.AllEntityQueryEnumerator(); - foreach (var mechanism in organs) + while (query.MoveNext(out _, out var sprite)) { - if (entityManager.TryGetComponent(mechanism.Owner, out SpriteComponent? sprite)) - { - sprite.ContainerOccluded = false; - } + sprite.ContainerOccluded = false; } IoCManager.Resolve().ExecuteCommand("showcontainedcontext"); diff --git a/Content.Client/Decals/Overlays/DecalOverlay.cs b/Content.Client/Decals/Overlays/DecalOverlay.cs index c37a0e3aea..f2c11e2a68 100644 --- a/Content.Client/Decals/Overlays/DecalOverlay.cs +++ b/Content.Client/Decals/Overlays/DecalOverlay.cs @@ -31,11 +31,11 @@ namespace Content.Client.Decals.Overlays // Shouldn't need to clear cached textures unless the prototypes get reloaded. var handle = args.WorldHandle; var xformQuery = _entManager.GetEntityQuery(); + var xformSystem = _entManager.System(); var eyeAngle = args.Viewport.Eye?.Rotation ?? Angle.Zero; foreach (var (decalGrid, xform) in _entManager.EntityQuery(true)) { - var gridId = decalGrid.Owner; var zIndexDictionary = decalGrid.DecalRenderIndex; if (zIndexDictionary.Count == 0) @@ -44,7 +44,7 @@ namespace Content.Client.Decals.Overlays if (xform.MapID != args.MapId) continue; - var (_, worldRot, worldMatrix) = xform.GetWorldPositionRotationMatrix(xformQuery); + var (_, worldRot, worldMatrix) = xformSystem.GetWorldPositionRotationMatrix(xform, xformQuery); handle.SetTransform(worldMatrix); diff --git a/Content.Client/Doors/DoorSystem.cs b/Content.Client/Doors/DoorSystem.cs index c4b88346de..4b82d3506a 100644 --- a/Content.Client/Doors/DoorSystem.cs +++ b/Content.Client/Doors/DoorSystem.cs @@ -22,8 +22,9 @@ public sealed class DoorSystem : SharedDoorSystem SubscribeLocalEvent(OnAppearanceChange); } - protected override void OnComponentInit(EntityUid uid, DoorComponent comp, ComponentInit args) + protected override void OnComponentInit(Entity ent, ref ComponentInit args) { + var comp = ent.Comp; comp.OpenSpriteStates = new(2); comp.ClosedSpriteStates = new(2); diff --git a/Content.Client/Effects/ColorFlashEffectSystem.cs b/Content.Client/Effects/ColorFlashEffectSystem.cs index 34acb7f370..9a84401948 100644 --- a/Content.Client/Effects/ColorFlashEffectSystem.cs +++ b/Content.Client/Effects/ColorFlashEffectSystem.cs @@ -114,7 +114,7 @@ public sealed class ColorFlashEffectSystem : SharedColorFlashEffectSystem var comp = EnsureComp(ent); comp.NetSyncEnabled = false; comp.Color = sprite.Color; - _animation.Play(player, animation, AnimationKey); + _animation.Play((ent, player), animation, AnimationKey); } } } diff --git a/Content.Client/Explosion/ExplosionOverlay.cs b/Content.Client/Explosion/ExplosionOverlay.cs index 17df782887..2ab84d4438 100644 --- a/Content.Client/Explosion/ExplosionOverlay.cs +++ b/Content.Client/Explosion/ExplosionOverlay.cs @@ -4,6 +4,7 @@ using JetBrains.Annotations; using Robust.Client.Graphics; using Robust.Shared.Enums; using Robust.Shared.Map; +using Robust.Shared.Map.Components; using Robust.Shared.Prototypes; using Robust.Shared.Random; @@ -63,10 +64,10 @@ public sealed class ExplosionOverlay : Overlay Box2 gridBounds; foreach (var (gridId, tiles) in visuals.Tiles) { - if (!_mapManager.TryGetGrid(gridId, out var grid)) + if (!_entMan.TryGetComponent(gridId, out MapGridComponent? grid)) continue; - var xform = xforms.GetComponent(grid.Owner); + var xform = xforms.GetComponent(gridId); var (_, _, worldMatrix, invWorldMatrix) = xform.GetWorldPositionRotationMatrixWithInv(xforms); gridBounds = invWorldMatrix.TransformBox(worldBounds).Enlarged(grid.TileSize * 2); diff --git a/Content.Client/Fluids/PuddleOverlay.cs b/Content.Client/Fluids/PuddleOverlay.cs index f2f5ca1b9a..8c8b13a1ef 100644 --- a/Content.Client/Fluids/PuddleOverlay.cs +++ b/Content.Client/Fluids/PuddleOverlay.cs @@ -1,9 +1,9 @@ -using System.Numerics; -using Content.Shared.FixedPoint; +using Content.Shared.FixedPoint; using Robust.Client.Graphics; using Robust.Client.ResourceManagement; using Robust.Shared.Enums; using Robust.Shared.Map; +using Robust.Shared.Map.Components; namespace Content.Client.Fluids; @@ -52,7 +52,7 @@ public sealed class PuddleOverlay : Overlay foreach (var gridId in _debugOverlaySystem.TileData.Keys) { - if (!_mapManager.TryGetGrid(gridId, out var mapGrid)) + if (!_entityManager.TryGetComponent(gridId, out MapGridComponent? mapGrid)) continue; var gridXform = xformQuery.GetComponent(gridId); @@ -60,7 +60,7 @@ public sealed class PuddleOverlay : Overlay gridBounds = invWorldMatrix.TransformBox(args.WorldBounds).Enlarged(mapGrid.TileSize * 2); drawHandle.SetTransform(worldMatrix); - foreach (var debugOverlayData in _debugOverlaySystem.GetData(mapGrid.Owner)) + foreach (var debugOverlayData in _debugOverlaySystem.GetData(gridId)) { var centre = (debugOverlayData.Pos + Vector2Helpers.Half) * mapGrid.TileSize; @@ -85,14 +85,14 @@ public sealed class PuddleOverlay : Overlay foreach (var gridId in _debugOverlaySystem.TileData.Keys) { - if (!_mapManager.TryGetGrid(gridId, out var mapGrid)) + if (!_entityManager.TryGetComponent(gridId, out MapGridComponent? mapGrid)) continue; var gridXform = xformQuery.GetComponent(gridId); var (_, _, matrix, invMatrix) = gridXform.GetWorldPositionRotationMatrixWithInv(xformQuery); var gridBounds = invMatrix.TransformBox(args.WorldBounds).Enlarged(mapGrid.TileSize * 2); - foreach (var debugOverlayData in _debugOverlaySystem.GetData(mapGrid.Owner)) + foreach (var debugOverlayData in _debugOverlaySystem.GetData(gridId)) { var centre = (debugOverlayData.Pos + Vector2Helpers.Half) * mapGrid.TileSize; diff --git a/Content.Client/GPS/Systems/HandheldGpsSystem.cs b/Content.Client/GPS/Systems/HandheldGpsSystem.cs index 5bc92f0c28..fa680de1fc 100644 --- a/Content.Client/GPS/Systems/HandheldGpsSystem.cs +++ b/Content.Client/GPS/Systems/HandheldGpsSystem.cs @@ -12,8 +12,8 @@ public sealed class HandheldGpsSystem : EntitySystem SubscribeLocalEvent(OnItemStatus); } - private void OnItemStatus(EntityUid uid, HandheldGPSComponent component, ItemStatusCollectMessage args) + private void OnItemStatus(Entity ent, ref ItemStatusCollectMessage args) { - args.Controls.Add(new HandheldGpsStatusControl(component)); + args.Controls.Add(new HandheldGpsStatusControl(ent)); } } diff --git a/Content.Client/GPS/UI/HandheldGpsStatusControl.cs b/Content.Client/GPS/UI/HandheldGpsStatusControl.cs index 2b703105ea..de6a1031ba 100644 --- a/Content.Client/GPS/UI/HandheldGpsStatusControl.cs +++ b/Content.Client/GPS/UI/HandheldGpsStatusControl.cs @@ -9,12 +9,12 @@ namespace Content.Client.GPS.UI; public sealed class HandheldGpsStatusControl : Control { - private readonly HandheldGPSComponent _parent; + private readonly Entity _parent; private readonly RichTextLabel _label; private float _updateDif; private readonly IEntityManager _entMan; - public HandheldGpsStatusControl(HandheldGPSComponent parent) + public HandheldGpsStatusControl(Entity parent) { _parent = parent; _entMan = IoCManager.Resolve(); @@ -28,10 +28,10 @@ public sealed class HandheldGpsStatusControl : Control base.FrameUpdate(args); _updateDif += args.DeltaSeconds; - if (_updateDif < _parent.UpdateRate) + if (_updateDif < _parent.Comp.UpdateRate) return; - _updateDif -= _parent.UpdateRate; + _updateDif -= _parent.Comp.UpdateRate; UpdateGpsDetails(); } @@ -39,7 +39,7 @@ public sealed class HandheldGpsStatusControl : Control private void UpdateGpsDetails() { var posText = "Error"; - if (_entMan.TryGetComponent(_parent.Owner, out TransformComponent? transComp)) + if (_entMan.TryGetComponent(_parent, out TransformComponent? transComp)) { var pos = transComp.MapPosition; var x = (int) pos.X; diff --git a/Content.Client/Guidebook/Controls/GuideEntityEmbed.xaml.cs b/Content.Client/Guidebook/Controls/GuideEntityEmbed.xaml.cs index 8fd11dc19e..d0b39abb37 100644 --- a/Content.Client/Guidebook/Controls/GuideEntityEmbed.xaml.cs +++ b/Content.Client/Guidebook/Controls/GuideEntityEmbed.xaml.cs @@ -5,7 +5,6 @@ using System.Numerics; using Content.Client.ContextMenu.UI; using Content.Client.Examine; using Content.Client.Guidebook.Richtext; -using Content.Client.Verbs; using Content.Client.Verbs.UI; using Content.Shared.Input; using Content.Shared.Tag; @@ -37,7 +36,9 @@ public sealed partial class GuideEntityEmbed : BoxContainer, IDocumentTag public bool Interactive; - public SpriteComponent? Sprite => View.Sprite; + public Entity? Sprite => View.Entity == null || View.Sprite == null + ? null + : (View.Entity.Value, View.Sprite); public Vector2 Scale { @@ -127,7 +128,7 @@ public sealed partial class GuideEntityEmbed : BoxContainer, IDocumentTag base.Dispose(disposing); if (Sprite is not null) - _entityManager.DeleteEntity(Sprite.Owner); + _entityManager.DeleteEntity(Sprite); } public bool TryParseTag(Dictionary args, [NotNullWhen(true)] out Control? control) diff --git a/Content.Client/Hands/Systems/HandsSystem.cs b/Content.Client/Hands/Systems/HandsSystem.cs index 1189f5a66e..f44bc1ec97 100644 --- a/Content.Client/Hands/Systems/HandsSystem.cs +++ b/Content.Client/Hands/Systems/HandsSystem.cs @@ -1,7 +1,5 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Numerics; -using Content.Client.Animations; using Content.Client.Examine; using Content.Client.Strip; using Content.Client.Verbs.UI; @@ -15,7 +13,6 @@ using Robust.Client.Player; using Robust.Client.UserInterface; using Robust.Shared.Containers; using Robust.Shared.GameStates; -using Robust.Shared.Map; using Robust.Shared.Timing; namespace Content.Client.Hands.Systems @@ -416,21 +413,21 @@ namespace Content.Client.Hands.Systems base.RemoveHand(uid, handName, handsComp); } - private void OnHandActivated(HandsComponent? handsComponent) + private void OnHandActivated(Entity? ent) { - if (handsComponent == null) + if (ent is not { } hand) return; - if (_playerManager.LocalPlayer?.ControlledEntity != handsComponent.Owner) + if (_playerManager.LocalPlayer?.ControlledEntity != hand.Owner) return; - if (handsComponent.ActiveHand == null) + if (hand.Comp.ActiveHand == null) { OnPlayerSetActiveHand?.Invoke(null); return; } - OnPlayerSetActiveHand?.Invoke(handsComponent.ActiveHand.Name); + OnPlayerSetActiveHand?.Invoke(hand.Comp.ActiveHand.Name); } } } diff --git a/Content.Client/HealthOverlay/HealthOverlaySystem.cs b/Content.Client/HealthOverlay/HealthOverlaySystem.cs index 9e1b39aed2..baeb4fe025 100644 --- a/Content.Client/HealthOverlay/HealthOverlaySystem.cs +++ b/Content.Client/HealthOverlay/HealthOverlaySystem.cs @@ -1,4 +1,3 @@ -using System.Collections.Generic; using Content.Client.HealthOverlay.UI; using Content.Shared.Damage; using Content.Shared.GameTicking; @@ -6,8 +5,6 @@ using Content.Shared.Mobs.Components; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Client.Graphics; -using Robust.Shared.GameObjects; -using Robust.Shared.IoC; namespace Content.Client.HealthOverlay { @@ -80,10 +77,9 @@ namespace Content.Client.HealthOverlay var viewBox = _eyeManager.GetWorldViewport().Enlarged(2.0f); - foreach (var (mobState, _) in EntityManager.EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var entity, out var mobState, out _)) { - var entity = mobState.Owner; - if (_entities.GetComponent(ent).MapID != _entities.GetComponent(entity).MapID || !viewBox.Contains(_entities.GetComponent(entity).WorldPosition)) { diff --git a/Content.Client/HealthOverlay/UI/HealthOverlayGui.cs b/Content.Client/HealthOverlay/UI/HealthOverlayGui.cs index 9f0c94acce..e8ec77e540 100644 --- a/Content.Client/HealthOverlay/UI/HealthOverlayGui.cs +++ b/Content.Client/HealthOverlay/UI/HealthOverlayGui.cs @@ -70,7 +70,7 @@ namespace Content.Client.HealthOverlay.UI Panel.Visible = val; } - private void MoreFrameUpdate(FrameEventArgs args) + private void MoreFrameUpdate() { if (_entities.Deleted(Entity)) { @@ -87,7 +87,7 @@ namespace Content.Client.HealthOverlay.UI var mobStateSystem = _entities.EntitySysManager.GetEntitySystem(); var mobThresholdSystem = _entities.EntitySysManager.GetEntitySystem(); - if (mobStateSystem.IsAlive(mobState.Owner, mobState)) + if (mobStateSystem.IsAlive(Entity, mobState)) { if (!mobThresholdSystem.TryGetThresholdForState(Entity,MobState.Critical, out var threshold)) { @@ -101,7 +101,7 @@ namespace Content.Client.HealthOverlay.UI HealthBar.Ratio = 1 - ((FixedPoint2)(damageable.TotalDamage / threshold)).Float(); HealthBar.Visible = true; } - else if (mobStateSystem.IsCritical(mobState.Owner, mobState)) + else if (mobStateSystem.IsCritical(Entity, mobState)) { HealthBar.Ratio = 0; HealthBar.Visible = false; @@ -118,7 +118,7 @@ namespace Content.Client.HealthOverlay.UI ((damageable.TotalDamage - critThreshold) / (deadThreshold - critThreshold)).Value.Float(); } - else if (mobStateSystem.IsDead(mobState.Owner, mobState)) + else if (mobStateSystem.IsDead(Entity, mobState)) { CritBar.Ratio = 0; CritBar.Visible = false; @@ -136,7 +136,7 @@ namespace Content.Client.HealthOverlay.UI { base.FrameUpdate(args); - MoreFrameUpdate(args); + MoreFrameUpdate(); if (_entities.Deleted(Entity) || _eyeManager.CurrentMap != _entities.GetComponent(Entity).MapID) { diff --git a/Content.Client/IconSmoothing/IconSmoothSystem.cs b/Content.Client/IconSmoothing/IconSmoothSystem.cs index 5b931b7232..7334c2fd43 100644 --- a/Content.Client/IconSmoothing/IconSmoothSystem.cs +++ b/Content.Client/IconSmoothing/IconSmoothSystem.cs @@ -236,6 +236,8 @@ namespace Content.Client.IconSmoothing return; } + var spriteEnt = (uid, sprite); + if (xform.Anchored) { if (!_mapManager.TryGetGrid(xform.GridUid, out grid)) @@ -248,13 +250,13 @@ namespace Content.Client.IconSmoothing switch (smooth.Mode) { case IconSmoothingMode.Corners: - CalculateNewSpriteCorners(grid, smooth, sprite, xform, smoothQuery); + CalculateNewSpriteCorners(grid, smooth, spriteEnt, xform, smoothQuery); break; case IconSmoothingMode.CardinalFlags: - CalculateNewSpriteCardinal(grid, smooth, sprite, xform, smoothQuery); + CalculateNewSpriteCardinal(grid, smooth, spriteEnt, xform, smoothQuery); break; case IconSmoothingMode.Diagonal: - CalculateNewSpriteDiagonal(grid, smooth, sprite, xform, smoothQuery); + CalculateNewSpriteDiagonal(grid, smooth, spriteEnt, xform, smoothQuery); break; default: throw new ArgumentOutOfRangeException(); @@ -262,11 +264,11 @@ namespace Content.Client.IconSmoothing } private void CalculateNewSpriteDiagonal(MapGridComponent? grid, IconSmoothComponent smooth, - SpriteComponent sprite, TransformComponent xform, EntityQuery smoothQuery) + Entity sprite, TransformComponent xform, EntityQuery smoothQuery) { if (grid == null) { - sprite.LayerSetState(0, $"{smooth.StateBase}0"); + sprite.Comp.LayerSetState(0, $"{smooth.StateBase}0"); return; } @@ -289,21 +291,21 @@ namespace Content.Client.IconSmoothing if (matching) { - sprite.LayerSetState(0, $"{smooth.StateBase}1"); + sprite.Comp.LayerSetState(0, $"{smooth.StateBase}1"); } else { - sprite.LayerSetState(0, $"{smooth.StateBase}0"); + sprite.Comp.LayerSetState(0, $"{smooth.StateBase}0"); } } - private void CalculateNewSpriteCardinal(MapGridComponent? grid, IconSmoothComponent smooth, SpriteComponent sprite, TransformComponent xform, EntityQuery smoothQuery) + private void CalculateNewSpriteCardinal(MapGridComponent? grid, IconSmoothComponent smooth, Entity sprite, TransformComponent xform, EntityQuery smoothQuery) { var dirs = CardinalConnectDirs.None; if (grid == null) { - sprite.LayerSetState(0, $"{smooth.StateBase}{(int) dirs}"); + sprite.Comp.LayerSetState(0, $"{smooth.StateBase}{(int) dirs}"); return; } @@ -317,7 +319,7 @@ namespace Content.Client.IconSmoothing if (MatchingEntity(smooth, grid.GetAnchoredEntitiesEnumerator(pos.Offset(Direction.West)), smoothQuery)) dirs |= CardinalConnectDirs.West; - sprite.LayerSetState(0, $"{smooth.StateBase}{(int) dirs}"); + sprite.Comp.LayerSetState(0, $"{smooth.StateBase}{(int) dirs}"); var directions = DirectionFlag.None; @@ -330,7 +332,7 @@ namespace Content.Client.IconSmoothing if ((dirs & CardinalConnectDirs.West) != 0x0) directions |= DirectionFlag.West; - CalculateEdge(sprite.Owner, directions, sprite); + CalculateEdge(sprite, directions, sprite); } private bool MatchingEntity(IconSmoothComponent smooth, AnchoredEntitiesEnumerator candidates, EntityQuery smoothQuery) @@ -348,7 +350,7 @@ namespace Content.Client.IconSmoothing return false; } - private void CalculateNewSpriteCorners(MapGridComponent? grid, IconSmoothComponent smooth, SpriteComponent sprite, TransformComponent xform, EntityQuery smoothQuery) + private void CalculateNewSpriteCorners(MapGridComponent? grid, IconSmoothComponent smooth, Entity spriteEnt, TransformComponent xform, EntityQuery smoothQuery) { var (cornerNE, cornerNW, cornerSW, cornerSE) = grid == null ? (CornerFill.None, CornerFill.None, CornerFill.None, CornerFill.None) @@ -359,6 +361,7 @@ namespace Content.Client.IconSmoothing // It will also result in 4-8 sprite update events being raised when it only needs to be 1-2. // At the very least each event currently only queues a sprite for updating. // Oh god sprite component is a mess. + var sprite = spriteEnt.Comp; sprite.LayerSetState(CornerLayers.NE, $"{smooth.StateBase}{(int) cornerNE}"); sprite.LayerSetState(CornerLayers.SE, $"{smooth.StateBase}{(int) cornerSE}"); sprite.LayerSetState(CornerLayers.SW, $"{smooth.StateBase}{(int) cornerSW}"); @@ -378,7 +381,7 @@ namespace Content.Client.IconSmoothing if ((cornerNW & cornerSW) != CornerFill.None) directions |= DirectionFlag.West; - CalculateEdge(sprite.Owner, directions, sprite); + CalculateEdge(spriteEnt, directions, sprite); } private (CornerFill ne, CornerFill nw, CornerFill sw, CornerFill se) CalculateCornerFill(MapGridComponent grid, IconSmoothComponent smooth, TransformComponent xform, EntityQuery smoothQuery) diff --git a/Content.Client/Interactable/Components/InteractionOutlineComponent.cs b/Content.Client/Interactable/Components/InteractionOutlineComponent.cs index 9c72d763ff..9803920257 100644 --- a/Content.Client/Interactable/Components/InteractionOutlineComponent.cs +++ b/Content.Client/Interactable/Components/InteractionOutlineComponent.cs @@ -22,11 +22,11 @@ namespace Content.Client.Interactable.Components private ShaderInstance? _shader; private int _lastRenderScale; - public void OnMouseEnter(bool inInteractionRange, int renderScale) + public void OnMouseEnter(EntityUid uid, bool inInteractionRange, int renderScale) { _lastRenderScale = renderScale; _inRange = inInteractionRange; - if (_entMan.TryGetComponent(Owner, out SpriteComponent? sprite) && sprite.PostShader == null) + if (_entMan.TryGetComponent(uid, out SpriteComponent? sprite) && sprite.PostShader == null) { // TODO why is this creating a new instance of the outline shader every time the mouse enters??? _shader = MakeNewShader(inInteractionRange, renderScale); @@ -34,9 +34,9 @@ namespace Content.Client.Interactable.Components } } - public void OnMouseLeave() + public void OnMouseLeave(EntityUid uid) { - if (_entMan.TryGetComponent(Owner, out SpriteComponent? sprite)) + if (_entMan.TryGetComponent(uid, out SpriteComponent? sprite)) { if (sprite.PostShader == _shader) sprite.PostShader = null; @@ -47,9 +47,9 @@ namespace Content.Client.Interactable.Components _shader = null; } - public void UpdateInRange(bool inInteractionRange, int renderScale) + public void UpdateInRange(EntityUid uid, bool inInteractionRange, int renderScale) { - if (_entMan.TryGetComponent(Owner, out SpriteComponent? sprite) + if (_entMan.TryGetComponent(uid, out SpriteComponent? sprite) && sprite.PostShader == _shader && (inInteractionRange != _inRange || _lastRenderScale != renderScale)) { diff --git a/Content.Client/Inventory/ClientInventorySystem.cs b/Content.Client/Inventory/ClientInventorySystem.cs index d6a487f3fd..ffff392aa4 100644 --- a/Content.Client/Inventory/ClientInventorySystem.cs +++ b/Content.Client/Inventory/ClientInventorySystem.cs @@ -107,7 +107,7 @@ namespace Content.Client.Inventory private void OnShutdown(EntityUid uid, InventoryComponent component, ComponentShutdown args) { - if (component.Owner != _playerManager.LocalPlayer?.ControlledEntity) + if (uid != _playerManager.LocalPlayer?.ControlledEntity) return; OnUnlinkInventory?.Invoke(); diff --git a/Content.Client/Light/Components/LightBehaviourComponent.cs b/Content.Client/Light/Components/LightBehaviourComponent.cs index 282df5c829..7e8bf82a29 100644 --- a/Content.Client/Light/Components/LightBehaviourComponent.cs +++ b/Content.Client/Light/Components/LightBehaviourComponent.cs @@ -408,9 +408,9 @@ namespace Content.Client.Light.Components /// /// If we disable all the light behaviours we want to be able to revert the light to its original state. /// - private void CopyLightSettings(string property) + private void CopyLightSettings(EntityUid uid, string property) { - if (_entMan.TryGetComponent(Owner, out PointLightComponent? light)) + if (_entMan.TryGetComponent(uid, out PointLightComponent? light)) { var propertyValue = AnimationHelper.GetAnimatableProperty(light, property); if (propertyValue != null) @@ -420,7 +420,7 @@ namespace Content.Client.Light.Components } else { - Logger.Warning($"{_entMan.GetComponent(Owner).EntityName} has a {nameof(LightBehaviourComponent)} but it has no {nameof(PointLightComponent)}! Check the prototype!"); + Logger.Warning($"{_entMan.GetComponent(uid).EntityName} has a {nameof(LightBehaviourComponent)} but it has no {nameof(PointLightComponent)}! Check the prototype!"); } } @@ -445,7 +445,7 @@ namespace Content.Client.Light.Components { if (!animations.HasRunningAnimation(uid, animation, KeyPrefix + container.Key)) { - CopyLightSettings(container.LightBehaviour.Property); + CopyLightSettings(uid, container.LightBehaviour.Property); container.LightBehaviour.UpdatePlaybackValues(container.Animation); animations.Play(uid, animation, container.Animation, KeyPrefix + container.Key); } diff --git a/Content.Client/Light/RgbLightControllerSystem.cs b/Content.Client/Light/RgbLightControllerSystem.cs index a9ba34ca7d..ad8ca47582 100644 --- a/Content.Client/Light/RgbLightControllerSystem.cs +++ b/Content.Client/Light/RgbLightControllerSystem.cs @@ -170,11 +170,12 @@ namespace Content.Client.Light public override void FrameUpdate(float frameTime) { - foreach (var (rgb, light, sprite) in EntityManager.EntityQuery()) + var lightQuery = EntityQueryEnumerator(); + while (lightQuery.MoveNext(out var uid, out var rgb, out var light, out var sprite)) { - var color = GetCurrentRgbColor(_gameTiming.RealTime, rgb.CreationTick.Value * _gameTiming.TickPeriod, rgb); + var color = GetCurrentRgbColor(_gameTiming.RealTime, rgb.CreationTick.Value * _gameTiming.TickPeriod, (uid, rgb)); - _lights.SetColor(light.Owner, color, light); + _lights.SetColor(uid, color, light); if (rgb.Layers != null) { @@ -196,17 +197,18 @@ namespace Content.Client.Light } } - foreach (var (map, rgb) in EntityQuery()) + var mapQuery = EntityQueryEnumerator(); + while (mapQuery.MoveNext(out var uid, out var map, out var rgb)) { - var color = GetCurrentRgbColor(_gameTiming.RealTime, rgb.CreationTick.Value * _gameTiming.TickPeriod, rgb); + var color = GetCurrentRgbColor(_gameTiming.RealTime, rgb.CreationTick.Value * _gameTiming.TickPeriod, (uid, rgb)); map.AmbientLightColor = color; } } - public static Color GetCurrentRgbColor(TimeSpan curTime, TimeSpan offset, RgbLightControllerComponent rgb) + public static Color GetCurrentRgbColor(TimeSpan curTime, TimeSpan offset, Entity rgb) { return Color.FromHsv(new Vector4( - (float) (((curTime.TotalSeconds - offset.TotalSeconds) * rgb.CycleRate + Math.Abs(rgb.Owner.Id * 0.1)) % 1), + (float) (((curTime.TotalSeconds - offset.TotalSeconds) * rgb.Comp.CycleRate + Math.Abs(rgb.Owner.Id * 0.1)) % 1), 1.0f, 1.0f, 1.0f diff --git a/Content.Client/NPC/NPCSteeringSystem.cs b/Content.Client/NPC/NPCSteeringSystem.cs index 271632d018..bb2145bce0 100644 --- a/Content.Client/NPC/NPCSteeringSystem.cs +++ b/Content.Client/NPC/NPCSteeringSystem.cs @@ -38,9 +38,10 @@ public sealed class NPCSteeringSystem : SharedNPCSteeringSystem Enabled = false }); - foreach (var comp in EntityQuery(true)) + var query = AllEntityQuery(); + while (query.MoveNext(out var uid, out var npc)) { - RemCompDeferred(comp.Owner); + RemCompDeferred(uid); } } } diff --git a/Content.Client/NPC/PathfindingSystem.cs b/Content.Client/NPC/PathfindingSystem.cs index 518c1f32aa..548edd601c 100644 --- a/Content.Client/NPC/PathfindingSystem.cs +++ b/Content.Client/NPC/PathfindingSystem.cs @@ -2,11 +2,13 @@ using System.Linq; using System.Numerics; using System.Text; using Content.Shared.NPC; +using Robust.Client.GameObjects; using Robust.Client.Graphics; using Robust.Client.Input; using Robust.Client.ResourceManagement; using Robust.Shared.Enums; using Robust.Shared.Map; +using Robust.Shared.Map.Components; using Robust.Shared.Timing; using Robust.Shared.Utility; @@ -20,6 +22,7 @@ namespace Content.Client.NPC [Dependency] private readonly IMapManager _mapManager = default!; [Dependency] private readonly IResourceCache _cache = default!; [Dependency] private readonly NPCSteeringSystem _steering = default!; + [Dependency] private readonly MapSystem _mapSystem = default!; public PathfindingDebugMode Modes { @@ -36,7 +39,7 @@ namespace Content.Client.NPC } else if (!overlayManager.HasOverlay()) { - overlayManager.AddOverlay(new PathfindingOverlay(EntityManager, _eyeManager, _inputManager, _mapManager, _cache, this)); + overlayManager.AddOverlay(new PathfindingOverlay(EntityManager, _eyeManager, _inputManager, _mapManager, _cache, this, _mapSystem)); } if ((value & PathfindingDebugMode.Steering) != 0x0) @@ -136,10 +139,12 @@ namespace Content.Client.NPC private readonly IInputManager _inputManager; private readonly IMapManager _mapManager; private readonly PathfindingSystem _system; + private readonly MapSystem _mapSystem; public override OverlaySpace Space => OverlaySpace.ScreenSpace | OverlaySpace.WorldSpace; private readonly Font _font; + private List> _grids = new(); public PathfindingOverlay( IEntityManager entManager, @@ -147,13 +152,15 @@ namespace Content.Client.NPC IInputManager inputManager, IMapManager mapManager, IResourceCache cache, - PathfindingSystem system) + PathfindingSystem system, + MapSystem mapSystem) { _entManager = entManager; _eyeManager = eyeManager; _inputManager = inputManager; _mapManager = mapManager; _system = system; + _mapSystem = mapSystem; _font = new VectorFont(cache.GetResource("/Fonts/NotoSans/NotoSans-Regular.ttf"), 10); } @@ -182,11 +189,14 @@ namespace Content.Client.NPC { var found = false; - foreach (var grid in _mapManager.FindGridsIntersecting(mouseWorldPos.MapId, aabb)) + _grids.Clear(); + _mapManager.FindGridsIntersecting(mouseWorldPos.MapId, aabb, ref _grids); + + foreach (var grid in _grids) { - var netGrid = _entManager.GetNetEntity(grid.Owner); + var netGrid = _entManager.GetNetEntity(grid); - if (found || !_system.Breadcrumbs.TryGetValue(netGrid, out var crumbs) || !xformQuery.TryGetComponent(grid.Owner, out var gridXform)) + if (found || !_system.Breadcrumbs.TryGetValue(netGrid, out var crumbs) || !xformQuery.TryGetComponent(grid, out var gridXform)) continue; var (_, _, worldMatrix, invWorldMatrix) = gridXform.GetWorldPositionRotationMatrixWithInv(); @@ -262,7 +272,7 @@ namespace Content.Client.NPC if (!_system.Polys.TryGetValue(_entManager.GetNetEntity(gridUid), out var data)) return; - var tileRef = grid.GetTileRef(mouseWorldPos); + var tileRef = _mapSystem.GetTileRef(gridUid, grid, mouseWorldPos); var localPos = tileRef.GridIndices; var chunkOrigin = localPos / SharedPathfindingSystem.ChunkSize; @@ -333,12 +343,15 @@ namespace Content.Client.NPC if ((_system.Modes & PathfindingDebugMode.Breadcrumbs) != 0x0 && mouseWorldPos.MapId == args.MapId) { - foreach (var grid in _mapManager.FindGridsIntersecting(mouseWorldPos.MapId, aabb)) + _grids.Clear(); + _mapManager.FindGridsIntersecting(mouseWorldPos.MapId, aabb, ref _grids); + + foreach (var grid in _grids) { - var netGrid = _entManager.GetNetEntity(grid.Owner); + var netGrid = _entManager.GetNetEntity(grid); if (!_system.Breadcrumbs.TryGetValue(netGrid, out var crumbs) || - !xformQuery.TryGetComponent(grid.Owner, out var gridXform)) + !xformQuery.TryGetComponent(grid, out var gridXform)) { continue; } @@ -392,12 +405,15 @@ namespace Content.Client.NPC if ((_system.Modes & PathfindingDebugMode.Polys) != 0x0 && mouseWorldPos.MapId == args.MapId) { - foreach (var grid in _mapManager.FindGridsIntersecting(args.MapId, aabb)) + _grids.Clear(); + _mapManager.FindGridsIntersecting(args.MapId, aabb, ref _grids); + + foreach (var grid in _grids) { - var netGrid = _entManager.GetNetEntity(grid.Owner); + var netGrid = _entManager.GetNetEntity(grid); if (!_system.Polys.TryGetValue(netGrid, out var data) || - !xformQuery.TryGetComponent(grid.Owner, out var gridXform)) + !xformQuery.TryGetComponent(grid, out var gridXform)) continue; var (_, _, worldMatrix, invWorldMatrix) = gridXform.GetWorldPositionRotationMatrixWithInv(); @@ -428,12 +444,15 @@ namespace Content.Client.NPC if ((_system.Modes & PathfindingDebugMode.PolyNeighbors) != 0x0 && mouseWorldPos.MapId == args.MapId) { - foreach (var grid in _mapManager.FindGridsIntersecting(args.MapId, aabb)) + _grids.Clear(); + _mapManager.FindGridsIntersecting(args.MapId, aabb, ref _grids); + + foreach (var grid in _grids) { - var netGrid = _entManager.GetNetEntity(grid.Owner); + var netGrid = _entManager.GetNetEntity(grid); if (!_system.Polys.TryGetValue(netGrid, out var data) || - !xformQuery.TryGetComponent(grid.Owner, out var gridXform)) + !xformQuery.TryGetComponent(grid, out var gridXform)) continue; var (_, _, worldMatrix, invMatrix) = gridXform.GetWorldPositionRotationMatrixWithInv(); @@ -484,12 +503,15 @@ namespace Content.Client.NPC if ((_system.Modes & PathfindingDebugMode.Chunks) != 0x0) { - foreach (var grid in _mapManager.FindGridsIntersecting(args.MapId, args.WorldBounds)) + _grids.Clear(); + _mapManager.FindGridsIntersecting(args.MapId, args.WorldBounds, ref _grids); + + foreach (var grid in _grids) { - var netGrid = _entManager.GetNetEntity(grid.Owner); + var netGrid = _entManager.GetNetEntity(grid); if (!_system.Breadcrumbs.TryGetValue(netGrid, out var crumbs) || - !xformQuery.TryGetComponent(grid.Owner, out var gridXform)) + !xformQuery.TryGetComponent(grid, out var gridXform)) continue; var (_, _, worldMatrix, invWorldMatrix) = gridXform.GetWorldPositionRotationMatrixWithInv(); diff --git a/Content.Client/NetworkConfigurator/NetworkConfiguratorLinkOverlay.cs b/Content.Client/NetworkConfigurator/NetworkConfiguratorLinkOverlay.cs index ca135f6ca2..4fcdada868 100644 --- a/Content.Client/NetworkConfigurator/NetworkConfiguratorLinkOverlay.cs +++ b/Content.Client/NetworkConfigurator/NetworkConfiguratorLinkOverlay.cs @@ -1,10 +1,9 @@ using Content.Client.NetworkConfigurator.Systems; -using Content.Shared.DeviceNetwork; using Content.Shared.DeviceNetwork.Components; using Robust.Client.Graphics; using Robust.Shared.Enums; -using Robust.Shared.Random; using Robust.Shared.Map; +using Robust.Shared.Random; namespace Content.Client.NetworkConfigurator; @@ -28,24 +27,25 @@ public sealed class NetworkConfiguratorLinkOverlay : Overlay protected override void Draw(in OverlayDrawArgs args) { - foreach (var tracker in _entityManager.EntityQuery()) + var query = _entityManager.EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out _)) { - if (_entityManager.Deleted(tracker.Owner) || !_entityManager.TryGetComponent(tracker.Owner, out DeviceListComponent? deviceList)) + if (_entityManager.Deleted(uid) || !_entityManager.TryGetComponent(uid, out DeviceListComponent? deviceList)) { - _entityManager.RemoveComponentDeferred(tracker.Owner); + _entityManager.RemoveComponentDeferred(uid); continue; } - if (!Colors.TryGetValue(tracker.Owner, out var color)) + if (!Colors.TryGetValue(uid, out var color)) { color = new Color( _random.Next(0, 255), _random.Next(0, 255), _random.Next(0, 255)); - Colors.Add(tracker.Owner, color); + Colors.Add(uid, color); } - var sourceTransform = _entityManager.GetComponent(tracker.Owner); + var sourceTransform = _entityManager.GetComponent(uid); if (sourceTransform.MapID == MapId.Nullspace) { // Can happen if the item is outside the client's view. In that case, @@ -53,7 +53,7 @@ public sealed class NetworkConfiguratorLinkOverlay : Overlay continue; } - foreach (var device in _deviceListSystem.GetAllDevices(tracker.Owner, deviceList)) + foreach (var device in _deviceListSystem.GetAllDevices(uid, deviceList)) { if (_entityManager.Deleted(device)) { @@ -66,7 +66,7 @@ public sealed class NetworkConfiguratorLinkOverlay : Overlay continue; } - args.WorldHandle.DrawLine(sourceTransform.WorldPosition, linkTransform.WorldPosition, Colors[tracker.Owner]); + args.WorldHandle.DrawLine(sourceTransform.WorldPosition, linkTransform.WorldPosition, Colors[uid]); } } } diff --git a/Content.Client/NetworkConfigurator/Systems/NetworkConfiguratorSystem.cs b/Content.Client/NetworkConfigurator/Systems/NetworkConfiguratorSystem.cs index af1861dc47..7bd13a12b2 100644 --- a/Content.Client/NetworkConfigurator/Systems/NetworkConfiguratorSystem.cs +++ b/Content.Client/NetworkConfigurator/Systems/NetworkConfiguratorSystem.cs @@ -1,9 +1,7 @@ -using System.Linq; using Content.Client.Actions; using Content.Client.Items; using Content.Client.Message; using Content.Client.Stylesheets; -using Content.Shared.Actions; using Content.Shared.DeviceNetwork.Components; using Content.Shared.DeviceNetwork.Systems; using Content.Shared.Input; @@ -94,9 +92,10 @@ public sealed class NetworkConfiguratorSystem : SharedNetworkConfiguratorSystem return; } - foreach (var tracker in EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out _)) { - RemCompDeferred(tracker.Owner); + RemCompDeferred(uid); } _actions.RemoveAction(overlay.Action); diff --git a/Content.Client/NodeContainer/NodeVisualizationOverlay.cs b/Content.Client/NodeContainer/NodeVisualizationOverlay.cs index 85198f01d0..f10eb9ed8b 100644 --- a/Content.Client/NodeContainer/NodeVisualizationOverlay.cs +++ b/Content.Client/NodeContainer/NodeVisualizationOverlay.cs @@ -6,6 +6,7 @@ using Robust.Client.Input; using Robust.Client.ResourceManagement; using Robust.Shared.Enums; using Robust.Shared.Map; +using Robust.Shared.Map.Components; using Robust.Shared.Timing; using Robust.Shared.Utility; using static Content.Shared.NodeContainer.NodeVis; @@ -22,6 +23,7 @@ namespace Content.Client.NodeContainer private readonly Dictionary<(int, int), NodeRenderData> _nodeIndex = new(); private readonly Dictionary>> _gridIndex = new (); + private List> _grids = new(); private readonly Font _font; @@ -112,21 +114,24 @@ namespace Content.Client.NodeContainer var worldAABB = overlayDrawArgs.WorldAABB; var xformQuery = _entityManager.GetEntityQuery(); - foreach (var grid in _mapManager.FindGridsIntersecting(map, worldAABB)) + _grids.Clear(); + _mapManager.FindGridsIntersecting(map, worldAABB, ref _grids); + + foreach (var grid in _grids) { - foreach (var entity in _lookup.GetEntitiesIntersecting(grid.Owner, worldAABB)) + foreach (var entity in _lookup.GetEntitiesIntersecting(grid, worldAABB)) { if (!_system.Entities.TryGetValue(entity, out var nodeData)) continue; - var gridDict = _gridIndex.GetOrNew(grid.Owner); + var gridDict = _gridIndex.GetOrNew(grid); var coords = xformQuery.GetComponent(entity).Coordinates; // TODO: This probably shouldn't be capable of returning NaN... if (float.IsNaN(coords.Position.X) || float.IsNaN(coords.Position.Y)) continue; - var tile = gridDict.GetOrNew(grid.TileIndicesFor(coords)); + var tile = gridDict.GetOrNew(grid.Comp.TileIndicesFor(coords)); foreach (var (group, nodeDatum) in nodeData) { @@ -141,7 +146,7 @@ namespace Content.Client.NodeContainer foreach (var (gridId, gridDict) in _gridIndex) { var grid = _mapManager.GetGrid(gridId); - var (_, _, worldMatrix, invMatrix) = _entityManager.GetComponent(grid.Owner).GetWorldPositionRotationMatrixWithInv(); + var (_, _, worldMatrix, invMatrix) = _entityManager.GetComponent(gridId).GetWorldPositionRotationMatrixWithInv(); var lCursorBox = invMatrix.TransformBox(cursorBox); foreach (var (pos, list) in gridDict) diff --git a/Content.Client/Outline/InteractionOutlineSystem.cs b/Content.Client/Outline/InteractionOutlineSystem.cs index ce1945ed03..bb341785d0 100644 --- a/Content.Client/Outline/InteractionOutlineSystem.cs +++ b/Content.Client/Outline/InteractionOutlineSystem.cs @@ -64,7 +64,7 @@ public sealed class InteractionOutlineSystem : EntitySystem return; if (TryComp(_lastHoveredEntity, out InteractionOutlineComponent? outline)) - outline.OnMouseLeave(); + outline.OnMouseLeave(_lastHoveredEntity.Value); } public void SetEnabled(bool enabled) @@ -83,7 +83,7 @@ public sealed class InteractionOutlineSystem : EntitySystem return; if (TryComp(_lastHoveredEntity, out InteractionOutlineComponent? outline)) - outline.OnMouseLeave(); + outline.OnMouseLeave(_lastHoveredEntity.Value); } public override void FrameUpdate(float frameTime) @@ -146,7 +146,7 @@ public sealed class InteractionOutlineSystem : EntitySystem { if (entityToClick != null && TryComp(entityToClick, out outline)) { - outline.UpdateInRange(inRange, renderScale); + outline.UpdateInRange(entityToClick.Value, inRange, renderScale); } return; @@ -155,14 +155,14 @@ public sealed class InteractionOutlineSystem : EntitySystem if (_lastHoveredEntity != null && !Deleted(_lastHoveredEntity) && TryComp(_lastHoveredEntity, out outline)) { - outline.OnMouseLeave(); + outline.OnMouseLeave(_lastHoveredEntity.Value); } _lastHoveredEntity = entityToClick; if (_lastHoveredEntity != null && TryComp(_lastHoveredEntity, out outline)) { - outline.OnMouseEnter(inRange, renderScale); + outline.OnMouseEnter(_lastHoveredEntity.Value, inRange, renderScale); } } } diff --git a/Content.Client/Pinpointer/NavMapSystem.cs b/Content.Client/Pinpointer/NavMapSystem.cs index 35b0a32b56..d346d90904 100644 --- a/Content.Client/Pinpointer/NavMapSystem.cs +++ b/Content.Client/Pinpointer/NavMapSystem.cs @@ -4,6 +4,7 @@ using Robust.Client.Graphics; using Robust.Shared.Enums; using Robust.Shared.GameStates; using Robust.Shared.Map; +using Robust.Shared.Map.Components; namespace Content.Client.Pinpointer; @@ -42,6 +43,8 @@ public sealed class NavMapOverlay : Overlay public override OverlaySpace Space => OverlaySpace.WorldSpace; + private List> _grids = new(); + public NavMapOverlay(IEntityManager entManager, IMapManager mapManager) { _entManager = entManager; @@ -54,9 +57,12 @@ public sealed class NavMapOverlay : Overlay var xformQuery = _entManager.GetEntityQuery(); var scale = Matrix3.CreateScale(new Vector2(1f, 1f)); - foreach (var grid in _mapManager.FindGridsIntersecting(args.MapId, args.WorldBounds)) + _grids.Clear(); + _mapManager.FindGridsIntersecting(args.MapId, args.WorldBounds, ref _grids); + + foreach (var grid in _grids) { - if (!query.TryGetComponent(grid.Owner, out var navMap) || !xformQuery.TryGetComponent(grid.Owner, out var xform)) + if (!query.TryGetComponent(grid, out var navMap) || !xformQuery.TryGetComponent(grid.Owner, out var xform)) continue; // TODO: Faster helper method @@ -67,9 +73,9 @@ public sealed class NavMapOverlay : Overlay args.WorldHandle.SetTransform(matty); - for (var x = Math.Floor(localAABB.Left); x <= Math.Ceiling(localAABB.Right); x += SharedNavMapSystem.ChunkSize * grid.TileSize) + for (var x = Math.Floor(localAABB.Left); x <= Math.Ceiling(localAABB.Right); x += SharedNavMapSystem.ChunkSize * grid.Comp.TileSize) { - for (var y = Math.Floor(localAABB.Bottom); y <= Math.Ceiling(localAABB.Top); y += SharedNavMapSystem.ChunkSize * grid.TileSize) + for (var y = Math.Floor(localAABB.Bottom); y <= Math.Ceiling(localAABB.Top); y += SharedNavMapSystem.ChunkSize * grid.Comp.TileSize) { var floored = new Vector2i((int) x, (int) y); @@ -89,7 +95,7 @@ public sealed class NavMapOverlay : Overlay continue; var tile = chunk.Origin * SharedNavMapSystem.ChunkSize + SharedNavMapSystem.GetTile(mask); - args.WorldHandle.DrawRect(new Box2(tile * grid.TileSize, (tile + 1) * grid.TileSize), Color.Aqua, false); + args.WorldHandle.DrawRect(new Box2(tile * grid.Comp.TileSize, (tile + 1) * grid.Comp.TileSize), Color.Aqua, false); } } } diff --git a/Content.Client/Radiation/Overlays/RadiationPulseOverlay.cs b/Content.Client/Radiation/Overlays/RadiationPulseOverlay.cs index b10025f56f..adc535b268 100644 --- a/Content.Client/Radiation/Overlays/RadiationPulseOverlay.cs +++ b/Content.Client/Radiation/Overlays/RadiationPulseOverlay.cs @@ -1,4 +1,3 @@ -using System.Linq; using System.Numerics; using Content.Shared.Radiation.Components; using Robust.Client.Graphics; @@ -81,11 +80,10 @@ namespace Content.Client.Radiation.Overlays var currentEyeLoc = currentEye.Position; - var pulses = _entityManager.EntityQuery(); - foreach (var pulse in pulses) //Add all pulses that are not added yet but qualify + var pulses = _entityManager.EntityQueryEnumerator(); + //Add all pulses that are not added yet but qualify + while (pulses.MoveNext(out var pulseEntity, out var pulse)) { - var pulseEntity = pulse.Owner; - if (!_pulses.ContainsKey(pulseEntity) && PulseQualifies(pulseEntity, currentEyeLoc)) { _pulses.Add( diff --git a/Content.Client/Replay/Spectator/ReplaySpectatorSystem.Position.cs b/Content.Client/Replay/Spectator/ReplaySpectatorSystem.Position.cs index 66768e9fda..427ed039e1 100644 --- a/Content.Client/Replay/Spectator/ReplaySpectatorSystem.Position.cs +++ b/Content.Client/Replay/Spectator/ReplaySpectatorSystem.Position.cs @@ -1,4 +1,3 @@ -using System.Linq; using Content.Shared.Movement.Components; using Robust.Client.GameObjects; using Robust.Shared.Map; @@ -134,9 +133,20 @@ public sealed partial class ReplaySpectatorSystem return true; } - var uid = EntityQuery().MaxBy(x => x.LocalAABB.Size.LengthSquared())?.Owner; - coords = new EntityCoordinates(uid ?? default, default); - return uid != null; + Entity? maxUid = null; + float? maxSize = null; + while (EntityQueryEnumerator().MoveNext(out var uid, out var grid)) + { + var size = grid.LocalAABB.Size.LengthSquared(); + if (maxSize == null || size > maxSize) + { + maxUid = (uid, grid); + maxSize = size; + } + } + + coords = new EntityCoordinates(maxUid ?? default, default); + return maxUid != null; } private void OnTerminating(EntityUid uid, ReplaySpectatorComponent component, ref EntityTerminatingEvent args) diff --git a/Content.Client/Revenant/RevenantOverloadedLightsSystem.cs b/Content.Client/Revenant/RevenantOverloadedLightsSystem.cs index 9fd4e4f068..3f3f3d876c 100644 --- a/Content.Client/Revenant/RevenantOverloadedLightsSystem.cs +++ b/Content.Client/Revenant/RevenantOverloadedLightsSystem.cs @@ -55,7 +55,7 @@ public sealed class RevenantOverloadedLightsSystem : SharedRevenantOverloadedLig Dirty(uid, light); } - protected override void OnZap(RevenantOverloadedLightsComponent component) + protected override void OnZap(Entity component) { } diff --git a/Content.Client/Rotation/RotationVisualizerSystem.cs b/Content.Client/Rotation/RotationVisualizerSystem.cs index 106bd79711..177c149faa 100644 --- a/Content.Client/Rotation/RotationVisualizerSystem.cs +++ b/Content.Client/Rotation/RotationVisualizerSystem.cs @@ -77,6 +77,6 @@ public sealed class RotationVisualizerSystem : VisualizerSystem public Dictionary> Docks = new(); + private List> _grids = new(); + public DockingControl() { _entManager = IoCManager.Resolve(); @@ -147,17 +150,19 @@ public class DockingControl : Control // TODO: Getting some overdraw so need to fix that. var xformQuery = _entManager.GetEntityQuery(); - foreach (var grid in _mapManager.FindGridsIntersecting(gridXform.MapID, - new Box2(worldPos - RangeVector, worldPos + RangeVector))) + _grids.Clear(); + _mapManager.FindGridsIntersecting(gridXform.MapID, new Box2(worldPos - RangeVector, worldPos + RangeVector)); + + foreach (var grid in _grids) { if (grid.Owner == GridEntity) continue; // Draw the fixtures before drawing any docks in range. - if (!_entManager.TryGetComponent(grid.Owner, out var gridFixtures)) + if (!_entManager.TryGetComponent(grid, out var gridFixtures)) continue; - var gridMatrix = xformQuery.GetComponent(grid.Owner).WorldMatrix; + var gridMatrix = xformQuery.GetComponent(grid).WorldMatrix; Matrix3.Multiply(in gridMatrix, in invMatrix, out var matty); @@ -204,7 +209,7 @@ public class DockingControl : Control } // Draw any docks on that grid - if (Docks.TryGetValue(_entManager.GetNetEntity(grid.Owner), out var gridDocks)) + if (Docks.TryGetValue(_entManager.GetNetEntity(grid), out var gridDocks)) { foreach (var dock in gridDocks) { diff --git a/Content.Client/Shuttles/UI/RadarControl.cs b/Content.Client/Shuttles/UI/RadarControl.cs index fa411ca9ba..764fb854a7 100644 --- a/Content.Client/Shuttles/UI/RadarControl.cs +++ b/Content.Client/Shuttles/UI/RadarControl.cs @@ -3,9 +3,7 @@ using Content.Client.UserInterface.Controls; using Content.Shared.Shuttles.BUIStates; using Content.Shared.Shuttles.Components; using JetBrains.Annotations; -using Content.Shared.Shuttles.Systems; using Robust.Client.Graphics; -using Robust.Client.Input; using Robust.Client.UserInterface; using Robust.Client.UserInterface.Controls; using Robust.Shared.Collections; @@ -13,7 +11,6 @@ using Robust.Shared.Input; using Robust.Shared.Map; using Robust.Shared.Map.Components; using Robust.Shared.Physics; -using Robust.Shared.Physics.Collision.Shapes; using Robust.Shared.Physics.Components; using Robust.Shared.Utility; @@ -57,6 +54,8 @@ public sealed class RadarControl : MapGridControl /// public Action? OnRadarClick; + private List> _grids = new(); + public RadarControl() : base(64f, 256f, 256f) { _transform = _entManager.System(); @@ -198,9 +197,11 @@ public sealed class RadarControl : MapGridControl var shown = new HashSet(); + _grids.Clear(); + _mapManager.FindGridsIntersecting(xform.MapID, new Box2(pos - MaxRadarRangeVector, pos + MaxRadarRangeVector), ref _grids); + // Draw other grids... differently - foreach (var grid in _mapManager.FindGridsIntersecting(xform.MapID, - new Box2(pos - MaxRadarRangeVector, pos + MaxRadarRangeVector))) + foreach (var grid in _grids) { var gUid = grid.Owner; if (gUid == ourGridId || !fixturesQuery.HasComponent(gUid)) @@ -240,7 +241,7 @@ public sealed class RadarControl : MapGridControl (iff == null && IFFComponent.ShowIFFDefault || (iff.Flags & IFFFlags.HideLabel) == 0x0)) { - var gridBounds = grid.LocalAABB; + var gridBounds = grid.Comp.LocalAABB; Label label; if (!_iffControls.TryGetValue(gUid, out var control)) diff --git a/Content.Client/Sprite/SpriteFadeSystem.cs b/Content.Client/Sprite/SpriteFadeSystem.cs index f6a94e6db1..d4ed1285a8 100644 --- a/Content.Client/Sprite/SpriteFadeSystem.cs +++ b/Content.Client/Sprite/SpriteFadeSystem.cs @@ -77,12 +77,13 @@ public sealed class SpriteFadeSystem : EntitySystem } } - foreach (var comp in EntityQuery(true)) + var query = AllEntityQuery(); + while (query.MoveNext(out var uid, out var comp)) { if (_comps.Contains(comp)) continue; - if (!spriteQuery.TryGetComponent(comp.Owner, out var sprite)) + if (!spriteQuery.TryGetComponent(uid, out var sprite)) continue; var newColor = Math.Min(sprite.Color.A + change, comp.OriginalAlpha); @@ -93,7 +94,7 @@ public sealed class SpriteFadeSystem : EntitySystem } else { - RemCompDeferred(comp.Owner); + RemCompDeferred(uid); } } diff --git a/Content.Client/Storage/Systems/ItemMapperSystem.cs b/Content.Client/Storage/Systems/ItemMapperSystem.cs index 71c1c5b3be..79fbc96491 100644 --- a/Content.Client/Storage/Systems/ItemMapperSystem.cs +++ b/Content.Client/Storage/Systems/ItemMapperSystem.cs @@ -21,26 +21,27 @@ public sealed class ItemMapperSystem : SharedItemMapperSystem { if (TryComp(uid, out var sprite)) { - component.RSIPath ??= sprite.BaseRSI!.Path!; + component.RSIPath ??= sprite.BaseRSI!.Path; } } private void OnAppearance(EntityUid uid, ItemMapperComponent component, ref AppearanceChangeEvent args) { - if (TryComp(component.Owner, out var spriteComponent)) + if (TryComp(uid, out var spriteComponent)) { if (component.SpriteLayers.Count == 0) { - InitLayers(component, spriteComponent, args.Component); + InitLayers((uid, component, spriteComponent, args.Component)); } - EnableLayers(component, spriteComponent, args.Component); + EnableLayers((uid, component, spriteComponent, args.Component)); } } - private void InitLayers(ItemMapperComponent component, SpriteComponent spriteComponent, AppearanceComponent appearance) + private void InitLayers(Entity ent) { - if (!_appearance.TryGetData(appearance.Owner, StorageMapVisuals.InitLayers, out var wrapper, appearance)) + var (owner, component, spriteComponent, appearance) = ent; + if (!_appearance.TryGetData(owner, StorageMapVisuals.InitLayers, out var wrapper, appearance)) return; component.SpriteLayers.AddRange(wrapper.QueuedEntities); @@ -53,9 +54,10 @@ public sealed class ItemMapperSystem : SharedItemMapperSystem } } - private void EnableLayers(ItemMapperComponent component, SpriteComponent spriteComponent, AppearanceComponent appearance) + private void EnableLayers(Entity ent) { - if (!_appearance.TryGetData(appearance.Owner, StorageMapVisuals.LayerChanged, out var wrapper, appearance)) + var (owner, component, spriteComponent, appearance) = ent; + if (!_appearance.TryGetData(owner, StorageMapVisuals.LayerChanged, out var wrapper, appearance)) return; foreach (var layerName in component.SpriteLayers) diff --git a/Content.Client/SubFloor/TrayScannerSystem.cs b/Content.Client/SubFloor/TrayScannerSystem.cs index 312a513e32..6497ba1d68 100644 --- a/Content.Client/SubFloor/TrayScannerSystem.cs +++ b/Content.Client/SubFloor/TrayScannerSystem.cs @@ -1,4 +1,3 @@ -using Content.Client.Hands; using Content.Shared.Hands.EntitySystems; using Content.Shared.Inventory; using Content.Shared.SubFloor; @@ -41,7 +40,7 @@ public sealed class TrayScannerSystem : SharedTrayScannerSystem var playerPos = _transform.GetWorldPosition(playerXform, xformQuery); var playerMap = playerXform.MapID; var range = 0f; - HashSet inRange; + HashSet> inRange; var scannerQuery = GetEntityQuery(); // TODO: Should probably sub to player attached changes / inventory changes but inventory's @@ -73,23 +72,20 @@ public sealed class TrayScannerSystem : SharedTrayScannerSystem canSee = true; } + inRange = new HashSet>(); + if (canSee) { - inRange = _lookup.GetComponentsInRange(playerMap, playerPos, range); + _lookup.GetEntitiesInRange(playerMap, playerPos, range, inRange); - foreach (var comp in inRange) + foreach (var (uid, comp) in inRange) { - var uid = comp.Owner; if (!comp.IsUnderCover || !comp.BlockAmbience | !comp.BlockInteractions) continue; EnsureComp(uid); } } - else - { - inRange = new HashSet(); - } var revealedQuery = AllEntityQuery(); var subfloorQuery = GetEntityQuery(); @@ -102,7 +98,7 @@ public sealed class TrayScannerSystem : SharedTrayScannerSystem xform.MapID != MapId.Nullspace && xform.MapID == playerMap && xform.Anchored && - inRange.Contains(subfloor)) + inRange.Contains((uid, subfloor))) { // Due to the fact client is predicting this server states will reset it constantly if ((!_appearance.TryGetData(uid, SubFloorVisuals.ScannerRevealed, out bool value) || !value) && diff --git a/Content.Client/UserInterface/Controls/SlotControl.cs b/Content.Client/UserInterface/Controls/SlotControl.cs index b0a2198443..37f8de88d6 100644 --- a/Content.Client/UserInterface/Controls/SlotControl.cs +++ b/Content.Client/UserInterface/Controls/SlotControl.cs @@ -188,10 +188,10 @@ namespace Content.Client.UserInterface.Controls if (!EntityHover) return; - var tempQualifier = HoverSpriteView.Sprite; + var tempQualifier = HoverSpriteView.Ent; if (tempQualifier != null) { - IoCManager.Resolve().QueueDeleteEntity(tempQualifier.Owner); + IoCManager.Resolve().QueueDeleteEntity(tempQualifier); } HoverSpriteView.SetEntity(null); diff --git a/Content.Client/Weather/WeatherOverlay.cs b/Content.Client/Weather/WeatherOverlay.cs index bd5627292a..12af31b863 100644 --- a/Content.Client/Weather/WeatherOverlay.cs +++ b/Content.Client/Weather/WeatherOverlay.cs @@ -7,9 +7,9 @@ using Robust.Client.Graphics; using Robust.Client.ResourceManagement; using Robust.Client.Utility; using Robust.Shared.Enums; -using Robust.Shared.Graphics; using Robust.Shared.Graphics.RSI; using Robust.Shared.Map; +using Robust.Shared.Map.Components; using Robust.Shared.Physics.Components; using Robust.Shared.Prototypes; using Robust.Shared.Timing; @@ -99,13 +99,17 @@ public sealed class WeatherOverlay : Overlay var xformQuery = _entManager.GetEntityQuery(); var weatherIgnoreQuery = _entManager.GetEntityQuery(); - foreach (var grid in _mapManager.FindGridsIntersecting(mapId, worldAABB)) + // idk if this is safe to cache in a field and clear sloth help + var grids = new List>(); + _mapManager.FindGridsIntersecting(mapId, worldAABB, ref grids); + + foreach (var grid in grids) { - var matrix = _transform.GetWorldMatrix(grid.Owner, xformQuery); + var matrix = _transform.GetWorldMatrix(grid, xformQuery); Matrix3.Multiply(in matrix, in invMatrix, out var matty); worldHandle.SetTransform(matty); - foreach (var tile in grid.GetTilesIntersecting(worldAABB)) + foreach (var tile in grid.Comp.GetTilesIntersecting(worldAABB)) { // Ignored tiles for stencil if (_weather.CanWeatherAffect(grid, tile, weatherIgnoreQuery, bodyQuery)) @@ -113,8 +117,8 @@ public sealed class WeatherOverlay : Overlay continue; } - var gridTile = new Box2(tile.GridIndices * grid.TileSize, - (tile.GridIndices + Vector2i.One) * grid.TileSize); + var gridTile = new Box2(tile.GridIndices * grid.Comp.TileSize, + (tile.GridIndices + Vector2i.One) * grid.Comp.TileSize); worldHandle.DrawRect(gridTile, Color.White); } diff --git a/Content.Client/Weather/WeatherSystem.cs b/Content.Client/Weather/WeatherSystem.cs index 43ad41ceaa..e1742f4790 100644 --- a/Content.Client/Weather/WeatherSystem.cs +++ b/Content.Client/Weather/WeatherSystem.cs @@ -18,6 +18,7 @@ public sealed class WeatherSystem : SharedWeatherSystem [Dependency] private readonly IOverlayManager _overlayManager = default!; [Dependency] private readonly IPlayerManager _playerManager = default!; [Dependency] private readonly AudioSystem _audio = default!; + [Dependency] private readonly MapSystem _mapSystem = default!; [Dependency] private readonly SharedPhysicsSystem _physics = default!; [Dependency] private readonly SharedTransformSystem _transform = default!; @@ -76,8 +77,9 @@ public sealed class WeatherSystem : SharedWeatherSystem // Work out tiles nearby to determine volume. if (TryComp(entXform.GridUid, out var grid)) { + var gridId = entXform.GridUid.Value; // Floodfill to the nearest tile and use that for audio. - var seed = grid.GetTileRef(entXform.Coordinates); + var seed = _mapSystem.GetTileRef(gridId, grid, entXform.Coordinates); var frontier = new Queue(); frontier.Enqueue(seed); // If we don't have a nearest node don't play any sound. @@ -107,7 +109,7 @@ public sealed class WeatherSystem : SharedWeatherSystem continue; } - frontier.Enqueue(grid.GetTileRef(new Vector2i(x, y) + node.GridIndices)); + frontier.Enqueue(_mapSystem.GetTileRef(gridId, grid, new Vector2i(x, y) + node.GridIndices)); } } diff --git a/Content.IntegrationTests/Pair/TestPair.Helpers.cs b/Content.IntegrationTests/Pair/TestPair.Helpers.cs index 510dc0b854..574644f67e 100644 --- a/Content.IntegrationTests/Pair/TestPair.Helpers.cs +++ b/Content.IntegrationTests/Pair/TestPair.Helpers.cs @@ -23,8 +23,9 @@ public sealed partial class TestPair { mapData.MapId = Server.MapMan.CreateMap(); mapData.MapUid = Server.MapMan.GetMapEntityId(mapData.MapId); - mapData.MapGrid = Server.MapMan.CreateGrid(mapData.MapId); - mapData.GridUid = mapData.MapGrid.Owner; // Fixing this requires an engine PR. + var mapGrid = Server.MapMan.CreateGridEntity(mapData.MapId); + mapData.MapGrid = mapGrid; + mapData.GridUid = mapGrid.Owner; // Fixing this requires an engine PR. mapData.GridCoords = new EntityCoordinates(mapData.GridUid, 0, 0); var plating = tileDefinitionManager["Plating"]; var platingTile = new Tile(plating.TileId); diff --git a/Content.IntegrationTests/Tests/Fluids/FluidSpillTest.cs b/Content.IntegrationTests/Tests/Fluids/FluidSpillTest.cs index da806aa10a..0d852bf2f0 100644 --- a/Content.IntegrationTests/Tests/Fluids/FluidSpillTest.cs +++ b/Content.IntegrationTests/Tests/Fluids/FluidSpillTest.cs @@ -17,11 +17,16 @@ namespace Content.IntegrationTests.Tests.Fluids; public sealed class FluidSpill { private static PuddleComponent? GetPuddle(IEntityManager entityManager, MapGridComponent mapGrid, Vector2i pos) + { + return GetPuddleEntity(entityManager, mapGrid, pos)?.Comp; + } + + private static Entity? GetPuddleEntity(IEntityManager entityManager, MapGridComponent mapGrid, Vector2i pos) { foreach (var uid in mapGrid.GetAnchoredEntities(pos)) { if (entityManager.TryGetComponent(uid, out PuddleComponent? puddleComponent)) - return puddleComponent; + return (uid, puddleComponent); } return null; @@ -48,19 +53,19 @@ public sealed class FluidSpill await server.WaitPost(() => { mapId = mapManager.CreateMap(); - var grid = mapManager.CreateGrid(mapId); + var grid = mapManager.CreateGridEntity(mapId); gridId = grid.Owner; for (var x = 0; x < 3; x++) { for (var y = 0; y < 3; y++) { - grid.SetTile(new Vector2i(x, y), new Tile(1)); + grid.Comp.SetTile(new Vector2i(x, y), new Tile(1)); } } - entityManager.SpawnEntity("WallReinforced", grid.GridTileToLocal(new Vector2i(0, 1))); - entityManager.SpawnEntity("WallReinforced", grid.GridTileToLocal(new Vector2i(1, 0))); + entityManager.SpawnEntity("WallReinforced", grid.Comp.GridTileToLocal(new Vector2i(0, 1))); + entityManager.SpawnEntity("WallReinforced", grid.Comp.GridTileToLocal(new Vector2i(1, 0))); }); @@ -82,12 +87,11 @@ public sealed class FluidSpill await server.WaitAssertion(() => { var grid = mapManager.GetGrid(gridId); - var puddle = GetPuddle(entityManager, grid, puddleOrigin); - + var puddle = GetPuddleEntity(entityManager, grid, puddleOrigin); #pragma warning disable NUnit2045 // Interdependent tests Assert.That(puddle, Is.Not.Null); - Assert.That(puddleSystem.CurrentVolume(puddle!.Owner, puddle), Is.EqualTo(FixedPoint2.New(100))); + Assert.That(puddleSystem.CurrentVolume(puddle!.Value.Owner, puddle), Is.EqualTo(FixedPoint2.New(100))); #pragma warning restore NUnit2045 for (var x = 0; x < 3; x++) diff --git a/Content.IntegrationTests/Tests/Interaction/InteractionTest.Helpers.cs b/Content.IntegrationTests/Tests/Interaction/InteractionTest.Helpers.cs index 453ad6b5ea..25171e1ea2 100644 --- a/Content.IntegrationTests/Tests/Interaction/InteractionTest.Helpers.cs +++ b/Content.IntegrationTests/Tests/Interaction/InteractionTest.Helpers.cs @@ -13,9 +13,7 @@ using Content.Server.Gravity; using Content.Server.Power.Components; using Content.Server.Tools.Components; using Content.Shared.Atmos; -using Content.Shared.Construction; using Content.Shared.Construction.Prototypes; -using Content.Shared.DoAfter; using Content.Shared.Gravity; using Content.Shared.Item; using Robust.Client.UserInterface; @@ -708,8 +706,9 @@ public abstract partial class InteractionTest if (proto == null) return; - grid = MapMan.CreateGrid(MapData.MapId); - gridUid = grid.Owner; + var gridEnt = MapMan.CreateGridEntity(MapData.MapId); + grid = gridEnt; + gridUid = gridEnt; var gridXform = SEntMan.GetComponent(gridUid); Transform.SetWorldPosition(gridXform, pos.Position); grid.SetTile(SEntMan.GetCoordinates(coords ?? TargetCoords), tile); diff --git a/Content.IntegrationTests/Tests/PostMapInitTest.cs b/Content.IntegrationTests/Tests/PostMapInitTest.cs index c650958199..45bff2f030 100644 --- a/Content.IntegrationTests/Tests/PostMapInitTest.cs +++ b/Content.IntegrationTests/Tests/PostMapInitTest.cs @@ -1,10 +1,10 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using System.Threading; using Content.Server.GameTicking; using Content.Server.Maps; using Content.Server.Shuttles.Components; +using Content.Server.Shuttles.Systems; using Content.Server.Spawners.Components; using Content.Server.Station.Components; using Content.Shared.CCVar; @@ -13,12 +13,11 @@ using Robust.Server.GameObjects; using Robust.Shared.Configuration; using Robust.Shared.ContentPack; using Robust.Shared.GameObjects; -using Robust.Shared.Utility; using Robust.Shared.Map; using Robust.Shared.Map.Components; using Robust.Shared.Prototypes; +using Robust.Shared.Utility; using YamlDotNet.RepresentationModel; -using ShuttleSystem = Content.Server.Shuttles.Systems.ShuttleSystem; namespace Content.IntegrationTests.Tests { @@ -184,7 +183,7 @@ namespace Content.IntegrationTests.Tests EntityUid? targetGrid = null; var memberQuery = entManager.GetEntityQuery(); - var grids = mapManager.GetAllMapGrids(mapId).ToList(); + var grids = mapManager.GetAllGrids(mapId).ToList(); var gridUids = grids.Select(o => o.Owner).ToList(); targetGrid = gridUids.First(); @@ -194,7 +193,7 @@ namespace Content.IntegrationTests.Tests if (!memberQuery.HasComponent(gridEnt)) continue; - var area = grid.LocalAABB.Width * grid.LocalAABB.Height; + var area = grid.Comp.LocalAABB.Width * grid.Comp.LocalAABB.Height; if (area > largest) { diff --git a/Content.Server/Access/Systems/IdCardSystem.cs b/Content.Server/Access/Systems/IdCardSystem.cs index 82a6c45555..3bf00d34c7 100644 --- a/Content.Server/Access/Systems/IdCardSystem.cs +++ b/Content.Server/Access/Systems/IdCardSystem.cs @@ -1,3 +1,4 @@ +using System.Linq; using Content.Server.Administration.Logs; using Content.Server.Kitchen.Components; using Content.Server.Popups; @@ -9,7 +10,6 @@ using Content.Shared.Popups; using Content.Shared.StatusIcon; using Robust.Shared.Prototypes; using Robust.Shared.Random; -using System.Linq; namespace Content.Server.Access.Systems { @@ -132,12 +132,12 @@ namespace Content.Server.Access.Systems } id.JobIcon = jobIcon.ID; - Dirty(id); + Dirty(uid, id); if (player != null) { _adminLogger.Add(LogType.Identity, LogImpact.Low, - $"{ToPrettyString(player.Value):player} has changed the job icon of {ToPrettyString(id.Owner):entity} to {jobIcon} "); + $"{ToPrettyString(player.Value):player} has changed the job icon of {ToPrettyString(uid):entity} to {jobIcon} "); } return true; @@ -181,7 +181,7 @@ namespace Content.Server.Access.Systems } /// - /// Changes the of . + /// Changes the name of the id's owner. /// /// /// If either or is empty, it's replaced by placeholders. diff --git a/Content.Server/Administration/Commands/RemoveEntityStorageCommand.cs b/Content.Server/Administration/Commands/RemoveEntityStorageCommand.cs index 48663f579d..858e48a71e 100644 --- a/Content.Server/Administration/Commands/RemoveEntityStorageCommand.cs +++ b/Content.Server/Administration/Commands/RemoveEntityStorageCommand.cs @@ -38,7 +38,7 @@ namespace Content.Server.Administration.Commands if (_entManager.TryGetComponent(parent, out var storage)) { - entstorage.Remove(entityUid.Value, storage.Owner, storage); + entstorage.Remove(entityUid.Value, parent, storage); } else { diff --git a/Content.Server/Administration/Systems/AdminVerbSystem.Smites.cs b/Content.Server/Administration/Systems/AdminVerbSystem.Smites.cs index e7b028cb94..c2f07320b5 100644 --- a/Content.Server/Administration/Systems/AdminVerbSystem.Smites.cs +++ b/Content.Server/Administration/Systems/AdminVerbSystem.Smites.cs @@ -337,7 +337,7 @@ public sealed partial class AdminVerbSystem Act = () => { var baseXform = Transform(args.Target); - foreach (var part in _bodySystem.GetBodyChildrenOfType(body.Owner, BodyPartType.Hand, body)) + foreach (var part in _bodySystem.GetBodyChildrenOfType(args.Target, BodyPartType.Hand, body)) { _transformSystem.AttachToGridOrMap(part.Id); break; diff --git a/Content.Server/Administration/Systems/BufferingSystem.cs b/Content.Server/Administration/Systems/BufferingSystem.cs index a8d1f88d72..f3df34e7d2 100644 --- a/Content.Server/Administration/Systems/BufferingSystem.cs +++ b/Content.Server/Administration/Systems/BufferingSystem.cs @@ -12,7 +12,8 @@ public sealed class BufferingSystem : EntitySystem public override void Update(float frameTime) { - foreach (var buffering in EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var buffering)) { if (buffering.BufferingIcon is not null) { @@ -21,7 +22,7 @@ public sealed class BufferingSystem : EntitySystem continue; Del(buffering.BufferingIcon.Value); - RemComp(buffering.Owner); + RemComp(uid); buffering.TimeTilNextBuffer = _random.NextFloat(buffering.MinimumTimeTilNextBuffer, buffering.MaximumTimeTilNextBuffer); buffering.BufferingIcon = null; } @@ -32,8 +33,8 @@ public sealed class BufferingSystem : EntitySystem continue; buffering.BufferingTimer = _random.NextFloat(buffering.MinimumBufferTime, buffering.MaximumBufferTime); - buffering.BufferingIcon = Spawn("BufferingIcon", new EntityCoordinates(buffering.Owner, Vector2.Zero)); - EnsureComp(buffering.Owner); + buffering.BufferingIcon = Spawn("BufferingIcon", new EntityCoordinates(uid, Vector2.Zero)); + EnsureComp(uid); } } } diff --git a/Content.Server/AlertLevel/AlertLevelDisplaySystem.cs b/Content.Server/AlertLevel/AlertLevelDisplaySystem.cs index 043f69e420..4f2108748b 100644 --- a/Content.Server/AlertLevel/AlertLevelDisplaySystem.cs +++ b/Content.Server/AlertLevel/AlertLevelDisplaySystem.cs @@ -1,7 +1,6 @@ using Content.Server.Power.Components; using Content.Server.Station.Systems; using Content.Shared.AlertLevel; -using Robust.Server.GameObjects; namespace Content.Server.AlertLevel; @@ -19,9 +18,10 @@ public sealed class AlertLevelDisplaySystem : EntitySystem private void OnAlertChanged(AlertLevelChangedEvent args) { - foreach (var (_, appearance) in EntityManager.EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out _, out var appearance)) { - _appearance.SetData(appearance.Owner, AlertLevelDisplay.CurrentLevel, args.AlertLevel, appearance); + _appearance.SetData(uid, AlertLevelDisplay.CurrentLevel, args.AlertLevel, appearance); } } diff --git a/Content.Server/AlertLevel/AlertLevelSystem.cs b/Content.Server/AlertLevel/AlertLevelSystem.cs index 121f6f4c1b..66e09d34e0 100644 --- a/Content.Server/AlertLevel/AlertLevelSystem.cs +++ b/Content.Server/AlertLevel/AlertLevelSystem.cs @@ -2,7 +2,6 @@ using System.Linq; using Content.Server.Chat.Systems; using Content.Server.Station.Systems; using Content.Shared.CCVar; -using Content.Shared.PDA; using Robust.Shared.Audio; using Robust.Shared.Configuration; using Robust.Shared.Prototypes; @@ -83,7 +82,8 @@ public sealed class AlertLevelSystem : EntitySystem return; } - foreach (var comp in EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var comp)) { comp.AlertLevels = alerts; @@ -95,7 +95,7 @@ public sealed class AlertLevelSystem : EntitySystem defaultLevel = comp.AlertLevels.Levels.Keys.First(); } - SetLevel(comp.Owner, defaultLevel, true, true, true); + SetLevel(uid, defaultLevel, true, true, true); } } diff --git a/Content.Server/Animals/Systems/UdderSystem.cs b/Content.Server/Animals/Systems/UdderSystem.cs index 4a90c3c3d8..4164aedfd1 100644 --- a/Content.Server/Animals/Systems/UdderSystem.cs +++ b/Content.Server/Animals/Systems/UdderSystem.cs @@ -1,9 +1,6 @@ using Content.Server.Animals.Components; -using Content.Server.DoAfter; -using Content.Server.Nutrition.Components; using Content.Server.Popups; using Content.Shared.Chemistry.Components; -using Content.Shared.Chemistry.Components.SolutionManager; using Content.Shared.Chemistry.EntitySystems; using Content.Shared.DoAfter; using Content.Shared.IdentityManagement; @@ -32,9 +29,11 @@ namespace Content.Server.Animals.Systems SubscribeLocalEvent>(AddMilkVerb); SubscribeLocalEvent(OnDoAfter); } + public override void Update(float frameTime) { - foreach (var udder in EntityManager.EntityQuery(false)) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var udder)) { udder.AccumulatedFrameTime += frameTime; @@ -43,19 +42,19 @@ namespace Content.Server.Animals.Systems udder.AccumulatedFrameTime -= udder.UpdateRate; // Actually there is food digestion so no problem with instant reagent generation "OnFeed" - if (EntityManager.TryGetComponent(udder.Owner, out HungerComponent? hunger)) + if (EntityManager.TryGetComponent(uid, out HungerComponent? hunger)) { // Is there enough nutrition to produce reagent? if (_hunger.GetHungerThreshold(hunger) < HungerThreshold.Peckish) continue; } - if (!_solutionContainerSystem.TryGetSolution(udder.Owner, udder.TargetSolutionName, + if (!_solutionContainerSystem.TryGetSolution(uid, udder.TargetSolutionName, out var solution)) continue; //TODO: toxins from bloodstream !? - _solutionContainerSystem.TryAddReagent(udder.Owner, solution, udder.ReagentId, + _solutionContainerSystem.TryAddReagent(uid, solution, udder.ReagentId, udder.QuantityPerUpdate, out var accepted); } } diff --git a/Content.Server/Anomaly/Effects/BluespaceAnomalySystem.cs b/Content.Server/Anomaly/Effects/BluespaceAnomalySystem.cs index cd7adbd3e4..964a42234d 100644 --- a/Content.Server/Anomaly/Effects/BluespaceAnomalySystem.cs +++ b/Content.Server/Anomaly/Effects/BluespaceAnomalySystem.cs @@ -28,9 +28,9 @@ public sealed class BluespaceAnomalySystem : EntitySystem var xformQuery = GetEntityQuery(); var xform = xformQuery.GetComponent(uid); var range = component.MaxShuffleRadius * args.Severity; - var allEnts = _lookup.GetComponentsInRange(xform.Coordinates, range) - .Select(x => x.Owner).ToList(); - allEnts.Add(uid); + var mobs = new HashSet>(); + _lookup.GetEntitiesInRange(xform.Coordinates, range, mobs); + var allEnts = new List(mobs.Select(m => m.Owner)) { uid }; var coords = new List(); foreach (var ent in allEnts) { @@ -51,7 +51,9 @@ public sealed class BluespaceAnomalySystem : EntitySystem var mapPos = _xform.GetWorldPosition(xform); var radius = component.SupercriticalTeleportRadius; var gridBounds = new Box2(mapPos - new Vector2(radius, radius), mapPos + new Vector2(radius, radius)); - foreach (var comp in _lookup.GetComponentsInRange(xform.Coordinates, component.MaxShuffleRadius)) + var mobs = new HashSet>(); + _lookup.GetEntitiesInRange(xform.Coordinates, component.MaxShuffleRadius, mobs); + foreach (var comp in mobs) { var ent = comp.Owner; var randomX = _random.NextFloat(gridBounds.Left, gridBounds.Right); diff --git a/Content.Server/Anomaly/Effects/ElectricityAnomalySystem.cs b/Content.Server/Anomaly/Effects/ElectricityAnomalySystem.cs index 688218d6ca..bc6aa3bb1f 100644 --- a/Content.Server/Anomaly/Effects/ElectricityAnomalySystem.cs +++ b/Content.Server/Anomaly/Effects/ElectricityAnomalySystem.cs @@ -1,5 +1,5 @@ using Content.Server.Electrocution; -using Content.Server.Emp; +using Content.Server.Emp; using Content.Server.Lightning; using Content.Server.Power.Components; using Content.Shared.Anomaly.Components; @@ -31,9 +31,8 @@ public sealed class ElectricityAnomalySystem : EntitySystem { var range = component.MaxElectrocuteRange * args.Stability; var xform = Transform(uid); - foreach (var comp in _lookup.GetComponentsInRange(xform.MapPosition, range)) + foreach (var (ent, comp) in _lookup.GetEntitiesInRange(xform.MapPosition, range)) { - var ent = comp.Owner; _lightning.ShootLightning(uid, ent); } } @@ -66,14 +65,13 @@ public sealed class ElectricityAnomalySystem : EntitySystem { base.Update(frameTime); - foreach (var (elec, anom, xform) in EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var elec, out var anom, out var xform)) { if (_timing.CurTime < elec.NextSecond) continue; elec.NextSecond = _timing.CurTime + TimeSpan.FromSeconds(1); - var owner = xform.Owner; - if (!_random.Prob(elec.PassiveElectrocutionChance * anom.Stability)) continue; @@ -81,11 +79,9 @@ public sealed class ElectricityAnomalySystem : EntitySystem var damage = (int) (elec.MaxElectrocuteDamage * anom.Severity); var duration = elec.MaxElectrocuteDuration * anom.Severity; - foreach (var comp in _lookup.GetComponentsInRange(xform.MapPosition, range)) + foreach (var (ent, comp) in _lookup.GetEntitiesInRange(xform.MapPosition, range)) { - var ent = comp.Owner; - - _electrocution.TryDoElectrocution(ent, owner, damage, duration, true, statusEffects: comp, ignoreInsulation: true); + _electrocution.TryDoElectrocution(ent, uid, damage, duration, true, statusEffects: comp, ignoreInsulation: true); } } } diff --git a/Content.Server/Anomaly/Effects/InjectionAnomalySystem.cs b/Content.Server/Anomaly/Effects/InjectionAnomalySystem.cs index 0cc7883808..05f1c5c61c 100644 --- a/Content.Server/Anomaly/Effects/InjectionAnomalySystem.cs +++ b/Content.Server/Anomaly/Effects/InjectionAnomalySystem.cs @@ -1,8 +1,8 @@ using System.Linq; using Content.Server.Anomaly.Components; +using Content.Shared.Anomaly.Components; using Content.Shared.Chemistry.Components.SolutionManager; using Content.Shared.Chemistry.EntitySystems; -using Content.Shared.Anomaly.Components; namespace Content.Server.Anomaly.Effects; /// @@ -44,7 +44,7 @@ public sealed class InjectionAnomalySystem : EntitySystem //We get all the entity in the radius into which the reagent will be injected. var xformQuery = GetEntityQuery(); var xform = xformQuery.GetComponent(uid); - var allEnts = _lookup.GetComponentsInRange(xform.MapPosition, injectRadius) + var allEnts = _lookup.GetEntitiesInRange(xform.MapPosition, injectRadius) .Select(x => x.Owner).ToList(); //for each matching entity found diff --git a/Content.Server/Anomaly/Effects/PyroclasticAnomalySystem.cs b/Content.Server/Anomaly/Effects/PyroclasticAnomalySystem.cs index 7ee6f12d05..6bd8be002e 100644 --- a/Content.Server/Anomaly/Effects/PyroclasticAnomalySystem.cs +++ b/Content.Server/Anomaly/Effects/PyroclasticAnomalySystem.cs @@ -36,7 +36,10 @@ public sealed class PyroclasticAnomalySystem : EntitySystem public void IgniteNearby(EntityUid uid, EntityCoordinates coordinates, float severity, float radius) { - foreach (var flammable in _lookup.GetComponentsInRange(coordinates, radius)) + var flammables = new HashSet>(); + _lookup.GetEntitiesInRange(coordinates, radius, flammables); + + foreach (var flammable in flammables) { var ent = flammable.Owner; var stackAmount = 1 + (int) (severity / 0.15f); diff --git a/Content.Server/Atmos/Commands/FillGasCommand.cs b/Content.Server/Atmos/Commands/FillGasCommand.cs index b6db46abed..7eb34d9066 100644 --- a/Content.Server/Atmos/Commands/FillGasCommand.cs +++ b/Content.Server/Atmos/Commands/FillGasCommand.cs @@ -3,7 +3,7 @@ using Content.Server.Atmos.EntitySystems; using Content.Shared.Administration; using Content.Shared.Atmos; using Robust.Shared.Console; -using Robust.Shared.Map; +using Robust.Shared.Map.Components; namespace Content.Server.Atmos.Commands { @@ -11,7 +11,6 @@ namespace Content.Server.Atmos.Commands public sealed class FillGas : IConsoleCommand { [Dependency] private readonly IEntityManager _entManager = default!; - [Dependency] private readonly IMapManager _mapManager = default!; public string Command => "fillgas"; public string Description => "Adds gas to all tiles in a grid."; @@ -30,7 +29,7 @@ namespace Content.Server.Atmos.Commands return; } - if (!_mapManager.TryGetGrid(gridId, out var grid)) + if (!_entManager.HasComponent(gridId)) { shell.WriteLine("Invalid grid ID."); return; @@ -38,7 +37,7 @@ namespace Content.Server.Atmos.Commands var atmosphereSystem = _entManager.System(); - foreach (var tile in atmosphereSystem.GetAllMixtures(grid.Owner, true)) + foreach (var tile in atmosphereSystem.GetAllMixtures(gridId.Value, true)) { tile.AdjustMoles(gasId, moles); } diff --git a/Content.Server/Atmos/Commands/SetAtmosTemperatureCommand.cs b/Content.Server/Atmos/Commands/SetAtmosTemperatureCommand.cs index 1d7e306d54..a3ec0f03fd 100644 --- a/Content.Server/Atmos/Commands/SetAtmosTemperatureCommand.cs +++ b/Content.Server/Atmos/Commands/SetAtmosTemperatureCommand.cs @@ -3,7 +3,7 @@ using Content.Server.Atmos.EntitySystems; using Content.Shared.Administration; using Content.Shared.Atmos; using Robust.Shared.Console; -using Robust.Shared.Map; +using Robust.Shared.Map.Components; namespace Content.Server.Atmos.Commands { @@ -11,7 +11,6 @@ namespace Content.Server.Atmos.Commands public sealed class SetAtmosTemperatureCommand : IConsoleCommand { [Dependency] private readonly IEntityManager _entManager = default!; - [Dependency] private readonly IMapManager _mapManager = default!; public string Command => "setatmostemp"; public string Description => "Sets a grid's temperature (in kelvin)."; @@ -34,7 +33,7 @@ namespace Content.Server.Atmos.Commands return; } - if (!gridId.Value.IsValid() || !_mapManager.TryGetGrid(gridId, out var gridComp)) + if (!gridId.Value.IsValid() || !_entManager.HasComponent(gridId)) { shell.WriteLine("Invalid grid ID."); return; @@ -43,7 +42,7 @@ namespace Content.Server.Atmos.Commands var atmosphereSystem = _entManager.System(); var tiles = 0; - foreach (var tile in atmosphereSystem.GetAllMixtures(gridComp.Owner, true)) + foreach (var tile in atmosphereSystem.GetAllMixtures(gridId.Value, true)) { tiles++; tile.Temperature = temperature; diff --git a/Content.Server/Atmos/Commands/SetTemperatureCommand.cs b/Content.Server/Atmos/Commands/SetTemperatureCommand.cs index e6dcbdb4cf..75d358dfd6 100644 --- a/Content.Server/Atmos/Commands/SetTemperatureCommand.cs +++ b/Content.Server/Atmos/Commands/SetTemperatureCommand.cs @@ -2,11 +2,8 @@ using Content.Server.Administration; using Content.Server.Atmos.EntitySystems; using Content.Shared.Administration; using Content.Shared.Atmos; -using Robust.Server.GameObjects; using Robust.Shared.Console; -using Robust.Shared.GameObjects; -using Robust.Shared.Map; -using Robust.Shared.Maths; +using Robust.Shared.Map.Components; namespace Content.Server.Atmos.Commands { @@ -14,7 +11,6 @@ namespace Content.Server.Atmos.Commands public sealed class SetTemperatureCommand : IConsoleCommand { [Dependency] private readonly IEntityManager _entities = default!; - [Dependency] private readonly IMapManager _mapManager = default!; public string Command => "settemp"; public string Description => "Sets a tile's temperature (in kelvin)."; @@ -40,7 +36,7 @@ namespace Content.Server.Atmos.Commands return; } - if (!_mapManager.TryGetGrid(gridId, out var grid)) + if (!_entities.HasComponent(gridId)) { shell.WriteError("Invalid grid."); return; @@ -49,7 +45,7 @@ namespace Content.Server.Atmos.Commands var atmospheres = _entities.EntitySysManager.GetEntitySystem(); var indices = new Vector2i(x, y); - var tile = atmospheres.GetTileMixture(grid.Owner, null, indices, true); + var tile = atmospheres.GetTileMixture(gridId, null, indices, true); if (tile == null) { diff --git a/Content.Server/Atmos/Components/GridAtmosphereComponent.cs b/Content.Server/Atmos/Components/GridAtmosphereComponent.cs index ab24daa716..f9301d7029 100644 --- a/Content.Server/Atmos/Components/GridAtmosphereComponent.cs +++ b/Content.Server/Atmos/Components/GridAtmosphereComponent.cs @@ -62,7 +62,7 @@ namespace Content.Server.Atmos.Components public readonly HashSet PipeNets = new(); [ViewVariables] - public readonly HashSet AtmosDevices = new(); + public readonly HashSet> AtmosDevices = new(); [ViewVariables] public Queue CurrentRunTiles = new(); @@ -74,7 +74,7 @@ namespace Content.Server.Atmos.Components public Queue CurrentRunPipeNet = new(); [ViewVariables] - public Queue CurrentRunAtmosDevices = new(); + public Queue> CurrentRunAtmosDevices = new(); [ViewVariables] public readonly HashSet InvalidatedCoords = new(1000); diff --git a/Content.Server/Atmos/EntitySystems/AirtightSystem.cs b/Content.Server/Atmos/EntitySystems/AirtightSystem.cs index f899ffb2e8..97dccbaabb 100644 --- a/Content.Server/Atmos/EntitySystems/AirtightSystem.cs +++ b/Content.Server/Atmos/EntitySystems/AirtightSystem.cs @@ -4,7 +4,6 @@ using Content.Shared.Atmos; using JetBrains.Annotations; using Robust.Shared.Map; using Robust.Shared.Map.Components; -using Content.Shared.Destructible; namespace Content.Server.Atmos.EntitySystems { @@ -24,31 +23,32 @@ namespace Content.Server.Atmos.EntitySystems SubscribeLocalEvent(OnAirtightMoved); } - private void OnAirtightInit(EntityUid uid, AirtightComponent airtight, ComponentInit args) + private void OnAirtightInit(Entity airtight, ref ComponentInit args) { - var xform = EntityManager.GetComponent(uid); + var xform = EntityManager.GetComponent(airtight); - if (airtight.FixAirBlockedDirectionInitialize) + if (airtight.Comp.FixAirBlockedDirectionInitialize) { - var moveEvent = new MoveEvent(uid, default, default, Angle.Zero, xform.LocalRotation, xform, false); - if (AirtightMove(uid, airtight, ref moveEvent)) + var moveEvent = new MoveEvent(airtight, default, default, Angle.Zero, xform.LocalRotation, xform, false); + if (AirtightMove(airtight, ref moveEvent)) return; } UpdatePosition(airtight); } - private void OnAirtightShutdown(EntityUid uid, AirtightComponent airtight, ComponentShutdown args) + private void OnAirtightShutdown(Entity airtight, ref ComponentShutdown args) { - var xform = Transform(uid); + var xform = Transform(airtight); // If the grid is deleting no point updating atmos. - if (_mapManager.TryGetGrid(xform.GridUid, out var grid)) + if (HasComp(xform.GridUid) && + MetaData(xform.GridUid.Value).EntityLifeStage > EntityLifeStage.MapInitialized) { - if (MetaData(grid.Owner).EntityLifeStage > EntityLifeStage.MapInitialized) return; + return; } - SetAirblocked(uid, airtight, false, xform); + SetAirblocked(airtight, false, xform); } private void OnAirtightPositionChanged(EntityUid uid, AirtightComponent airtight, ref AnchorStateChangedEvent args) @@ -78,44 +78,47 @@ namespace Content.Server.Atmos.EntitySystems } } - private void OnAirtightMoved(EntityUid uid, AirtightComponent airtight, ref MoveEvent ev) + private void OnAirtightMoved(Entity airtight, ref MoveEvent ev) { - AirtightMove(uid, airtight, ref ev); + AirtightMove(airtight, ref ev); } - private bool AirtightMove(EntityUid uid, AirtightComponent airtight, ref MoveEvent ev) + private bool AirtightMove(Entity ent, ref MoveEvent ev) { + var (owner, airtight) = ent; if (!airtight.RotateAirBlocked || airtight.InitialAirBlockedDirection == (int)AtmosDirection.Invalid) return false; airtight.CurrentAirBlockedDirection = (int) Rotate((AtmosDirection)airtight.InitialAirBlockedDirection, ev.NewRotation); var pos = airtight.LastPosition; - UpdatePosition(airtight, ev.Component); - var airtightEv = new AirtightChanged(uid, airtight, pos); - RaiseLocalEvent(uid, ref airtightEv, true); + UpdatePosition(ent, ev.Component); + var airtightEv = new AirtightChanged(owner, airtight, pos); + RaiseLocalEvent(owner, ref airtightEv, true); return true; } - public void SetAirblocked(EntityUid uid, AirtightComponent airtight, bool airblocked, TransformComponent? xform = null) + public void SetAirblocked(Entity airtight, bool airblocked, TransformComponent? xform = null) { - if (airtight.AirBlocked == airblocked) + if (airtight.Comp.AirBlocked == airblocked) return; - if (!Resolve(uid, ref xform)) + if (!Resolve(airtight, ref xform)) return; - var pos = airtight.LastPosition; - airtight.AirBlocked = airblocked; + var pos = airtight.Comp.LastPosition; + airtight.Comp.AirBlocked = airblocked; UpdatePosition(airtight, xform); - var airtightEv = new AirtightChanged(uid, airtight, pos); - RaiseLocalEvent(uid, ref airtightEv, true); + var airtightEv = new AirtightChanged(airtight, airtight, pos); + RaiseLocalEvent(airtight, ref airtightEv, true); } - public void UpdatePosition(AirtightComponent airtight, TransformComponent? xform = null) + public void UpdatePosition(Entity ent, TransformComponent? xform = null) { - if (!Resolve(airtight.Owner, ref xform)) return; + var (owner, airtight) = ent; + if (!Resolve(owner, ref xform)) + return; - if (!xform.Anchored || !_mapManager.TryGetGrid(xform.GridUid, out var grid)) + if (!xform.Anchored || !TryComp(xform.GridUid, out MapGridComponent? grid)) return; airtight.LastPosition = (xform.GridUid.Value, grid.TileIndicesFor(xform.Coordinates)); @@ -124,15 +127,13 @@ namespace Content.Server.Atmos.EntitySystems public void InvalidatePosition(EntityUid gridId, Vector2i pos, bool fixVacuum = false) { - if (!_mapManager.TryGetGrid(gridId, out var grid)) + if (!TryComp(gridId, out MapGridComponent? grid)) return; - var gridUid = grid.Owner; - var query = EntityManager.GetEntityQuery(); _explosionSystem.UpdateAirtightMap(gridId, pos, grid, query); // TODO make atmos system use query - _atmosphereSystem.InvalidateTile(gridUid, pos); + _atmosphereSystem.InvalidateTile(gridId, pos); } private AtmosDirection Rotate(AtmosDirection myDirection, Angle myAngle) @@ -146,7 +147,8 @@ namespace Content.Server.Atmos.EntitySystems for (var i = 0; i < Atmospherics.Directions; i++) { var direction = (AtmosDirection) (1 << i); - if (!myDirection.IsFlagSet(direction)) continue; + if (!myDirection.IsFlagSet(direction)) + continue; var angle = direction.ToAngle(); angle += myAngle; newAirBlockedDirs |= angle.ToAtmosDirectionCardinal(); diff --git a/Content.Server/Atmos/EntitySystems/AtmosDebugOverlaySystem.cs b/Content.Server/Atmos/EntitySystems/AtmosDebugOverlaySystem.cs index 8b1c425d89..34f558a252 100644 --- a/Content.Server/Atmos/EntitySystems/AtmosDebugOverlaySystem.cs +++ b/Content.Server/Atmos/EntitySystems/AtmosDebugOverlaySystem.cs @@ -4,10 +4,12 @@ using Content.Shared.Atmos; using Content.Shared.Atmos.EntitySystems; using Content.Shared.CCVar; using JetBrains.Annotations; +using Robust.Server.GameObjects; using Robust.Server.Player; using Robust.Shared.Configuration; using Robust.Shared.Enums; using Robust.Shared.Map; +using Robust.Shared.Map.Components; namespace Content.Server.Atmos.EntitySystems { @@ -18,6 +20,7 @@ namespace Content.Server.Atmos.EntitySystems [Dependency] private readonly IMapManager _mapManager = default!; [Dependency] private readonly IConfigurationManager _configManager = default!; [Dependency] private readonly AtmosphereSystem _atmosphereSystem = default!; + [Dependency] private readonly MapSystem _mapSystem = default!; /// /// Players allowed to see the atmos debug overlay. @@ -31,6 +34,8 @@ namespace Content.Server.Atmos.EntitySystems /// private float _updateCooldown; + private List> _grids = new(); + public override void Initialize() { base.Initialize(); @@ -137,7 +142,10 @@ namespace Content.Server.Atmos.EntitySystems var worldBounds = Box2.CenteredAround(transform.WorldPosition, new Vector2(LocalViewRange, LocalViewRange)); - foreach (var grid in _mapManager.FindGridsIntersecting(transform.MapID, worldBounds)) + _grids.Clear(); + _mapManager.FindGridsIntersecting(transform.MapID, worldBounds, ref _grids); + + foreach (var grid in _grids) { var uid = grid.Owner; @@ -147,7 +155,7 @@ namespace Content.Server.Atmos.EntitySystems if (!TryComp(uid, out GridAtmosphereComponent? gridAtmos)) continue; - var entityTile = grid.GetTileRef(transform.Coordinates).GridIndices; + var entityTile = _mapSystem.GetTileRef(grid, grid, transform.Coordinates).GridIndices; var baseTile = new Vector2i(entityTile.X - (LocalViewRange / 2), entityTile.Y - (LocalViewRange / 2)); var debugOverlayContent = new AtmosDebugOverlayData[LocalViewRange * LocalViewRange]; @@ -161,7 +169,7 @@ namespace Content.Server.Atmos.EntitySystems } } - RaiseNetworkEvent(new AtmosDebugOverlayMessage(GetNetEntity(grid.Owner), baseTile, debugOverlayContent), session.ConnectedClient); + RaiseNetworkEvent(new AtmosDebugOverlayMessage(GetNetEntity(grid), baseTile, debugOverlayContent), session.ConnectedClient); } } } diff --git a/Content.Server/Atmos/EntitySystems/AtmosphereSystem.BreathTool.cs b/Content.Server/Atmos/EntitySystems/AtmosphereSystem.BreathTool.cs index 22270cb541..741a9341e7 100644 --- a/Content.Server/Atmos/EntitySystems/AtmosphereSystem.BreathTool.cs +++ b/Content.Server/Atmos/EntitySystems/AtmosphereSystem.BreathTool.cs @@ -22,7 +22,7 @@ public sealed partial class AtmosphereSystem if (TryComp(old, out var internalsComponent)) { - _internals.DisconnectBreathTool(internalsComponent); + _internals.DisconnectBreathTool((old.Value, internalsComponent)); } component.IsFunctional = false; diff --git a/Content.Server/Atmos/EntitySystems/AtmosphereSystem.Commands.cs b/Content.Server/Atmos/EntitySystems/AtmosphereSystem.Commands.cs index 75caab93f0..6fbd638844 100644 --- a/Content.Server/Atmos/EntitySystems/AtmosphereSystem.Commands.cs +++ b/Content.Server/Atmos/EntitySystems/AtmosphereSystem.Commands.cs @@ -3,7 +3,6 @@ using Content.Server.Administration; using Content.Server.Atmos.Components; using Content.Shared.Administration; using Content.Shared.Atmos; -using Content.Shared.Maps; using Robust.Shared.Console; using Robust.Shared.Map; using Robust.Shared.Map.Components; @@ -128,12 +127,13 @@ public sealed partial class AtmosphereSystem if (playerMap == null) return CompletionResult.FromOptions(options); - foreach (var grid in _mapManager.GetAllMapGrids(playerMap.Value).OrderBy(o => o.Owner)) + foreach (var grid in _mapManager.GetAllGrids(playerMap.Value).OrderBy(o => o.Owner)) { - if (!TryComp(grid.Owner, out var gridXform)) + var uid = grid.Owner; + if (!TryComp(uid, out var gridXform)) continue; - options.Add(new CompletionOption(grid.Owner.ToString(), $"{MetaData(grid.Owner).EntityName} - Map {gridXform.MapID}")); + options.Add(new CompletionOption(uid.ToString(), $"{MetaData(uid).EntityName} - Map {gridXform.MapID}")); } return CompletionResult.FromOptions(options); diff --git a/Content.Server/Atmos/EntitySystems/AtmosphereSystem.GridAtmosphere.cs b/Content.Server/Atmos/EntitySystems/AtmosphereSystem.GridAtmosphere.cs index 935abb29fc..036b64cad9 100644 --- a/Content.Server/Atmos/EntitySystems/AtmosphereSystem.GridAtmosphere.cs +++ b/Content.Server/Atmos/EntitySystems/AtmosphereSystem.GridAtmosphere.cs @@ -3,7 +3,6 @@ using Content.Server.Atmos.Components; using Content.Server.Atmos.Reactions; using Content.Shared.Atmos; using Content.Shared.Atmos.Components; -using Robust.Shared.Map; using Robust.Shared.Map.Components; using Robust.Shared.Utility; @@ -57,7 +56,7 @@ public sealed partial class AtmosphereSystem tile.GridIndex = uid; } - GridRepopulateTiles(mapGrid, gridAtmosphere); + GridRepopulateTiles((uid, mapGrid, gridAtmosphere)); } private void OnGridSplit(EntityUid uid, GridAtmosphereComponent originalGridAtmos, ref GridSplitEvent args) @@ -65,14 +64,12 @@ public sealed partial class AtmosphereSystem foreach (var newGrid in args.NewGrids) { // Make extra sure this is a valid grid. - if (!_mapManager.TryGetGrid(newGrid, out var mapGrid)) + if (!TryComp(newGrid, out MapGridComponent? mapGrid)) continue; - var entity = mapGrid.Owner; - // If the new split grid has an atmosphere already somehow, use that. Otherwise, add a new one. - if (!TryComp(entity, out GridAtmosphereComponent? newGridAtmos)) - newGridAtmos = AddComp(entity); + if (!TryComp(newGrid, out GridAtmosphereComponent? newGridAtmos)) + newGridAtmos = AddComp(newGrid); // We assume the tiles on the new grid have the same coordinates as they did on the old grid... var enumerator = mapGrid.GetAllTilesEnumerator(); @@ -505,16 +502,15 @@ public sealed partial class AtmosphereSystem args.Handled = component.PipeNets.Remove(args.PipeNet); } - private void GridAddAtmosDevice(EntityUid uid, GridAtmosphereComponent component, - ref AddAtmosDeviceMethodEvent args) + private void GridAddAtmosDevice(Entity grid, ref AddAtmosDeviceMethodEvent args) { if (args.Handled) return; - if (!component.AtmosDevices.Add(args.Device)) + if (!grid.Comp.AtmosDevices.Add((args.Device.Owner, args.Device))) return; - args.Device.JoinedGrid = uid; + args.Device.JoinedGrid = grid; args.Handled = true; args.Result = true; } @@ -525,7 +521,7 @@ public sealed partial class AtmosphereSystem if (args.Handled) return; - if (!component.AtmosDevices.Remove(args.Device)) + if (!component.AtmosDevices.Remove((args.Device.Owner, args.Device))) return; args.Device.JoinedGrid = null; @@ -538,8 +534,9 @@ public sealed partial class AtmosphereSystem /// /// The grid where to get all valid tiles from. /// The grid atmosphere where the tiles will be repopulated. - private void GridRepopulateTiles(MapGridComponent mapGrid, GridAtmosphereComponent gridAtmosphere) + private void GridRepopulateTiles(Entity grid) { + var (uid, mapGrid, gridAtmosphere) = grid; var volume = GetVolumeForTiles(mapGrid, 1); foreach (var tile in mapGrid.GetAllTiles()) @@ -551,16 +548,14 @@ public sealed partial class AtmosphereSystem gridAtmosphere.InvalidatedCoords.Add(tile.GridIndices); } - var uid = gridAtmosphere.Owner; - - TryComp(gridAtmosphere.Owner, out GasTileOverlayComponent? overlay); + TryComp(uid, out GasTileOverlayComponent? overlay); // Gotta do this afterwards so we can properly update adjacent tiles. foreach (var (position, _) in gridAtmosphere.Tiles.ToArray()) { var ev = new UpdateAdjacentMethodEvent(uid, position); GridUpdateAdjacent(uid, gridAtmosphere, ref ev); - InvalidateVisuals(mapGrid.Owner, position, overlay); + InvalidateVisuals(uid, position, overlay); } } } diff --git a/Content.Server/Atmos/EntitySystems/AtmosphereSystem.HighPressureDelta.cs b/Content.Server/Atmos/EntitySystems/AtmosphereSystem.HighPressureDelta.cs index a06bf3504c..020684aa3b 100644 --- a/Content.Server/Atmos/EntitySystems/AtmosphereSystem.HighPressureDelta.cs +++ b/Content.Server/Atmos/EntitySystems/AtmosphereSystem.HighPressureDelta.cs @@ -22,32 +22,34 @@ namespace Content.Server.Atmos.EntitySystems [ViewVariables(VVAccess.ReadWrite)] public string? SpaceWindSound { get; private set; } = "/Audio/Effects/space_wind.ogg"; - private HashSet _activePressures = new(8); + private readonly HashSet> _activePressures = new(8); private void UpdateHighPressure(float frameTime) { - var toRemove = new RemQueue(); + var toRemove = new RemQueue>(); - foreach (var comp in _activePressures) + foreach (var ent in _activePressures) { - var uid = comp.Owner; + var (uid, comp) = ent; MetaDataComponent? metadata = null; if (Deleted(uid, metadata)) { - toRemove.Add(comp); + toRemove.Add((uid, comp)); continue; } - if (Paused(uid, metadata)) continue; + if (Paused(uid, metadata)) + continue; comp.Accumulator += frameTime; - if (comp.Accumulator < 2f) continue; + if (comp.Accumulator < 2f) + continue; // Reset it just for VV reasons even though it doesn't matter comp.Accumulator = 0f; - toRemove.Add(comp); + toRemove.Add(ent); if (HasComp(uid) && TryComp(uid, out var body)) @@ -86,10 +88,10 @@ namespace Content.Server.Atmos.EntitySystems // idk it's hard. component.Accumulator = 0f; - _activePressures.Add(component); + _activePressures.Add((uid, component)); } - private void HighPressureMovements(GridAtmosphereComponent gridAtmosphere, TileAtmosphere tile, EntityQuery bodies, EntityQuery xforms, EntityQuery pressureQuery, EntityQuery metas) + private void HighPressureMovements(Entity gridAtmosphere, TileAtmosphere tile, EntityQuery bodies, EntityQuery xforms, EntityQuery pressureQuery, EntityQuery metas) { // TODO ATMOS finish this @@ -118,7 +120,7 @@ namespace Content.Server.Atmos.EntitySystems return; // Used by ExperiencePressureDifference to correct push/throw directions from tile-relative to physics world. - var gridWorldRotation = xforms.GetComponent(gridAtmosphere.Owner).WorldRotation; + var gridWorldRotation = xforms.GetComponent(gridAtmosphere).WorldRotation; // If we're using monstermos, smooth out the yeet direction to follow the flow if (MonstermosEqualization) @@ -151,12 +153,12 @@ namespace Content.Server.Atmos.EntitySystems if (_containers.IsEntityInContainer(entity, metas.GetComponent(entity))) continue; var pressureMovements = EnsureComp(entity); - if (pressure.LastHighPressureMovementAirCycle < gridAtmosphere.UpdateCounter) + if (pressure.LastHighPressureMovementAirCycle < gridAtmosphere.Comp.UpdateCounter) { // tl;dr YEET ExperiencePressureDifference( - pressureMovements, - gridAtmosphere.UpdateCounter, + (entity, pressureMovements), + gridAtmosphere.Comp.UpdateCounter, tile.PressureDifference, tile.PressureDirection, 0, tile.PressureSpecificTarget?.GridIndices.ToEntityCoordinates(tile.GridIndex, _mapManager) ?? EntityCoordinates.Invalid, @@ -180,7 +182,7 @@ namespace Content.Server.Atmos.EntitySystems } public void ExperiencePressureDifference( - MovedByPressureComponent component, + Entity ent, int cycle, float pressureDifference, AtmosDirection direction, @@ -190,12 +192,12 @@ namespace Content.Server.Atmos.EntitySystems TransformComponent? xform = null, PhysicsComponent? physics = null) { - var uid = component.Owner; - + var (uid, component) = ent; if (!Resolve(uid, ref physics, false)) return; - if (!Resolve(uid, ref xform)) return; + if (!Resolve(uid, ref xform)) + return; // TODO ATMOS stuns? diff --git a/Content.Server/Atmos/EntitySystems/AtmosphereSystem.Monstermos.cs b/Content.Server/Atmos/EntitySystems/AtmosphereSystem.Monstermos.cs index c7191b2779..aceda3cd33 100644 --- a/Content.Server/Atmos/EntitySystems/AtmosphereSystem.Monstermos.cs +++ b/Content.Server/Atmos/EntitySystems/AtmosphereSystem.Monstermos.cs @@ -1,16 +1,15 @@ +using System.Linq; +using System.Numerics; using Content.Server.Atmos.Components; using Content.Server.Doors.Systems; -using Content.Shared.Doors.Components; using Content.Shared.Atmos; using Content.Shared.Atmos.Components; using Content.Shared.Database; -using Robust.Shared.Map; +using Content.Shared.Doors.Components; using Robust.Shared.Map.Components; using Robust.Shared.Physics.Components; using Robust.Shared.Random; using Robust.Shared.Utility; -using System.Linq; -using System.Numerics; namespace Content.Server.Atmos.EntitySystems { @@ -28,7 +27,7 @@ namespace Content.Server.Atmos.EntitySystems private readonly TileAtmosphere[] _depressurizeSpaceTiles = new TileAtmosphere[Atmospherics.MonstermosHardTileLimit]; private readonly TileAtmosphere[] _depressurizeProgressionOrder = new TileAtmosphere[Atmospherics.MonstermosHardTileLimit * 2]; - private void EqualizePressureInZone(MapGridComponent mapGrid, GridAtmosphereComponent gridAtmosphere, TileAtmosphere tile, int cycleNum, GasTileOverlayComponent? visuals) + private void EqualizePressureInZone(Entity ent, TileAtmosphere tile, int cycleNum, GasTileOverlayComponent? visuals) { if (tile.Air == null || (tile.MonstermosInfo.LastCycle >= cycleNum)) return; // Already done. @@ -57,6 +56,7 @@ namespace Content.Server.Atmos.EntitySystems return; } + var (_, mapGrid, gridAtmosphere) = ent; var queueCycle = ++gridAtmosphere.EqualizationQueueCycleControl; var totalMoles = 0f; _equalizeTiles[0] = tile; @@ -91,7 +91,7 @@ namespace Content.Server.Atmos.EntitySystems { // Looks like someone opened an airlock to space! - ExplosivelyDepressurize(mapGrid, gridAtmosphere, tile, cycleNum, visuals); + ExplosivelyDepressurize(ent, tile, cycleNum, visuals); return; } } @@ -359,7 +359,7 @@ namespace Content.Server.Atmos.EntitySystems Array.Clear(_equalizeQueue, 0, Atmospherics.MonstermosTileLimit); } - private void ExplosivelyDepressurize(MapGridComponent mapGrid, GridAtmosphereComponent gridAtmosphere, TileAtmosphere tile, int cycleNum, GasTileOverlayComponent? visuals) + private void ExplosivelyDepressurize(Entity ent, TileAtmosphere tile, int cycleNum, GasTileOverlayComponent? visuals) { // Check if explosive depressurization is enabled and if the tile is valid. if (!MonstermosDepressurization || tile.Air == null) @@ -368,6 +368,7 @@ namespace Content.Server.Atmos.EntitySystems const int limit = Atmospherics.MonstermosHardTileLimit; var totalMolesRemoved = 0f; + var (owner, mapGrid, gridAtmosphere) = ent; var queueCycle = ++gridAtmosphere.EqualizationQueueCycleControl; var tileCount = 0; @@ -394,7 +395,7 @@ namespace Content.Server.Atmos.EntitySystems DebugTools.Assert(otherTile2.AdjacentBits.IsFlagSet(direction.GetOpposite())); if (otherTile2.MonstermosInfo.LastQueueCycle == queueCycle) continue; - ConsiderFirelocks(gridAtmosphere, otherTile, otherTile2, visuals, mapGrid); + ConsiderFirelocks((owner, gridAtmosphere), otherTile, otherTile2, visuals, mapGrid); // The firelocks might have closed on us. if (!otherTile.AdjacentBits.IsFlagSet(direction)) continue; @@ -527,11 +528,11 @@ namespace Content.Server.Atmos.EntitySystems { var direction = ((Vector2)_depressurizeTiles[tileCount - 1].GridIndices - tile.GridIndices).Normalized(); - var gridPhysics = Comp(mapGrid.Owner); + var gridPhysics = Comp(owner); // TODO ATMOS: Come up with better values for these. - _physics.ApplyLinearImpulse(mapGrid.Owner, direction * totalMolesRemoved * gridPhysics.Mass, body: gridPhysics); - _physics.ApplyAngularImpulse(mapGrid.Owner, Vector2Helpers.Cross(tile.GridIndices - gridPhysics.LocalCenter, direction) * totalMolesRemoved, body: gridPhysics); + _physics.ApplyLinearImpulse(owner, direction * totalMolesRemoved * gridPhysics.Mass, body: gridPhysics); + _physics.ApplyAngularImpulse(owner, Vector2Helpers.Cross(tile.GridIndices - gridPhysics.LocalCenter, direction) * totalMolesRemoved, body: gridPhysics); } if(tileCount > 10 && (totalMolesRemoved / tileCount) > 10) @@ -543,7 +544,7 @@ namespace Content.Server.Atmos.EntitySystems Array.Clear(_depressurizeProgressionOrder, 0, Atmospherics.MonstermosHardTileLimit * 2); } - private void ConsiderFirelocks(GridAtmosphereComponent gridAtmosphere, TileAtmosphere tile, TileAtmosphere other, GasTileOverlayComponent? visuals, MapGridComponent mapGrid) + private void ConsiderFirelocks(Entity ent, TileAtmosphere tile, TileAtmosphere other, GasTileOverlayComponent? visuals, MapGridComponent mapGrid) { var reconsiderAdjacent = false; @@ -566,10 +567,11 @@ namespace Content.Server.Atmos.EntitySystems if (!reconsiderAdjacent) return; - var tileEv = new UpdateAdjacentMethodEvent(mapGrid.Owner, tile.GridIndices); - var otherEv = new UpdateAdjacentMethodEvent(mapGrid.Owner, other.GridIndices); - GridUpdateAdjacent(mapGrid.Owner, gridAtmosphere, ref tileEv); - GridUpdateAdjacent(mapGrid.Owner, gridAtmosphere, ref otherEv); + var (owner, gridAtmosphere) = ent; + var tileEv = new UpdateAdjacentMethodEvent(owner, tile.GridIndices); + var otherEv = new UpdateAdjacentMethodEvent(owner, other.GridIndices); + GridUpdateAdjacent(owner, gridAtmosphere, ref tileEv); + GridUpdateAdjacent(owner, gridAtmosphere, ref otherEv); InvalidateVisuals(tile.GridIndex, tile.GridIndices, visuals); InvalidateVisuals(other.GridIndex, other.GridIndices, visuals); } diff --git a/Content.Server/Atmos/EntitySystems/AtmosphereSystem.Processing.cs b/Content.Server/Atmos/EntitySystems/AtmosphereSystem.Processing.cs index 38b66a73fa..6499291495 100644 --- a/Content.Server/Atmos/EntitySystems/AtmosphereSystem.Processing.cs +++ b/Content.Server/Atmos/EntitySystems/AtmosphereSystem.Processing.cs @@ -26,50 +26,49 @@ namespace Content.Server.Atmos.EntitySystems /// private const int InvalidCoordinatesLagCheckIterations = 50; - private int _currentRunAtmosphereIndex = 0; - private bool _simulationPaused = false; + private int _currentRunAtmosphereIndex; + private bool _simulationPaused; - private readonly List _currentRunAtmosphere = new(); + private readonly List> _currentRunAtmosphere = new(); /// /// Revalidates all invalid coordinates in a grid atmosphere. /// - /// The grid atmosphere in question. + /// The grid atmosphere in question. /// Whether the process succeeded or got paused due to time constrains. - private bool ProcessRevalidate(GridAtmosphereComponent atmosphere, GasTileOverlayComponent? visuals) + private bool ProcessRevalidate(Entity ent, GasTileOverlayComponent? visuals) { + var (owner, atmosphere) = ent; if (!atmosphere.ProcessingPaused) { atmosphere.CurrentRunInvalidatedCoordinates = new Queue(atmosphere.InvalidatedCoords); atmosphere.InvalidatedCoords.Clear(); } - var uid = atmosphere.Owner; - - if (!TryComp(uid, out MapGridComponent? mapGridComp)) + if (!TryComp(owner, out MapGridComponent? mapGridComp)) return true; - var mapUid = _mapManager.GetMapEntityIdOrThrow(Transform(mapGridComp.Owner).MapID); + var mapUid = _mapManager.GetMapEntityIdOrThrow(Transform(owner).MapID); - var volume = GetVolumeForTiles(mapGridComp, 1); + var volume = GetVolumeForTiles(mapGridComp); var number = 0; while (atmosphere.CurrentRunInvalidatedCoordinates.TryDequeue(out var indices)) { if (!atmosphere.Tiles.TryGetValue(indices, out var tile)) { - tile = new TileAtmosphere(mapGridComp.Owner, indices, + tile = new TileAtmosphere(owner, indices, new GasMixture(volume) { Temperature = Atmospherics.T20C }); atmosphere.Tiles[indices] = tile; } - var airBlockedEv = new IsTileAirBlockedMethodEvent(uid, indices, MapGridComponent:mapGridComp); - GridIsTileAirBlocked(uid, atmosphere, ref airBlockedEv); + var airBlockedEv = new IsTileAirBlockedMethodEvent(owner, indices, MapGridComponent:mapGridComp); + GridIsTileAirBlocked(owner, atmosphere, ref airBlockedEv); var isAirBlocked = airBlockedEv.Result; var oldBlocked = tile.BlockedAirflow; - var updateAdjacentEv = new UpdateAdjacentMethodEvent(uid, indices, mapGridComp); - GridUpdateAdjacent(uid, atmosphere, ref updateAdjacentEv); + var updateAdjacentEv = new UpdateAdjacentMethodEvent(owner, indices, mapGridComp); + GridUpdateAdjacent(owner, atmosphere, ref updateAdjacentEv); // Blocked airflow changed, rebuild excited groups! if (tile.Excited && tile.BlockedAirflow != oldBlocked) @@ -99,8 +98,8 @@ namespace Content.Server.Atmos.EntitySystems { if (tile.Air == null && NeedsVacuumFixing(mapGridComp, indices)) { - var vacuumEv = new FixTileVacuumMethodEvent(uid, indices); - GridFixTileVacuum(uid, atmosphere, ref vacuumEv); + var vacuumEv = new FixTileVacuumMethodEvent(owner, indices); + GridFixTileVacuum(owner, atmosphere, ref vacuumEv); } // Tile used to be space, but isn't anymore. @@ -122,11 +121,12 @@ namespace Content.Server.Atmos.EntitySystems // TODO ATMOS: Query all the contents of this tile (like walls) and calculate the correct thermal conductivity and heat capacity var tileDef = mapGridComp.TryGetTileRef(indices, out var tileRef) - ? tileRef.GetContentTileDefinition(_tileDefinitionManager) : null; + ? tileRef.GetContentTileDefinition(_tileDefinitionManager) + : null; tile.ThermalConductivity = tileDef?.ThermalConductivity ?? 0.5f; tile.HeatCapacity = tileDef?.HeatCapacity ?? float.PositiveInfinity; - InvalidateVisuals(mapGridComp.Owner, indices, visuals); + InvalidateVisuals(owner, indices, visuals); for (var i = 0; i < Atmospherics.Directions; i++) { @@ -137,7 +137,9 @@ namespace Content.Server.Atmos.EntitySystems AddActiveTile(atmosphere, otherTile); } - if (number++ < InvalidCoordinatesLagCheckIterations) continue; + if (number++ < InvalidCoordinatesLagCheckIterations) + continue; + number = 0; // Process the rest next time. if (_simulationStopwatch.Elapsed.TotalMilliseconds >= AtmosMaxProcessTime) @@ -149,22 +151,23 @@ namespace Content.Server.Atmos.EntitySystems return true; } - private bool ProcessTileEqualize(GridAtmosphereComponent atmosphere, GasTileOverlayComponent? visuals) + private bool ProcessTileEqualize(Entity ent, GasTileOverlayComponent? visuals) { - if(!atmosphere.ProcessingPaused) + var (uid, atmosphere) = ent; + if (!atmosphere.ProcessingPaused) atmosphere.CurrentRunTiles = new Queue(atmosphere.ActiveTiles); - var uid = atmosphere.Owner; - if (!TryComp(uid, out MapGridComponent? mapGridComp)) throw new Exception("Tried to process a grid atmosphere on an entity that isn't a grid!"); var number = 0; while (atmosphere.CurrentRunTiles.TryDequeue(out var tile)) { - EqualizePressureInZone(mapGridComp, atmosphere, tile, atmosphere.UpdateCounter, visuals); + EqualizePressureInZone((uid, mapGridComp, atmosphere), tile, atmosphere.UpdateCounter, visuals); + + if (number++ < LagCheckIterations) + continue; - if (number++ < LagCheckIterations) continue; number = 0; // Process the rest next time. if (_simulationStopwatch.Elapsed.TotalMilliseconds >= AtmosMaxProcessTime) @@ -186,7 +189,9 @@ namespace Content.Server.Atmos.EntitySystems { ProcessCell(atmosphere, tile, atmosphere.UpdateCounter, visuals); - if (number++ < LagCheckIterations) continue; + if (number++ < LagCheckIterations) + continue; + number = 0; // Process the rest next time. if (_simulationStopwatch.Elapsed.TotalMilliseconds >= AtmosMaxProcessTime) @@ -215,7 +220,9 @@ namespace Content.Server.Atmos.EntitySystems else if(excitedGroup.DismantleCooldown > Atmospherics.ExcitedGroupsDismantleCycles) ExcitedGroupDismantle(gridAtmosphere, excitedGroup); - if (number++ < LagCheckIterations) continue; + if (number++ < LagCheckIterations) + continue; + number = 0; // Process the rest next time. if (_simulationStopwatch.Elapsed.TotalMilliseconds >= AtmosMaxProcessTime) @@ -227,9 +234,10 @@ namespace Content.Server.Atmos.EntitySystems return true; } - private bool ProcessHighPressureDelta(GridAtmosphereComponent atmosphere) + private bool ProcessHighPressureDelta(Entity ent) { - if(!atmosphere.ProcessingPaused) + var atmosphere = ent.Comp; + if (!atmosphere.ProcessingPaused) atmosphere.CurrentRunTiles = new Queue(atmosphere.HighPressureDelta); // Note: This is still processed even if space wind is turned off since this handles playing the sounds. @@ -242,14 +250,15 @@ namespace Content.Server.Atmos.EntitySystems while (atmosphere.CurrentRunTiles.TryDequeue(out var tile)) { - HighPressureMovements(atmosphere, tile, bodies, xforms, pressureQuery, metas); + HighPressureMovements(ent, tile, bodies, xforms, pressureQuery, metas); tile.PressureDifference = 0f; tile.LastPressureDirection = tile.PressureDirection; tile.PressureDirection = AtmosDirection.Invalid; tile.PressureSpecificTarget = null; atmosphere.HighPressureDelta.Remove(tile); - if (number++ < LagCheckIterations) continue; + if (number++ < LagCheckIterations) + continue; number = 0; // Process the rest next time. if (_simulationStopwatch.Elapsed.TotalMilliseconds >= AtmosMaxProcessTime) @@ -271,7 +280,9 @@ namespace Content.Server.Atmos.EntitySystems { ProcessHotspot(atmosphere, hotspot); - if (number++ < LagCheckIterations) continue; + if (number++ < LagCheckIterations) + continue; + number = 0; // Process the rest next time. if (_simulationStopwatch.Elapsed.TotalMilliseconds >= AtmosMaxProcessTime) @@ -293,7 +304,9 @@ namespace Content.Server.Atmos.EntitySystems { Superconduct(atmosphere, superconductivity); - if (number++ < LagCheckIterations) continue; + if (number++ < LagCheckIterations) + continue; + number = 0; // Process the rest next time. if (_simulationStopwatch.Elapsed.TotalMilliseconds >= AtmosMaxProcessTime) @@ -315,7 +328,9 @@ namespace Content.Server.Atmos.EntitySystems { pipenet.Update(); - if (number++ < LagCheckIterations) continue; + if (number++ < LagCheckIterations) + continue; + number = 0; // Process the rest next time. if (_simulationStopwatch.Elapsed.TotalMilliseconds >= AtmosMaxProcessTime) @@ -346,17 +361,19 @@ namespace Content.Server.Atmos.EntitySystems private bool ProcessAtmosDevices(GridAtmosphereComponent atmosphere) { - if(!atmosphere.ProcessingPaused) - atmosphere.CurrentRunAtmosDevices = new Queue(atmosphere.AtmosDevices); + if (!atmosphere.ProcessingPaused) + atmosphere.CurrentRunAtmosDevices = new Queue>(atmosphere.AtmosDevices); var time = _gameTiming.CurTime; var number = 0; while (atmosphere.CurrentRunAtmosDevices.TryDequeue(out var device)) { - RaiseLocalEvent(device.Owner, new AtmosDeviceUpdateEvent(RealAtmosTime()), false); - device.LastProcess = time; + RaiseLocalEvent(device, new AtmosDeviceUpdateEvent(RealAtmosTime())); + device.Comp.LastProcess = time; + + if (number++ < LagCheckIterations) + continue; - if (number++ < LagCheckIterations) continue; number = 0; // Process the rest next time. if (_simulationStopwatch.Elapsed.TotalMilliseconds >= AtmosMaxProcessTime) @@ -376,7 +393,12 @@ namespace Content.Server.Atmos.EntitySystems { _currentRunAtmosphereIndex = 0; _currentRunAtmosphere.Clear(); - _currentRunAtmosphere.AddRange(EntityManager.EntityQuery()); + + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var grid)) + { + _currentRunAtmosphere.Add((uid, grid)); + } } // We set this to true just in case we have to stop processing due to time constraints. @@ -384,10 +406,11 @@ namespace Content.Server.Atmos.EntitySystems for (; _currentRunAtmosphereIndex < _currentRunAtmosphere.Count; _currentRunAtmosphereIndex++) { - var atmosphere = _currentRunAtmosphere[_currentRunAtmosphereIndex]; - TryComp(atmosphere.Owner, out GasTileOverlayComponent? visuals); + var ent = _currentRunAtmosphere[_currentRunAtmosphereIndex]; + var (owner, atmosphere) = ent; + TryComp(owner, out GasTileOverlayComponent? visuals); - if (atmosphere.LifeStage >= ComponentLifeStage.Stopping || Paused(atmosphere.Owner) || !atmosphere.Simulated) + if (atmosphere.LifeStage >= ComponentLifeStage.Stopping || Paused(owner) || !atmosphere.Simulated) continue; atmosphere.Timer += frameTime; @@ -401,7 +424,7 @@ namespace Content.Server.Atmos.EntitySystems switch (atmosphere.State) { case AtmosphereProcessingState.Revalidate: - if (!ProcessRevalidate(atmosphere, visuals)) + if (!ProcessRevalidate(ent, visuals)) { atmosphere.ProcessingPaused = true; return; @@ -416,7 +439,7 @@ namespace Content.Server.Atmos.EntitySystems : AtmosphereProcessingState.ActiveTiles; continue; case AtmosphereProcessingState.TileEqualize: - if (!ProcessTileEqualize(atmosphere, visuals)) + if (!ProcessTileEqualize(ent, visuals)) { atmosphere.ProcessingPaused = true; return; @@ -447,7 +470,7 @@ namespace Content.Server.Atmos.EntitySystems atmosphere.State = AtmosphereProcessingState.HighPressureDelta; continue; case AtmosphereProcessingState.HighPressureDelta: - if (!ProcessHighPressureDelta(atmosphere)) + if (!ProcessHighPressureDelta(ent)) { atmosphere.ProcessingPaused = true; return; diff --git a/Content.Server/Atmos/EntitySystems/AtmosphereSystem.cs b/Content.Server/Atmos/EntitySystems/AtmosphereSystem.cs index 5d3e989e41..91634de8d7 100644 --- a/Content.Server/Atmos/EntitySystems/AtmosphereSystem.cs +++ b/Content.Server/Atmos/EntitySystems/AtmosphereSystem.cs @@ -4,7 +4,6 @@ using Content.Server.Body.Systems; using Content.Server.Maps; using Content.Server.NodeContainer.EntitySystems; using Content.Shared.Atmos.EntitySystems; -using Content.Shared.Maps; using JetBrains.Annotations; using Robust.Server.GameObjects; using Robust.Shared.Containers; @@ -76,15 +75,16 @@ public sealed partial class AtmosphereSystem : SharedAtmosphereSystem if (_exposedTimer < ExposedUpdateDelay) return; - foreach (var (exposed, transform) in EntityManager.EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var exposed, out var transform)) { - var air = GetContainingMixture(exposed.Owner, transform:transform); + var air = GetContainingMixture(uid, transform:transform); if (air == null) continue; var updateEvent = new AtmosExposedUpdateEvent(transform.Coordinates, air, transform); - RaiseLocalEvent(exposed.Owner, ref updateEvent); + RaiseLocalEvent(uid, ref updateEvent); } _exposedTimer -= ExposedUpdateDelay; diff --git a/Content.Server/Atmos/EntitySystems/FlammableSystem.cs b/Content.Server/Atmos/EntitySystems/FlammableSystem.cs index b2f62572bf..be3e5cd934 100644 --- a/Content.Server/Atmos/EntitySystems/FlammableSystem.cs +++ b/Content.Server/Atmos/EntitySystems/FlammableSystem.cs @@ -16,9 +16,7 @@ using Content.Shared.Temperature; using Content.Shared.Throwing; using Content.Shared.Weapons.Melee.Events; using Robust.Server.GameObjects; -using Robust.Shared.Physics; using Robust.Shared.Physics.Components; -using Robust.Shared.Physics.Dynamics; using Robust.Shared.Physics.Events; using Robust.Shared.Physics.Systems; @@ -48,7 +46,7 @@ namespace Content.Server.Atmos.EntitySystems private float _timer; - private Dictionary _fireEvents = new(); + private readonly Dictionary, float> _fireEvents = new(); public override void Initialize() { @@ -188,14 +186,14 @@ namespace Content.Server.Atmos.EntitySystems args.IsHot = flammable.OnFire; } - private void OnTileFire(EntityUid uid, FlammableComponent flammable, ref TileFireEvent args) + private void OnTileFire(Entity ent, ref TileFireEvent args) { var tempDelta = args.Temperature - MinIgnitionTemperature; - _fireEvents.TryGetValue(flammable, out var maxTemp); + _fireEvents.TryGetValue(ent, out var maxTemp); if (tempDelta > maxTemp) - _fireEvents[flammable] = tempDelta; + _fireEvents[ent] = tempDelta; } private void OnRejuvenate(EntityUid uid, FlammableComponent component, RejuvenateEvent args) @@ -295,7 +293,7 @@ namespace Content.Server.Atmos.EntitySystems { // 100 -> 1, 200 -> 2, 400 -> 3... var fireStackMod = Math.Max(MathF.Log2(deltaTemp / 100) + 1, 0); - var fireStackDelta = fireStackMod - flammable.FireStacks; + var fireStackDelta = fireStackMod - flammable.Comp.FireStacks; var flammableEntity = flammable.Owner; if (fireStackDelta > 0) { @@ -313,10 +311,9 @@ namespace Content.Server.Atmos.EntitySystems _timer -= UpdateTime; // TODO: This needs cleanup to take off the crust from TemperatureComponent and shit. - foreach (var (flammable, transform) in EntityManager.EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var flammable, out var transform)) { - var uid = flammable.Owner; - // Slowly dry ourselves off if wet. if (flammable.FireStacks < 0) { diff --git a/Content.Server/Atmos/EntitySystems/GasTankSystem.cs b/Content.Server/Atmos/EntitySystems/GasTankSystem.cs index 03286f08ab..df867d3516 100644 --- a/Content.Server/Atmos/EntitySystems/GasTankSystem.cs +++ b/Content.Server/Atmos/EntitySystems/GasTankSystem.cs @@ -53,31 +53,35 @@ namespace Content.Server.Atmos.EntitySystems SubscribeLocalEvent>(OnGetAlternativeVerb); } - private void OnGasShutdown(EntityUid uid, GasTankComponent component, ComponentShutdown args) + private void OnGasShutdown(Entity gasTank, ref ComponentShutdown args) { - DisconnectFromInternals(component); + DisconnectFromInternals(gasTank); } - private void OnGasTankToggleInternals(EntityUid uid, GasTankComponent component, GasTankToggleInternalsMessage args) + private void OnGasTankToggleInternals(Entity ent, ref GasTankToggleInternalsMessage args) { if (args.Session is not IPlayerSession playerSession || - playerSession.AttachedEntity is not {} player) return; + playerSession.AttachedEntity == null) + { + return; + } - ToggleInternals(component); + ToggleInternals(ent); } - private void OnGasTankSetPressure(EntityUid uid, GasTankComponent component, GasTankSetPressureMessage args) + private void OnGasTankSetPressure(Entity ent, ref GasTankSetPressureMessage args) { - var pressure = Math.Min(args.Pressure, component.MaxOutputPressure); + var pressure = Math.Min(args.Pressure, ent.Comp.MaxOutputPressure); - component.OutputPressure = pressure; + ent.Comp.OutputPressure = pressure; - UpdateUserInterface(component, true); + UpdateUserInterface(ent, true); } - public void UpdateUserInterface(GasTankComponent component, bool initialUpdate = false) + public void UpdateUserInterface(Entity ent, bool initialUpdate = false) { - _ui.TrySetUiState(component.Owner, SharedGasTankUiKey.Key, + var (owner, component) = ent; + _ui.TrySetUiState(owner, SharedGasTankUiKey.Key, new GasTankBoundUserInterfaceState { TankPressure = component.Air?.Pressure ?? 0, @@ -87,10 +91,10 @@ namespace Content.Server.Atmos.EntitySystems }); } - private void BeforeUiOpen(EntityUid uid, GasTankComponent component, BeforeActivatableUIOpenEvent args) + private void BeforeUiOpen(Entity ent, ref BeforeActivatableUIOpenEvent args) { // Only initial update includes output pressure information, to avoid overwriting client-input as the updates come in. - UpdateUserInterface(component, true); + UpdateUserInterface(ent, true); } private void OnParentChange(EntityUid uid, GasTankComponent component, ref EntParentChangedMessage args) @@ -115,12 +119,12 @@ namespace Content.Server.Atmos.EntitySystems args.PushMarkup(Loc.GetString(component.IsValveOpen ? "comp-gas-tank-examine-open-valve" : "comp-gas-tank-examine-closed-valve")); } - private void OnActionToggle(EntityUid uid, GasTankComponent component, ToggleActionEvent args) + private void OnActionToggle(Entity gasTank, ref ToggleActionEvent args) { if (args.Handled) return; - ToggleInternals(component); + ToggleInternals(gasTank); args.Handled = true; } @@ -130,30 +134,33 @@ namespace Content.Server.Atmos.EntitySystems _timer += frameTime; - if (_timer < TimerDelay) return; + if (_timer < TimerDelay) + return; + _timer -= TimerDelay; var query = EntityQueryEnumerator(); - while (query.MoveNext(out var uid, out var gasTank)) + while (query.MoveNext(out var uid, out var comp)) { - if (gasTank.IsValveOpen && !gasTank.IsLowPressure) + var gasTank = (uid, comp); + if (comp.IsValveOpen && !comp.IsLowPressure) { - ReleaseGas(uid, gasTank); + ReleaseGas(gasTank); } - if (gasTank.CheckUser) + if (comp.CheckUser) { - gasTank.CheckUser = false; - if (Transform(uid).ParentUid != gasTank.User) + comp.CheckUser = false; + if (Transform(uid).ParentUid != comp.User) { DisconnectFromInternals(gasTank); continue; } } - if (gasTank.Air != null) + if (comp.Air != null) { - _atmosphereSystem.React(gasTank.Air, gasTank); + _atmosphereSystem.React(comp.Air, comp); } CheckStatus(gasTank); if (_ui.IsUiOpen(uid, SharedGasTankUiKey.Key)) @@ -163,47 +170,48 @@ namespace Content.Server.Atmos.EntitySystems } } - private void ReleaseGas(EntityUid uid, GasTankComponent component) + private void ReleaseGas(Entity gasTank) { - var removed = RemoveAirVolume(component, component.ValveOutputRate * TimerDelay); - var environment = _atmosphereSystem.GetContainingMixture(uid, false, true); + var removed = RemoveAirVolume(gasTank, gasTank.Comp.ValveOutputRate * TimerDelay); + var environment = _atmosphereSystem.GetContainingMixture(gasTank, false, true); if (environment != null) { _atmosphereSystem.Merge(environment, removed); } var impulse = removed.TotalMoles * removed.Temperature; - _physics.ApplyLinearImpulse(uid, _random.NextAngle().ToWorldVec() * impulse); - _physics.ApplyAngularImpulse(uid, _random.NextFloat(-3f, 3f)); - _audioSys.PlayPvs(component.RuptureSound, uid); + _physics.ApplyLinearImpulse(gasTank, _random.NextAngle().ToWorldVec() * impulse); + _physics.ApplyAngularImpulse(gasTank, _random.NextFloat(-3f, 3f)); + _audioSys.PlayPvs(gasTank.Comp.RuptureSound, gasTank); } - private void ToggleInternals(GasTankComponent component) + private void ToggleInternals(Entity ent) { - if (component.IsConnected) + if (ent.Comp.IsConnected) { - DisconnectFromInternals(component); + DisconnectFromInternals(ent); } else { - ConnectToInternals(component); + ConnectToInternals(ent); } } - public GasMixture? RemoveAir(GasTankComponent component, float amount) + public GasMixture? RemoveAir(Entity gasTank, float amount) { - var gas = component.Air?.Remove(amount); - CheckStatus(component); + var gas = gasTank.Comp.Air?.Remove(amount); + CheckStatus(gasTank); return gas; } - public GasMixture RemoveAirVolume(GasTankComponent component, float volume) + public GasMixture RemoveAirVolume(Entity gasTank, float volume) { + var component = gasTank.Comp; if (component.Air == null) return new GasMixture(volume); var molesNeeded = component.OutputPressure * volume / (Atmospherics.R * component.Air.Temperature); - var air = RemoveAir(component, molesNeeded); + var air = RemoveAir(gasTank, molesNeeded); if (air != null) air.Volume = volume; @@ -215,12 +223,13 @@ namespace Content.Server.Atmos.EntitySystems public bool CanConnectToInternals(GasTankComponent component) { - var internals = GetInternalsComponent(component); + var internals = GetInternalsComponent(component, component.User); return internals != null && internals.BreathToolEntity != null && !component.IsValveOpen; } - public void ConnectToInternals(GasTankComponent component) + public void ConnectToInternals(Entity ent) { + var (owner, component) = ent; if (component.IsConnected || !CanConnectToInternals(component)) return; @@ -228,7 +237,7 @@ namespace Content.Server.Atmos.EntitySystems if (internals == null) return; - if (_internals.TryConnectTank(internals, component.Owner)) + if (_internals.TryConnectTank((internals.Owner, internals), owner)) component.User = internals.Owner; _actions.SetToggled(component.ToggleActionEntity, component.IsConnected); @@ -240,13 +249,14 @@ namespace Content.Server.Atmos.EntitySystems component.ConnectStream?.Stop(); if (component.ConnectSound != null) - component.ConnectStream = _audioSys.PlayPvs(component.ConnectSound, component.Owner); + component.ConnectStream = _audioSys.PlayPvs(component.ConnectSound, owner); - UpdateUserInterface(component); + UpdateUserInterface(ent); } - public void DisconnectFromInternals(GasTankComponent component) + public void DisconnectFromInternals(Entity ent) { + var (owner, component) = ent; if (component.User == null) return; @@ -259,29 +269,30 @@ namespace Content.Server.Atmos.EntitySystems component.DisconnectStream?.Stop(); if (component.DisconnectSound != null) - component.DisconnectStream = _audioSys.PlayPvs(component.DisconnectSound, component.Owner); + component.DisconnectStream = _audioSys.PlayPvs(component.DisconnectSound, owner); - UpdateUserInterface(component); + UpdateUserInterface(ent); } private InternalsComponent? GetInternalsComponent(GasTankComponent component, EntityUid? owner = null) { owner ??= component.User; - if (Deleted(component.Owner)) return null; + if (Deleted(component.Owner))return null; if (owner != null) return CompOrNull(owner.Value); return _containers.TryGetContainingContainer(component.Owner, out var container) ? CompOrNull(container.Owner) : null; } - public void AssumeAir(GasTankComponent component, GasMixture giver) + public void AssumeAir(Entity ent, GasMixture giver) { - _atmosphereSystem.Merge(component.Air, giver); - CheckStatus(component); + _atmosphereSystem.Merge(ent.Comp.Air, giver); + CheckStatus(ent); } - public void CheckStatus(GasTankComponent component) + public void CheckStatus(Entity ent) { + var (owner, component) = ent; if (component.Air == null) return; @@ -305,7 +316,7 @@ namespace Content.Server.Atmos.EntitySystems range = GasTankComponent.MaxExplosionRange; } - _explosions.TriggerExplosive(component.Owner, radius: range); + _explosions.TriggerExplosive(owner, radius: range); return; } @@ -314,13 +325,13 @@ namespace Content.Server.Atmos.EntitySystems { if (component.Integrity <= 0) { - var environment = _atmosphereSystem.GetContainingMixture(component.Owner, false, true); + var environment = _atmosphereSystem.GetContainingMixture(owner, false, true); if(environment != null) _atmosphereSystem.Merge(environment, component.Air); - _audioSys.Play(component.RuptureSound, Filter.Pvs(component.Owner), Transform(component.Owner).Coordinates, true, AudioParams.Default.WithVariation(0.125f)); + _audioSys.Play(component.RuptureSound, Filter.Pvs(owner), Transform(owner).Coordinates, true, AudioParams.Default.WithVariation(0.125f)); - QueueDel(component.Owner); + QueueDel(owner); return; } @@ -332,7 +343,7 @@ namespace Content.Server.Atmos.EntitySystems { if (component.Integrity <= 0) { - var environment = _atmosphereSystem.GetContainingMixture(component.Owner, false, true); + var environment = _atmosphereSystem.GetContainingMixture(owner, false, true); if (environment == null) return; diff --git a/Content.Server/Atmos/Monitor/Systems/AtmosMonitoringSystem.cs b/Content.Server/Atmos/Monitor/Systems/AtmosMonitoringSystem.cs index c7995f4ae6..efd67550ba 100644 --- a/Content.Server/Atmos/Monitor/Systems/AtmosMonitoringSystem.cs +++ b/Content.Server/Atmos/Monitor/Systems/AtmosMonitoringSystem.cs @@ -1,8 +1,7 @@ -using System.Linq; -using Content.Server.Atmos.Monitor.Components; using Content.Server.Atmos.EntitySystems; -using Content.Server.Atmos.Piping.EntitySystems; +using Content.Server.Atmos.Monitor.Components; using Content.Server.Atmos.Piping.Components; +using Content.Server.Atmos.Piping.EntitySystems; using Content.Server.DeviceNetwork; using Content.Server.DeviceNetwork.Systems; using Content.Server.Power.Components; @@ -87,7 +86,7 @@ public sealed class AtmosMonitorSystem : EntitySystem if (!HasComp(uid) && TryComp(uid, out var atmosDeviceComponent)) { - _atmosDeviceSystem.LeaveAtmosphere(atmosDeviceComponent); + _atmosDeviceSystem.LeaveAtmosphere((uid, atmosDeviceComponent)); } } @@ -155,18 +154,18 @@ public sealed class AtmosMonitorSystem : EntitySystem } } - private void OnPowerChangedEvent(EntityUid uid, AtmosMonitorComponent component, ref PowerChangedEvent args) + private void OnPowerChangedEvent(Entity ent, ref PowerChangedEvent args) { - if (TryComp(uid, out var atmosDeviceComponent)) + if (TryComp(ent, out var atmosDeviceComponent)) { if (!args.Powered) { - _atmosDeviceSystem.LeaveAtmosphere(atmosDeviceComponent); + _atmosDeviceSystem.LeaveAtmosphere((ent, atmosDeviceComponent)); } else { - _atmosDeviceSystem.JoinAtmosphere(atmosDeviceComponent); - Alert(uid, component.LastAlarmState); + _atmosDeviceSystem.JoinAtmosphere((ent, atmosDeviceComponent)); + Alert(ent, ent.Comp.LastAlarmState); } } } @@ -305,12 +304,13 @@ public sealed class AtmosMonitorSystem : EntitySystem /// The alarms that caused this alarm state. public void Alert(EntityUid uid, AtmosAlarmType state, HashSet? alarms = null, AtmosMonitorComponent? monitor = null) { - if (!Resolve(uid, ref monitor)) return; + if (!Resolve(uid, ref monitor)) + return; monitor.LastAlarmState = state; monitor.TrippedThresholds = alarms ?? monitor.TrippedThresholds; - BroadcastAlertPacket(monitor); + BroadcastAlertPacket((uid, monitor)); // TODO: Central system that grabs *all* alarms from wired network } @@ -336,11 +336,13 @@ public sealed class AtmosMonitorSystem : EntitySystem /// is synced between monitors the moment a monitor sends out an alarm, /// or if it is explicitly synced (see ResetAll/Sync). /// - private void BroadcastAlertPacket(AtmosMonitorComponent monitor, TagComponent? tags = null) + private void BroadcastAlertPacket(Entity ent, TagComponent? tags = null) { - if (!monitor.NetEnabled) return; + var (owner, monitor) = ent; + if (!monitor.NetEnabled) + return; - if (!Resolve(monitor.Owner, ref tags, false)) + if (!Resolve(owner, ref tags, false)) { return; } @@ -355,7 +357,7 @@ public sealed class AtmosMonitorSystem : EntitySystem foreach (var addr in monitor.RegisteredDevices) { - _deviceNetSystem.QueuePacket(monitor.Owner, addr, payload); + _deviceNetSystem.QueuePacket(owner, addr, payload); } } @@ -367,7 +369,8 @@ public sealed class AtmosMonitorSystem : EntitySystem /// Gas, if applicable. public void SetThreshold(EntityUid uid, AtmosMonitorThresholdType type, AtmosAlarmThreshold threshold, Gas? gas = null, AtmosMonitorComponent? monitor = null) { - if (!Resolve(uid, ref monitor)) return; + if (!Resolve(uid, ref monitor)) + return; switch (type) { @@ -378,7 +381,8 @@ public sealed class AtmosMonitorSystem : EntitySystem monitor.TemperatureThreshold = threshold; break; case AtmosMonitorThresholdType.Gas: - if (gas == null || monitor.GasThresholds == null) return; + if (gas == null || monitor.GasThresholds == null) + return; monitor.GasThresholds[(Gas) gas] = threshold; break; } diff --git a/Content.Server/Atmos/Piping/Binary/EntitySystems/GasPassiveGateSystem.cs b/Content.Server/Atmos/Piping/Binary/EntitySystems/GasPassiveGateSystem.cs index d2326b2b56..9b37aaaf3e 100644 --- a/Content.Server/Atmos/Piping/Binary/EntitySystems/GasPassiveGateSystem.cs +++ b/Content.Server/Atmos/Piping/Binary/EntitySystems/GasPassiveGateSystem.cs @@ -79,12 +79,12 @@ namespace Content.Server.Atmos.Piping.Binary.EntitySystems gate.FlowRate = a*dV/tau + (1-a)*gate.FlowRate; // in L/sec } - private void OnExamined(EntityUid uid, GasPassiveGateComponent gate, ExaminedEvent args) + private void OnExamined(Entity gate, ref ExaminedEvent args) { - if (!EntityManager.GetComponent(gate.Owner).Anchored || !args.IsInDetailsRange) // Not anchored? Out of range? No status. + if (!Comp(gate).Anchored || !args.IsInDetailsRange) // Not anchored? Out of range? No status. return; - var str = Loc.GetString("gas-passive-gate-examined", ("flowRate", $"{gate.FlowRate:0.#}")); + var str = Loc.GetString("gas-passive-gate-examined", ("flowRate", $"{gate.Comp.FlowRate:0.#}")); args.PushMarkup(str); } } diff --git a/Content.Server/Atmos/Piping/Binary/EntitySystems/GasRecyclerSystem.cs b/Content.Server/Atmos/Piping/Binary/EntitySystems/GasRecyclerSystem.cs index 26000d50cf..359123aabf 100644 --- a/Content.Server/Atmos/Piping/Binary/EntitySystems/GasRecyclerSystem.cs +++ b/Content.Server/Atmos/Piping/Binary/EntitySystems/GasRecyclerSystem.cs @@ -1,5 +1,4 @@ using Content.Server.Atmos.EntitySystems; -using Content.Shared.Atmos.Piping; using Content.Server.Atmos.Piping.Binary.Components; using Content.Server.Atmos.Piping.Components; using Content.Server.Construction; @@ -7,6 +6,7 @@ using Content.Server.NodeContainer; using Content.Server.NodeContainer.EntitySystems; using Content.Server.NodeContainer.Nodes; using Content.Shared.Atmos; +using Content.Shared.Atmos.Piping; using Content.Shared.Audio; using Content.Shared.Examine; using JetBrains.Annotations; @@ -38,12 +38,13 @@ namespace Content.Server.Atmos.Piping.Binary.EntitySystems UpdateAppearance(uid, comp); } - private void OnExamined(EntityUid uid, GasRecyclerComponent comp, ExaminedEvent args) + private void OnExamined(Entity ent, ref ExaminedEvent args) { - if (!EntityManager.GetComponent(comp.Owner).Anchored || !args.IsInDetailsRange) // Not anchored? Out of range? No status. + var comp = ent.Comp; + if (!EntityManager.GetComponent(ent).Anchored || !args.IsInDetailsRange) // Not anchored? Out of range? No status. return; - if (!EntityManager.TryGetComponent(uid, out NodeContainerComponent? nodeContainer) + if (!EntityManager.TryGetComponent(ent, out NodeContainerComponent? nodeContainer) || !_nodeContainer.TryGetNode(nodeContainer, comp.InletName, out PipeNode? inlet) || !_nodeContainer.TryGetNode(nodeContainer, comp.OutletName, out PipeNode? _)) { @@ -68,13 +69,14 @@ namespace Content.Server.Atmos.Piping.Binary.EntitySystems } } - private void OnUpdate(EntityUid uid, GasRecyclerComponent comp, AtmosDeviceUpdateEvent args) + private void OnUpdate(Entity ent, ref AtmosDeviceUpdateEvent args) { - if (!EntityManager.TryGetComponent(uid, out NodeContainerComponent? nodeContainer) + var comp = ent.Comp; + if (!EntityManager.TryGetComponent(ent, out NodeContainerComponent? nodeContainer) || !_nodeContainer.TryGetNode(nodeContainer, comp.InletName, out PipeNode? inlet) || !_nodeContainer.TryGetNode(nodeContainer, comp.OutletName, out PipeNode? outlet)) { - _ambientSoundSystem.SetAmbience(comp.Owner, false); + _ambientSoundSystem.SetAmbience(ent, false); return; } @@ -92,8 +94,8 @@ namespace Content.Server.Atmos.Piping.Binary.EntitySystems } _atmosphereSystem.Merge(outlet.Air, removed); - UpdateAppearance(uid, comp); - _ambientSoundSystem.SetAmbience(comp.Owner, true); + UpdateAppearance(ent, comp); + _ambientSoundSystem.SetAmbience(ent, true); } public float PassiveTransferVol(GasMixture inlet, GasMixture outlet) diff --git a/Content.Server/Atmos/Piping/Binary/EntitySystems/GasValveSystem.cs b/Content.Server/Atmos/Piping/Binary/EntitySystems/GasValveSystem.cs index ceabee689d..914e732991 100644 --- a/Content.Server/Atmos/Piping/Binary/EntitySystems/GasValveSystem.cs +++ b/Content.Server/Atmos/Piping/Binary/EntitySystems/GasValveSystem.cs @@ -7,7 +7,6 @@ using Content.Shared.Audio; using Content.Shared.Examine; using Content.Shared.Interaction; using JetBrains.Annotations; -using Robust.Server.GameObjects; using Robust.Shared.Audio; using Robust.Shared.Player; @@ -29,9 +28,10 @@ namespace Content.Server.Atmos.Piping.Binary.EntitySystems SubscribeLocalEvent(OnExamined); } - private void OnExamined(EntityUid uid, GasValveComponent valve, ExaminedEvent args) + private void OnExamined(Entity ent, ref ExaminedEvent args) { - if (!Comp(valve.Owner).Anchored || !args.IsInDetailsRange) // Not anchored? Out of range? No status. + var valve = ent.Comp; + if (!Comp(ent).Anchored || !args.IsInDetailsRange) // Not anchored? Out of range? No status. return; if (Loc.TryGetString("gas-valve-system-examined", out var str, @@ -50,7 +50,7 @@ namespace Content.Server.Atmos.Piping.Binary.EntitySystems private void OnActivate(EntityUid uid, GasValveComponent component, ActivateInWorldEvent args) { Toggle(uid, component); - SoundSystem.Play(component.ValveSound.GetSound(), Filter.Pvs(component.Owner), component.Owner, AudioHelpers.WithVariation(0.25f)); + SoundSystem.Play(component.ValveSound.GetSound(), Filter.Pvs(uid), uid, AudioHelpers.WithVariation(0.25f)); } public void Set(EntityUid uid, GasValveComponent component, bool value) @@ -60,7 +60,7 @@ namespace Content.Server.Atmos.Piping.Binary.EntitySystems && _nodeContainer.TryGetNode(nodeContainer, component.InletName, out PipeNode? inlet) && _nodeContainer.TryGetNode(nodeContainer, component.OutletName, out PipeNode? outlet)) { - if (TryComp(component.Owner,out var appearance)) + if (TryComp(uid, out var appearance)) { _appearance.SetData(uid, FilterVisuals.Enabled, component.Open, appearance); } @@ -68,13 +68,13 @@ namespace Content.Server.Atmos.Piping.Binary.EntitySystems { inlet.AddAlwaysReachable(outlet); outlet.AddAlwaysReachable(inlet); - _ambientSoundSystem.SetAmbience(component.Owner, true); + _ambientSoundSystem.SetAmbience(uid, true); } else { inlet.RemoveAlwaysReachable(outlet); outlet.RemoveAlwaysReachable(inlet); - _ambientSoundSystem.SetAmbience(component.Owner, false); + _ambientSoundSystem.SetAmbience(uid, false); } } } diff --git a/Content.Server/Atmos/Piping/EntitySystems/AtmosDeviceSystem.cs b/Content.Server/Atmos/Piping/EntitySystems/AtmosDeviceSystem.cs index a3f5f2113f..ee7cf37096 100644 --- a/Content.Server/Atmos/Piping/EntitySystems/AtmosDeviceSystem.cs +++ b/Content.Server/Atmos/Piping/EntitySystems/AtmosDeviceSystem.cs @@ -11,10 +11,10 @@ namespace Content.Server.Atmos.Piping.EntitySystems [Dependency] private readonly IGameTiming _gameTiming = default!; [Dependency] private readonly AtmosphereSystem _atmosphereSystem = default!; - private float _timer = 0f; + private float _timer; // Set of atmos devices that are off-grid but have JoinSystem set. - private readonly HashSet _joinedDevices = new(); + private readonly HashSet> _joinedDevices = new(); public override void Initialize() { @@ -27,9 +27,10 @@ namespace Content.Server.Atmos.Piping.EntitySystems SubscribeLocalEvent(OnDeviceAnchorChanged); } - public void JoinAtmosphere(AtmosDeviceComponent component) + public void JoinAtmosphere(Entity ent) { - var transform = Transform(component.Owner); + var component = ent.Comp; + var transform = Transform(ent); if (component.RequireAnchored && !transform.Anchored) return; @@ -39,16 +40,17 @@ namespace Content.Server.Atmos.Piping.EntitySystems if (!onGrid && component.JoinSystem) { - _joinedDevices.Add(component); + _joinedDevices.Add(ent); component.JoinedSystem = true; } component.LastProcess = _gameTiming.CurTime; - RaiseLocalEvent(component.Owner, new AtmosDeviceEnabledEvent(), false); + RaiseLocalEvent(ent, new AtmosDeviceEnabledEvent()); } - public void LeaveAtmosphere(AtmosDeviceComponent component) + public void LeaveAtmosphere(Entity ent) { + var component = ent.Comp; // Try to remove the component from an atmosphere, and if not if (component.JoinedGrid != null && !_atmosphereSystem.RemoveAtmosDevice(component.JoinedGrid.Value, component)) { @@ -59,45 +61,45 @@ namespace Content.Server.Atmos.Piping.EntitySystems if (component.JoinedSystem) { - _joinedDevices.Remove(component); + _joinedDevices.Remove(ent); component.JoinedSystem = false; } component.LastProcess = TimeSpan.Zero; - RaiseLocalEvent(component.Owner, new AtmosDeviceDisabledEvent(), false); + RaiseLocalEvent(ent, new AtmosDeviceDisabledEvent()); } - public void RejoinAtmosphere(AtmosDeviceComponent component) + public void RejoinAtmosphere(Entity component) { LeaveAtmosphere(component); JoinAtmosphere(component); } - private void OnDeviceInitialize(EntityUid uid, AtmosDeviceComponent component, ComponentInit args) + private void OnDeviceInitialize(Entity ent, ref ComponentInit args) { - JoinAtmosphere(component); + JoinAtmosphere(ent); } - private void OnDeviceShutdown(EntityUid uid, AtmosDeviceComponent component, ComponentShutdown args) + private void OnDeviceShutdown(Entity ent, ref ComponentShutdown args) { - LeaveAtmosphere(component); + LeaveAtmosphere(ent); } - private void OnDeviceAnchorChanged(EntityUid uid, AtmosDeviceComponent component, ref AnchorStateChangedEvent args) + private void OnDeviceAnchorChanged(Entity ent, ref AnchorStateChangedEvent args) { // Do nothing if the component doesn't require being anchored to function. - if (!component.RequireAnchored) + if (!ent.Comp.RequireAnchored) return; if (args.Anchored) - JoinAtmosphere(component); + JoinAtmosphere(ent); else - LeaveAtmosphere(component); + LeaveAtmosphere(ent); } - private void OnDeviceParentChanged(EntityUid uid, AtmosDeviceComponent component, ref EntParentChangedMessage args) + private void OnDeviceParentChanged(Entity ent, ref EntParentChangedMessage args) { - RejoinAtmosphere(component); + RejoinAtmosphere(ent); } /// @@ -116,8 +118,8 @@ namespace Content.Server.Atmos.Piping.EntitySystems var time = _gameTiming.CurTime; foreach (var device in _joinedDevices) { - RaiseLocalEvent(device.Owner, new AtmosDeviceUpdateEvent(_atmosphereSystem.AtmosTime), false); - device.LastProcess = time; + RaiseLocalEvent(device, new AtmosDeviceUpdateEvent(_atmosphereSystem.AtmosTime)); + device.Comp.LastProcess = time; } } } diff --git a/Content.Server/Atmos/Piping/Other/EntitySystems/GasMinerSystem.cs b/Content.Server/Atmos/Piping/Other/EntitySystems/GasMinerSystem.cs index 9cdee72b68..9853a17f82 100644 --- a/Content.Server/Atmos/Piping/Other/EntitySystems/GasMinerSystem.cs +++ b/Content.Server/Atmos/Piping/Other/EntitySystems/GasMinerSystem.cs @@ -1,13 +1,10 @@ using System.Diagnostics.CodeAnalysis; -using Content.Server.Atmos.Components; using Content.Server.Atmos.EntitySystems; using Content.Server.Atmos.Piping.Components; using Content.Server.Atmos.Piping.Other.Components; using Content.Shared.Atmos; using JetBrains.Annotations; using Robust.Server.GameObjects; -using Robust.Shared.GameObjects; -using Robust.Shared.IoC; namespace Content.Server.Atmos.Piping.Other.EntitySystems { @@ -24,9 +21,10 @@ namespace Content.Server.Atmos.Piping.Other.EntitySystems SubscribeLocalEvent(OnMinerUpdated); } - private void OnMinerUpdated(EntityUid uid, GasMinerComponent miner, AtmosDeviceUpdateEvent args) + private void OnMinerUpdated(Entity ent, ref AtmosDeviceUpdateEvent args) { - if (!CheckMinerOperation(miner, out var environment) || !miner.Enabled || !miner.SpawnGas.HasValue || miner.SpawnAmount <= 0f) + var miner = ent.Comp; + if (!CheckMinerOperation(ent, out var environment) || !miner.Enabled || !miner.SpawnGas.HasValue || miner.SpawnAmount <= 0f) return; // Time to mine some gas. @@ -37,9 +35,9 @@ namespace Content.Server.Atmos.Piping.Other.EntitySystems _atmosphereSystem.Merge(environment, merger); } - private bool CheckMinerOperation(GasMinerComponent miner, [NotNullWhen(true)] out GasMixture? environment) + private bool CheckMinerOperation(Entity ent, [NotNullWhen(true)] out GasMixture? environment) { - var uid = miner.Owner; + var (uid, miner) = ent; environment = _atmosphereSystem.GetContainingMixture(uid, true, true); var transform = Transform(uid); diff --git a/Content.Server/Atmos/Piping/Trinary/EntitySystems/GasFilterSystem.cs b/Content.Server/Atmos/Piping/Trinary/EntitySystems/GasFilterSystem.cs index 9f41671bca..69a0178a01 100644 --- a/Content.Server/Atmos/Piping/Trinary/EntitySystems/GasFilterSystem.cs +++ b/Content.Server/Atmos/Piping/Trinary/EntitySystems/GasFilterSystem.cs @@ -14,7 +14,6 @@ using Content.Shared.Interaction; using Content.Shared.Popups; using JetBrains.Annotations; using Robust.Server.GameObjects; -using Robust.Shared.Player; namespace Content.Server.Atmos.Piping.Trinary.EntitySystems { @@ -60,16 +59,16 @@ namespace Content.Server.Atmos.Piping.Trinary.EntitySystems || !_nodeContainer.TryGetNode(nodeContainer, filter.OutletName, out PipeNode? outletNode) || outletNode.Air.Pressure >= Atmospherics.MaxOutputPressure) // No need to transfer if target is full. { - _ambientSoundSystem.SetAmbience(filter.Owner, false); + _ambientSoundSystem.SetAmbience(uid, false); return; } // We multiply the transfer rate in L/s by the seconds passed since the last process to get the liters. - var transferVol = (float)(filter.TransferRate * args.dt); + var transferVol = filter.TransferRate * args.dt; if (transferVol <= 0) { - _ambientSoundSystem.SetAmbience(filter.Owner, false); + _ambientSoundSystem.SetAmbience(uid, false); return; } @@ -84,7 +83,7 @@ namespace Content.Server.Atmos.Piping.Trinary.EntitySystems var target = filterNode.Air.Pressure < Atmospherics.MaxOutputPressure ? filterNode : inletNode; _atmosphereSystem.Merge(target.Air, filteredOut); - _ambientSoundSystem.SetAmbience(filter.Owner, filteredOut.TotalMoles > 0f); + _ambientSoundSystem.SetAmbience(uid, filteredOut.TotalMoles > 0f); } _atmosphereSystem.Merge(outletNode.Air, removed); @@ -95,7 +94,7 @@ namespace Content.Server.Atmos.Piping.Trinary.EntitySystems filter.Enabled = false; UpdateAppearance(uid, filter); - _ambientSoundSystem.SetAmbience(filter.Owner, false); + _ambientSoundSystem.SetAmbience(uid, false); DirtyUI(uid, filter); _userInterfaceSystem.TryCloseAll(uid, GasFilterUiKey.Key); @@ -106,7 +105,7 @@ namespace Content.Server.Atmos.Piping.Trinary.EntitySystems if (!EntityManager.TryGetComponent(args.User, out ActorComponent? actor)) return; - if (EntityManager.GetComponent(filter.Owner).Anchored) + if (EntityManager.GetComponent(uid).Anchored) { _userInterfaceSystem.TryOpen(uid, GasFilterUiKey.Key, actor.PlayerSession); DirtyUI(uid, filter); @@ -125,7 +124,7 @@ namespace Content.Server.Atmos.Piping.Trinary.EntitySystems return; _userInterfaceSystem.TrySetUiState(uid, GasFilterUiKey.Key, - new GasFilterBoundUserInterfaceState(EntityManager.GetComponent(filter.Owner).EntityName, filter.TransferRate, filter.Enabled, filter.FilteredGas)); + new GasFilterBoundUserInterfaceState(MetaData(uid).EntityName, filter.TransferRate, filter.Enabled, filter.FilteredGas)); } private void UpdateAppearance(EntityUid uid, GasFilterComponent? filter = null) diff --git a/Content.Server/Atmos/Piping/Trinary/EntitySystems/PressureControlledValveSystem.cs b/Content.Server/Atmos/Piping/Trinary/EntitySystems/PressureControlledValveSystem.cs index cbb1b33eef..ceea449a31 100644 --- a/Content.Server/Atmos/Piping/Trinary/EntitySystems/PressureControlledValveSystem.cs +++ b/Content.Server/Atmos/Piping/Trinary/EntitySystems/PressureControlledValveSystem.cs @@ -7,7 +7,6 @@ using Content.Server.NodeContainer.Nodes; using Content.Shared.Atmos.Piping; using Content.Shared.Audio; using JetBrains.Annotations; -using Robust.Server.GameObjects; namespace Content.Server.Atmos.Piping.Trinary.EntitySystems { @@ -40,7 +39,7 @@ namespace Content.Server.Atmos.Piping.Trinary.EntitySystems || !_nodeContainer.TryGetNode(nodeContainer, comp.ControlName, out PipeNode? controlNode) || !_nodeContainer.TryGetNode(nodeContainer, comp.OutletName, out PipeNode? outletNode)) { - _ambientSoundSystem.SetAmbience(comp.Owner, false); + _ambientSoundSystem.SetAmbience(uid, false); comp.Enabled = false; return; } @@ -68,14 +67,14 @@ namespace Content.Server.Atmos.Piping.Trinary.EntitySystems UpdateAppearance(uid, comp); // We multiply the transfer rate in L/s by the seconds passed since the last process to get the liters. - var transferVolume = (float)(transferRate * args.dt); + var transferVolume = transferRate * args.dt; if (transferVolume <= 0) { - _ambientSoundSystem.SetAmbience(comp.Owner, false); + _ambientSoundSystem.SetAmbience(uid, false); return; } - _ambientSoundSystem.SetAmbience(comp.Owner, true); + _ambientSoundSystem.SetAmbience(uid, true); var removed = inletNode.Air.RemoveVolume(transferVolume); _atmosphereSystem.Merge(outletNode.Air, removed); } @@ -84,7 +83,7 @@ namespace Content.Server.Atmos.Piping.Trinary.EntitySystems { comp.Enabled = false; UpdateAppearance(uid, comp); - _ambientSoundSystem.SetAmbience(comp.Owner, false); + _ambientSoundSystem.SetAmbience(uid, false); } private void UpdateAppearance(EntityUid uid, PressureControlledValveComponent? comp = null, AppearanceComponent? appearance = null) diff --git a/Content.Server/Atmos/Piping/Unary/EntitySystems/GasOutletInjectorSystem.cs b/Content.Server/Atmos/Piping/Unary/EntitySystems/GasOutletInjectorSystem.cs index 49241b43dd..adde584cc3 100644 --- a/Content.Server/Atmos/Piping/Unary/EntitySystems/GasOutletInjectorSystem.cs +++ b/Content.Server/Atmos/Piping/Unary/EntitySystems/GasOutletInjectorSystem.cs @@ -7,7 +7,6 @@ using Content.Server.NodeContainer.Nodes; using Content.Shared.Atmos.Piping; using Content.Shared.Interaction; using JetBrains.Annotations; -using Robust.Server.GameObjects; namespace Content.Server.Atmos.Piping.Unary.EntitySystems { @@ -40,7 +39,7 @@ namespace Content.Server.Atmos.Piping.Unary.EntitySystems public void UpdateAppearance(EntityUid uid, GasOutletInjectorComponent component, AppearanceComponent? appearance = null) { - if (!Resolve(component.Owner, ref appearance, false)) + if (!Resolve(uid, ref appearance, false)) return; _appearance.SetData(uid, OutletInjectorVisuals.Enabled, component.Enabled, appearance); diff --git a/Content.Server/Bed/BedSystem.cs b/Content.Server/Bed/BedSystem.cs index 12eda65f84..e7d1e3be3c 100644 --- a/Content.Server/Bed/BedSystem.cs +++ b/Content.Server/Bed/BedSystem.cs @@ -57,14 +57,16 @@ namespace Content.Server.Bed { base.Update(frameTime); - foreach (var (_, bedComponent, strapComponent) in EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out _, out var bedComponent, out var strapComponent)) { if (_timing.CurTime < bedComponent.NextHealTime) continue; bedComponent.NextHealTime += TimeSpan.FromSeconds(bedComponent.HealTime); - if (strapComponent.BuckledEntities.Count == 0) continue; + if (strapComponent.BuckledEntities.Count == 0) + continue; foreach (var healedEntity in strapComponent.BuckledEntities) { @@ -76,7 +78,7 @@ namespace Content.Server.Bed if (HasComp(healedEntity)) damage *= bedComponent.SleepMultiplier; - _damageableSystem.TryChangeDamage(healedEntity, damage, true, origin: bedComponent.Owner); + _damageableSystem.TryChangeDamage(healedEntity, damage, true, origin: uid); } } } diff --git a/Content.Server/Bible/BibleSystem.cs b/Content.Server/Bible/BibleSystem.cs index e2cdc8c744..b3b41e2f32 100644 --- a/Content.Server/Bible/BibleSystem.cs +++ b/Content.Server/Bible/BibleSystem.cs @@ -65,7 +65,8 @@ namespace Content.Server.Bible } _remQueue.Clear(); - foreach (var (respawning, summonableComp) in EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var respawning, out var summonableComp)) { summonableComp.Accumulator += frameTime; if (summonableComp.Accumulator < summonableComp.RespawnTime) @@ -79,11 +80,11 @@ namespace Content.Server.Bible summonableComp.Summon = null; } summonableComp.AlreadySummoned = false; - _popupSystem.PopupEntity(Loc.GetString("bible-summon-respawn-ready", ("book", summonableComp.Owner)), summonableComp.Owner, PopupType.Medium); - SoundSystem.Play("/Audio/Effects/radpulse9.ogg", Filter.Pvs(summonableComp.Owner), summonableComp.Owner, AudioParams.Default.WithVolume(-4f)); + _popupSystem.PopupEntity(Loc.GetString("bible-summon-respawn-ready", ("book", uid)), uid, PopupType.Medium); + SoundSystem.Play("/Audio/Effects/radpulse9.ogg", Filter.Pvs(uid), uid, AudioParams.Default.WithVolume(-4f)); // Clean up the accumulator and respawn tracking component summonableComp.Accumulator = 0; - _remQueue.Enqueue(respawning.Owner); + _remQueue.Enqueue(uid); } } @@ -167,7 +168,7 @@ namespace Content.Server.Bible { if (!TryComp(args.User, out var userXform)) return; - AttemptSummon(component, args.User, userXform); + AttemptSummon((uid, component), args.User, userXform); }, Text = Loc.GetString("bible-summon-verb"), Priority = 2 @@ -183,9 +184,9 @@ namespace Content.Server.Bible args.AddAction(ref component.SummonActionEntity, component.SummonAction); } - private void OnSummon(EntityUid uid, SummonableComponent component, SummonActionEvent args) + private void OnSummon(Entity ent, ref SummonActionEvent args) { - AttemptSummon(component, args.Performer, Transform(args.Performer)); + AttemptSummon(ent, args.Performer, Transform(args.Performer)); } /// @@ -198,9 +199,9 @@ namespace Content.Server.Bible return; var source = component.Source; - if (source != null && TryComp(source, out var summonable)) + if (source != null && HasComp(source)) { - _addQueue.Enqueue(summonable.Owner); + _addQueue.Enqueue(source.Value); } } @@ -209,24 +210,26 @@ namespace Content.Server.Bible /// private void OnSpawned(EntityUid uid, FamiliarComponent component, GhostRoleSpawnerUsedEvent args) { - if (!TryComp(Transform(args.Spawner).ParentUid, out var summonable)) + var parent = Transform(args.Spawner).ParentUid; + if (!TryComp(parent, out var summonable)) return; - component.Source = summonable.Owner; + component.Source = parent; summonable.Summon = uid; } - private void AttemptSummon(SummonableComponent component, EntityUid user, TransformComponent? position) + private void AttemptSummon(Entity ent, EntityUid user, TransformComponent? position) { + var (uid, component) = ent; if (component.AlreadySummoned || component.SpecialItemPrototype == null) return; if (component.RequiresBibleUser && !HasComp(user)) return; if (!Resolve(user, ref position)) return; - if (component.Deleted || Deleted(component.Owner)) + if (component.Deleted || Deleted(uid)) return; - if (!_blocker.CanInteract(user, component.Owner)) + if (!_blocker.CanInteract(user, uid)) return; // Make this familiar the component's summon @@ -237,7 +240,7 @@ namespace Content.Server.Bible if (HasComp(familiar)) { _popupSystem.PopupEntity(Loc.GetString("bible-summon-requested"), user, PopupType.Medium); - Transform(familiar).AttachParent(component.Owner); + Transform(familiar).AttachParent(uid); } component.AlreadySummoned = true; _actionsSystem.RemoveAction(user, component.SummonActionEntity); diff --git a/Content.Server/Body/Commands/DestroyMechanismCommand.cs b/Content.Server/Body/Commands/DestroyMechanismCommand.cs index f4e299fac9..6ad0631150 100644 --- a/Content.Server/Body/Commands/DestroyMechanismCommand.cs +++ b/Content.Server/Body/Commands/DestroyMechanismCommand.cs @@ -51,7 +51,7 @@ namespace Content.Server.Body.Commands var mechanismName = string.Join(" ", args).ToLowerInvariant(); var bodySystem = entityManager.System(); - foreach (var organ in bodySystem.GetBodyOrgans(body.Owner, body)) + foreach (var organ in bodySystem.GetBodyOrgans(attached, body)) { if (fac.GetComponentName(organ.Component.GetType()).ToLowerInvariant() == mechanismName) { diff --git a/Content.Server/Body/Systems/InternalsSystem.cs b/Content.Server/Body/Systems/InternalsSystem.cs index 3e8e2307e3..ec4faa345c 100644 --- a/Content.Server/Body/Systems/InternalsSystem.cs +++ b/Content.Server/Body/Systems/InternalsSystem.cs @@ -81,7 +81,7 @@ public sealed class InternalsSystem : EntitySystem return; } - var tank = FindBestGasTank(uid ,internals); + var tank = FindBestGasTank(uid, internals); if (tank == null) { @@ -95,7 +95,7 @@ public sealed class InternalsSystem : EntitySystem return; } - _gasTank.ConnectToInternals(tank); + _gasTank.ConnectToInternals(tank.Value); } private void StartToggleInternalsDoAfter(EntityUid user, EntityUid target, InternalsComponent internals) @@ -139,34 +139,36 @@ public sealed class InternalsSystem : EntitySystem if (AreInternalsWorking(component)) { var gasTank = Comp(component.GasTankEntity!.Value); - args.Gas = _gasTank.RemoveAirVolume(gasTank, Atmospherics.BreathVolume); + args.Gas = _gasTank.RemoveAirVolume((component.GasTankEntity.Value, gasTank), Atmospherics.BreathVolume); // TODO: Should listen to gas tank updates instead I guess? _alerts.ShowAlert(uid, AlertType.Internals, GetSeverity(component)); } } - public void DisconnectBreathTool(InternalsComponent component) + public void DisconnectBreathTool(Entity ent) { + var (owner, component) = ent; var old = component.BreathToolEntity; component.BreathToolEntity = null; if (TryComp(old, out BreathToolComponent? breathTool) ) { _atmos.DisconnectInternals(breathTool); - DisconnectTank(component); + DisconnectTank(ent); } - _alerts.ShowAlert(component.Owner, AlertType.Internals, GetSeverity(component)); + _alerts.ShowAlert(owner, AlertType.Internals, GetSeverity(component)); } - public void ConnectBreathTool(InternalsComponent component, EntityUid toolEntity) + public void ConnectBreathTool(Entity ent, EntityUid toolEntity) { + var (owner, component) = ent; if (TryComp(component.BreathToolEntity, out BreathToolComponent? tool)) { _atmos.DisconnectInternals(tool); } component.BreathToolEntity = toolEntity; - _alerts.ShowAlert(component.Owner, AlertType.Internals, GetSeverity(component)); + _alerts.ShowAlert(owner, AlertType.Internals, GetSeverity(component)); } public void DisconnectTank(InternalsComponent? component) @@ -175,22 +177,23 @@ public sealed class InternalsSystem : EntitySystem return; if (TryComp(component.GasTankEntity, out GasTankComponent? tank)) - _gasTank.DisconnectFromInternals(tank); + _gasTank.DisconnectFromInternals((component.GasTankEntity.Value, tank)); component.GasTankEntity = null; _alerts.ShowAlert(component.Owner, AlertType.Internals, GetSeverity(component)); } - public bool TryConnectTank(InternalsComponent component, EntityUid tankEntity) + public bool TryConnectTank(Entity ent, EntityUid tankEntity) { + var component = ent.Comp; if (component.BreathToolEntity == null) return false; if (TryComp(component.GasTankEntity, out GasTankComponent? tank)) - _gasTank.DisconnectFromInternals(tank); + _gasTank.DisconnectFromInternals((component.GasTankEntity.Value, tank)); component.GasTankEntity = tankEntity; - _alerts.ShowAlert(component.Owner, AlertType.Internals, GetSeverity(component)); + _alerts.ShowAlert(ent, AlertType.Internals, GetSeverity(component)); return true; } @@ -213,7 +216,7 @@ public sealed class InternalsSystem : EntitySystem return 1; } - public GasTankComponent? FindBestGasTank(EntityUid internalsOwner, InternalsComponent component) + public Entity? FindBestGasTank(EntityUid internalsOwner, InternalsComponent component) { // Prioritise // 1. back equipped tanks @@ -227,27 +230,27 @@ public sealed class InternalsSystem : EntitySystem TryComp(backEntity, out var backGasTank) && _gasTank.CanConnectToInternals(backGasTank)) { - return backGasTank; + return (backEntity.Value, backGasTank); } if (_inventory.TryGetSlotEntity(internalsOwner, "suitstorage", out var entity, inventory, containerManager) && TryComp(entity, out var gasTank) && _gasTank.CanConnectToInternals(gasTank)) { - return gasTank; + return (entity.Value, gasTank); } - var tanks = new List(); + var tanks = new List>(); foreach (var hand in _hands.EnumerateHands(internalsOwner)) { if (TryComp(hand.HeldEntity, out gasTank) && _gasTank.CanConnectToInternals(gasTank)) - tanks.Add(gasTank); + tanks.Add((hand.HeldEntity.Value, gasTank)); } if (tanks.Count > 0) { - tanks.Sort((x, y) => y.Air.TotalMoles.CompareTo(x.Air.TotalMoles)); + tanks.Sort((x, y) => y.Comp.Air.TotalMoles.CompareTo(x.Comp.Air.TotalMoles)); return tanks[0]; } @@ -258,12 +261,12 @@ public sealed class InternalsSystem : EntitySystem while (enumerator.MoveNext(out var container)) { if (TryComp(container.ContainedEntity, out gasTank) && _gasTank.CanConnectToInternals(gasTank)) - tanks.Add(gasTank); + tanks.Add((container.ContainedEntity.Value, gasTank)); } if (tanks.Count > 0) { - tanks.Sort((x, y) => y.Air.TotalMoles.CompareTo(x.Air.TotalMoles)); + tanks.Sort((x, y) => y.Comp.Air.TotalMoles.CompareTo(x.Comp.Air.TotalMoles)); return tanks[0]; } } diff --git a/Content.Server/Body/Systems/LungSystem.cs b/Content.Server/Body/Systems/LungSystem.cs index a66efbac08..301cf14311 100644 --- a/Content.Server/Body/Systems/LungSystem.cs +++ b/Content.Server/Body/Systems/LungSystem.cs @@ -37,7 +37,7 @@ public sealed class LungSystem : EntitySystem if (TryComp(args.Equipee, out InternalsComponent? internals)) { component.ConnectedInternalsEntity = args.Equipee; - _internals.ConnectBreathTool(internals, uid); + _internals.ConnectBreathTool((args.Equipee, internals), uid); } } diff --git a/Content.Server/Body/Systems/RespiratorSystem.cs b/Content.Server/Body/Systems/RespiratorSystem.cs index 5bde141b54..58f803acdc 100644 --- a/Content.Server/Body/Systems/RespiratorSystem.cs +++ b/Content.Server/Body/Systems/RespiratorSystem.cs @@ -10,7 +10,6 @@ using Content.Shared.Damage; using Content.Shared.Database; using Content.Shared.Mobs.Systems; using JetBrains.Annotations; -using Robust.Shared.Player; using Robust.Shared.Timing; namespace Content.Server.Body.Systems @@ -41,10 +40,9 @@ namespace Content.Server.Body.Systems { base.Update(frameTime); - foreach (var (respirator, body) in EntityManager.EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var respirator, out var body)) { - var uid = respirator.Owner; - if (_mobState.IsDead(uid)) { continue; @@ -55,7 +53,7 @@ namespace Content.Server.Body.Systems if (respirator.AccumulatedFrametime < respirator.CycleDelay) continue; respirator.AccumulatedFrametime -= respirator.CycleDelay; - UpdateSaturation(respirator.Owner, -respirator.CycleDelay, respirator); + UpdateSaturation(uid, -respirator.CycleDelay, respirator); if (!_mobState.IsIncapacitated(uid)) // cannot breathe in crit. { @@ -99,7 +97,7 @@ namespace Content.Server.Body.Systems // Inhale gas var ev = new InhaleLocationEvent(); - RaiseLocalEvent(uid, ev, false); + RaiseLocalEvent(uid, ev); ev.Gas ??= _atmosSys.GetContainingMixture(uid, false, true); diff --git a/Content.Server/Body/Systems/StomachSystem.cs b/Content.Server/Body/Systems/StomachSystem.cs index 1d793887ee..5a3f6cf31a 100644 --- a/Content.Server/Body/Systems/StomachSystem.cs +++ b/Content.Server/Body/Systems/StomachSystem.cs @@ -20,7 +20,8 @@ namespace Content.Server.Body.Systems public override void Update(float frameTime) { - foreach (var (stomach, organ, sol)in EntityManager.EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var stomach, out var organ, out var sol)) { stomach.AccumulatedFrameTime += frameTime; @@ -30,7 +31,7 @@ namespace Content.Server.Body.Systems stomach.AccumulatedFrameTime -= stomach.UpdateInterval; // Get our solutions - if (!_solutionContainerSystem.TryGetSolution(stomach.Owner, DefaultSolutionName, + if (!_solutionContainerSystem.TryGetSolution(uid, DefaultSolutionName, out var stomachSolution, sol)) continue; @@ -50,7 +51,7 @@ namespace Content.Server.Body.Systems if (reagent.Quantity > delta.ReagentQuantity.Quantity) reagent = new(reagent.Reagent, delta.ReagentQuantity.Quantity); - _solutionContainerSystem.RemoveReagent((stomach).Owner, stomachSolution, reagent); + _solutionContainerSystem.RemoveReagent(uid, stomachSolution, reagent); transferSolution.AddReagent(reagent); } diff --git a/Content.Server/Body/Systems/ThermalRegulatorSystem.cs b/Content.Server/Body/Systems/ThermalRegulatorSystem.cs index 9bfba759a2..60d2e389da 100644 --- a/Content.Server/Body/Systems/ThermalRegulatorSystem.cs +++ b/Content.Server/Body/Systems/ThermalRegulatorSystem.cs @@ -12,14 +12,15 @@ public sealed class ThermalRegulatorSystem : EntitySystem public override void Update(float frameTime) { - foreach (var regulator in EntityManager.EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var regulator)) { regulator.AccumulatedFrametime += frameTime; if (regulator.AccumulatedFrametime < 1) continue; regulator.AccumulatedFrametime -= 1; - ProcessThermalRegulation(regulator.Owner, regulator); + ProcessThermalRegulation(uid, regulator); } } diff --git a/Content.Server/Botany/Systems/LogSystem.cs b/Content.Server/Botany/Systems/LogSystem.cs index b6cb0dedaf..a0639e3708 100644 --- a/Content.Server/Botany/Systems/LogSystem.cs +++ b/Content.Server/Botany/Systems/LogSystem.cs @@ -3,7 +3,6 @@ using Content.Server.Kitchen.Components; using Content.Shared.Hands.EntitySystems; using Content.Shared.Interaction; using Content.Shared.Random; -using Content.Shared.Random.Helpers; using Robust.Shared.Containers; namespace Content.Server.Botany.Systems; @@ -39,7 +38,7 @@ public sealed class LogSystem : EntitySystem else { var xform = Transform(plank); - _containerSystem.AttachParentToContainerOrGrid(xform); + _containerSystem.AttachParentToContainerOrGrid((plank, xform)); xform.LocalRotation = 0; _randomHelper.RandomOffset(plank, 0.25f); } diff --git a/Content.Server/Botany/Systems/PlantHolderSystem.cs b/Content.Server/Botany/Systems/PlantHolderSystem.cs index c3d57c4ad8..9991edd230 100644 --- a/Content.Server/Botany/Systems/PlantHolderSystem.cs +++ b/Content.Server/Botany/Systems/PlantHolderSystem.cs @@ -58,13 +58,14 @@ public sealed class PlantHolderSystem : EntitySystem { base.Update(frameTime); - foreach (var plantHolder in EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var plantHolder)) { if (plantHolder.NextUpdate > _gameTiming.CurTime) continue; plantHolder.NextUpdate = _gameTiming.CurTime + plantHolder.UpdateDelay; - Update(plantHolder.Owner, plantHolder); + Update(uid, plantHolder); } } diff --git a/Content.Server/Cargo/Systems/CargoSystem.Orders.cs b/Content.Server/Cargo/Systems/CargoSystem.Orders.cs index 9ea054b628..d9327b5150 100644 --- a/Content.Server/Cargo/Systems/CargoSystem.Orders.cs +++ b/Content.Server/Cargo/Systems/CargoSystem.Orders.cs @@ -1,14 +1,12 @@ using System.Diagnostics.CodeAnalysis; using Content.Server.Cargo.Components; using Content.Server.Labels.Components; +using Content.Server.Paper; using Content.Shared.Cargo; using Content.Shared.Cargo.BUI; using Content.Shared.Cargo.Events; using Content.Shared.Cargo.Prototypes; using Content.Shared.Database; -using Content.Shared.GameTicking; -using Content.Server.Paper; -using Robust.Server.GameObjects; using Robust.Shared.Map; using Robust.Shared.Players; using Robust.Shared.Prototypes; @@ -146,7 +144,8 @@ namespace Content.Server.Cargo.Systems } _idCardSystem.TryFindIdCard(player, out var idCard); - order.SetApproverData(idCard?.FullName, idCard?.JobTitle); + // ReSharper disable once ConditionalAccessQualifierIsNonNullableAccordingToAPIContract + order.SetApproverData(idCard.Comp?.FullName, idCard.Comp?.JobTitle); _audio.PlayPvs(_audio.GetSound(component.ConfirmSound), uid); // Log order approval diff --git a/Content.Server/Cargo/Systems/PricingSystem.cs b/Content.Server/Cargo/Systems/PricingSystem.cs index 289f383d29..509e99a28a 100644 --- a/Content.Server/Cargo/Systems/PricingSystem.cs +++ b/Content.Server/Cargo/Systems/PricingSystem.cs @@ -13,6 +13,7 @@ using Content.Shared.Stacks; using Robust.Shared.Console; using Robust.Shared.Containers; using Robust.Shared.Map; +using Robust.Shared.Map.Components; using Robust.Shared.Prototypes; using Robust.Shared.Utility; @@ -57,7 +58,7 @@ public sealed class PricingSystem : EntitySystem continue; } - if (!_mapManager.TryGetGrid(gridId, out var mapGrid)) + if (!TryComp(gridId, out MapGridComponent? mapGrid)) { shell.WriteError($"Grid \"{gridId}\" doesn't exist."); continue; @@ -65,7 +66,7 @@ public sealed class PricingSystem : EntitySystem List<(double, EntityUid)> mostValuable = new(); - var value = AppraiseGrid(mapGrid.Owner, null, (uid, price) => + var value = AppraiseGrid(gridId.Value, null, (uid, price) => { mostValuable.Add((price, uid)); mostValuable.Sort((i1, i2) => i2.Item1.CompareTo(i1.Item1)); diff --git a/Content.Server/Chat/Systems/AutoEmoteSystem.cs b/Content.Server/Chat/Systems/AutoEmoteSystem.cs index d8d7f952d5..3d6bd53540 100644 --- a/Content.Server/Chat/Systems/AutoEmoteSystem.cs +++ b/Content.Server/Chat/Systems/AutoEmoteSystem.cs @@ -1,5 +1,3 @@ -namespace Content.Server.Chat.Systems; - using System.Linq; using Content.Shared.Chat.Prototypes; using Robust.Shared.Prototypes; @@ -7,6 +5,8 @@ using Robust.Shared.Random; using Robust.Shared.Timing; using Robust.Shared.Utility; +namespace Content.Server.Chat.Systems; + public sealed class AutoEmoteSystem : EntitySystem { [Dependency] private readonly IGameTiming _gameTiming = default!; @@ -27,14 +27,13 @@ public sealed class AutoEmoteSystem : EntitySystem base.Update(frameTime); var curTime = _gameTiming.CurTime; - foreach (var autoEmote in EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var autoEmote)) { - var uid = autoEmote.Owner; - if (autoEmote.NextEmoteTime > curTime) continue; - foreach ((var key, var time) in autoEmote.EmoteTimers) + foreach (var (key, time) in autoEmote.EmoteTimers) { if (time > curTime) continue; diff --git a/Content.Server/Chemistry/EntitySystems/ChemMasterSystem.cs b/Content.Server/Chemistry/EntitySystems/ChemMasterSystem.cs index c22e36c993..a831165e68 100644 --- a/Content.Server/Chemistry/EntitySystems/ChemMasterSystem.cs +++ b/Content.Server/Chemistry/EntitySystems/ChemMasterSystem.cs @@ -45,11 +45,11 @@ namespace Content.Server.Chemistry.EntitySystems { base.Initialize(); - SubscribeLocalEvent((_, comp, _) => UpdateUiState(comp)); - SubscribeLocalEvent((_, comp, _) => UpdateUiState(comp)); - SubscribeLocalEvent((_, comp, _) => UpdateUiState(comp)); - SubscribeLocalEvent((_, comp, _) => UpdateUiState(comp)); - SubscribeLocalEvent((_, comp, _) => UpdateUiState(comp)); + SubscribeLocalEvent(SubscribeUpdateUiState); + SubscribeLocalEvent(SubscribeUpdateUiState); + SubscribeLocalEvent(SubscribeUpdateUiState); + SubscribeLocalEvent(SubscribeUpdateUiState); + SubscribeLocalEvent(SubscribeUpdateUiState); SubscribeLocalEvent(OnSetModeMessage); SubscribeLocalEvent(OnSetPillTypeMessage); @@ -58,12 +58,18 @@ namespace Content.Server.Chemistry.EntitySystems SubscribeLocalEvent(OnOutputToBottleMessage); } - private void UpdateUiState(ChemMasterComponent chemMaster, bool updateLabel = false) + private void SubscribeUpdateUiState(Entity ent, ref T ev) { - if (!_solutionContainerSystem.TryGetSolution(chemMaster.Owner, SharedChemMaster.BufferSolutionName, out var bufferSolution)) + UpdateUiState(ent); + } + + private void UpdateUiState(Entity ent, bool updateLabel = false) + { + var (owner, chemMaster) = ent; + if (!_solutionContainerSystem.TryGetSolution(owner, SharedChemMaster.BufferSolutionName, out var bufferSolution)) return; - var inputContainer = _itemSlotsSystem.GetItemOrNull(chemMaster.Owner, SharedChemMaster.InputSlotName); - var outputContainer = _itemSlotsSystem.GetItemOrNull(chemMaster.Owner, SharedChemMaster.OutputSlotName); + var inputContainer = _itemSlotsSystem.GetItemOrNull(owner, SharedChemMaster.InputSlotName); + var outputContainer = _itemSlotsSystem.GetItemOrNull(owner, SharedChemMaster.OutputSlotName); var bufferReagents = bufferSolution.Contents; var bufferCurrentVolume = bufferSolution.Volume; @@ -72,38 +78,38 @@ namespace Content.Server.Chemistry.EntitySystems chemMaster.Mode, BuildInputContainerInfo(inputContainer), BuildOutputContainerInfo(outputContainer), bufferReagents, bufferCurrentVolume, chemMaster.PillType, chemMaster.PillDosageLimit, updateLabel); - _userInterfaceSystem.TrySetUiState(chemMaster.Owner, ChemMasterUiKey.Key, state); + _userInterfaceSystem.TrySetUiState(owner, ChemMasterUiKey.Key, state); } - private void OnSetModeMessage(EntityUid uid, ChemMasterComponent chemMaster, ChemMasterSetModeMessage message) + private void OnSetModeMessage(Entity chemMaster, ref ChemMasterSetModeMessage message) { // Ensure the mode is valid, either Transfer or Discard. if (!Enum.IsDefined(typeof(ChemMasterMode), message.ChemMasterMode)) return; - chemMaster.Mode = message.ChemMasterMode; + chemMaster.Comp.Mode = message.ChemMasterMode; UpdateUiState(chemMaster); ClickSound(chemMaster); } - private void OnSetPillTypeMessage(EntityUid uid, ChemMasterComponent chemMaster, ChemMasterSetPillTypeMessage message) + private void OnSetPillTypeMessage(Entity chemMaster, ref ChemMasterSetPillTypeMessage message) { // Ensure valid pill type. There are 20 pills selectable, 0-19. if (message.PillType > SharedChemMaster.PillTypes - 1) return; - chemMaster.PillType = message.PillType; + chemMaster.Comp.PillType = message.PillType; UpdateUiState(chemMaster); ClickSound(chemMaster); } - private void OnReagentButtonMessage(EntityUid uid, ChemMasterComponent chemMaster, ChemMasterReagentAmountButtonMessage message) + private void OnReagentButtonMessage(Entity chemMaster, ref ChemMasterReagentAmountButtonMessage message) { // Ensure the amount corresponds to one of the reagent amount buttons. if (!Enum.IsDefined(typeof(ChemMasterReagentAmount), message.Amount)) return; - switch (chemMaster.Mode) + switch (chemMaster.Comp.Mode) { case ChemMasterMode.Transfer: TransferReagents(chemMaster, message.ReagentId, message.Amount.GetFixedPoint(), message.FromBuffer); @@ -119,12 +125,12 @@ namespace Content.Server.Chemistry.EntitySystems ClickSound(chemMaster); } - private void TransferReagents(ChemMasterComponent chemMaster, ReagentId id, FixedPoint2 amount, bool fromBuffer) + private void TransferReagents(Entity chemMaster, ReagentId id, FixedPoint2 amount, bool fromBuffer) { - var container = _itemSlotsSystem.GetItemOrNull(chemMaster.Owner, SharedChemMaster.InputSlotName); + var container = _itemSlotsSystem.GetItemOrNull(chemMaster, SharedChemMaster.InputSlotName); if (container is null || !_solutionContainerSystem.TryGetFitsInDispenser(container.Value, out var containerSolution) || - !_solutionContainerSystem.TryGetSolution(chemMaster.Owner, SharedChemMaster.BufferSolutionName, out var bufferSolution)) + !_solutionContainerSystem.TryGetSolution(chemMaster, SharedChemMaster.BufferSolutionName, out var bufferSolution)) { return; } @@ -145,19 +151,18 @@ namespace Content.Server.Chemistry.EntitySystems UpdateUiState(chemMaster, updateLabel: true); } - private void DiscardReagents(ChemMasterComponent chemMaster, ReagentId id, FixedPoint2 amount, bool fromBuffer) + private void DiscardReagents(Entity chemMaster, ReagentId id, FixedPoint2 amount, bool fromBuffer) { - if (fromBuffer) { - if (_solutionContainerSystem.TryGetSolution(chemMaster.Owner, SharedChemMaster.BufferSolutionName, out var bufferSolution)) + if (_solutionContainerSystem.TryGetSolution(chemMaster, SharedChemMaster.BufferSolutionName, out var bufferSolution)) bufferSolution.RemoveReagent(id, amount); else return; } else { - var container = _itemSlotsSystem.GetItemOrNull(chemMaster.Owner, SharedChemMaster.InputSlotName); + var container = _itemSlotsSystem.GetItemOrNull(chemMaster, SharedChemMaster.InputSlotName); if (container is not null && _solutionContainerSystem.TryGetFitsInDispenser(container.Value, out var containerSolution)) { @@ -170,10 +175,10 @@ namespace Content.Server.Chemistry.EntitySystems UpdateUiState(chemMaster, updateLabel: fromBuffer); } - private void OnCreatePillsMessage(EntityUid uid, ChemMasterComponent chemMaster, ChemMasterCreatePillsMessage message) + private void OnCreatePillsMessage(Entity chemMaster, ref ChemMasterCreatePillsMessage message) { var user = message.Session.AttachedEntity; - var maybeContainer = _itemSlotsSystem.GetItemOrNull(chemMaster.Owner, SharedChemMaster.OutputSlotName); + var maybeContainer = _itemSlotsSystem.GetItemOrNull(chemMaster, SharedChemMaster.OutputSlotName); if (maybeContainer is not { Valid: true } container || !TryComp(container, out StorageComponent? storage) || storage.Container is null) @@ -186,7 +191,7 @@ namespace Content.Server.Chemistry.EntitySystems return; // Ensure the amount is valid. - if (message.Dosage == 0 || message.Dosage > chemMaster.PillDosageLimit) + if (message.Dosage == 0 || message.Dosage > chemMaster.Comp.PillDosageLimit) return; // Ensure label length is within the character limit. @@ -211,8 +216,8 @@ namespace Content.Server.Chemistry.EntitySystems item, itemSolution, withdrawal.SplitSolution(message.Dosage)); var pill = EnsureComp(item); - pill.PillType = chemMaster.PillType; - Dirty(pill); + pill.PillType = chemMaster.Comp.PillType; + Dirty(item, pill); if (user.HasValue) { @@ -232,11 +237,10 @@ namespace Content.Server.Chemistry.EntitySystems ClickSound(chemMaster); } - private void OnOutputToBottleMessage( - EntityUid uid, ChemMasterComponent chemMaster, ChemMasterOutputToBottleMessage message) + private void OnOutputToBottleMessage(Entity chemMaster, ref ChemMasterOutputToBottleMessage message) { var user = message.Session.AttachedEntity; - var maybeContainer = _itemSlotsSystem.GetItemOrNull(chemMaster.Owner, SharedChemMaster.OutputSlotName); + var maybeContainer = _itemSlotsSystem.GetItemOrNull(chemMaster, SharedChemMaster.OutputSlotName); if (maybeContainer is not { Valid: true } container || !_solutionContainerSystem.TryGetSolution( container, SharedChemMaster.BottleSolutionName, out var solution)) @@ -277,14 +281,14 @@ namespace Content.Server.Chemistry.EntitySystems } private bool WithdrawFromBuffer( - IComponent chemMaster, + Entity chemMaster, FixedPoint2 neededVolume, EntityUid? user, [NotNullWhen(returnValue: true)] out Solution? outputSolution) { outputSolution = null; if (!_solutionContainerSystem.TryGetSolution( - chemMaster.Owner, SharedChemMaster.BufferSolutionName, out var solution)) + chemMaster, SharedChemMaster.BufferSolutionName, out var solution)) { return false; } @@ -308,9 +312,9 @@ namespace Content.Server.Chemistry.EntitySystems return true; } - private void ClickSound(ChemMasterComponent chemMaster) + private void ClickSound(Entity chemMaster) { - _audioSystem.PlayPvs(chemMaster.ClickSound, chemMaster.Owner, AudioParams.Default.WithVolume(-2f)); + _audioSystem.PlayPvs(chemMaster.Comp.ClickSound, chemMaster, AudioParams.Default.WithVolume(-2f)); } private ContainerInfo? BuildInputContainerInfo(EntityUid? container) diff --git a/Content.Server/Chemistry/EntitySystems/ReagentDispenserSystem.cs b/Content.Server/Chemistry/EntitySystems/ReagentDispenserSystem.cs index ee3b038acc..daa2ac80b7 100644 --- a/Content.Server/Chemistry/EntitySystems/ReagentDispenserSystem.cs +++ b/Content.Server/Chemistry/EntitySystems/ReagentDispenserSystem.cs @@ -34,11 +34,11 @@ namespace Content.Server.Chemistry.EntitySystems { base.Initialize(); - SubscribeLocalEvent((_, comp, _) => UpdateUiState(comp)); - SubscribeLocalEvent((_, comp, _) => UpdateUiState(comp)); - SubscribeLocalEvent((_, comp, _) => UpdateUiState(comp)); - SubscribeLocalEvent((_, comp, _) => UpdateUiState(comp)); - SubscribeLocalEvent((_, comp, _) => UpdateUiState(comp)); + SubscribeLocalEvent(SubscribeUpdateUiState); + SubscribeLocalEvent(SubscribeUpdateUiState); + SubscribeLocalEvent(SubscribeUpdateUiState); + SubscribeLocalEvent(SubscribeUpdateUiState); + SubscribeLocalEvent(SubscribeUpdateUiState); SubscribeLocalEvent(OnEmagged); SubscribeLocalEvent(OnSetDispenseAmountMessage); @@ -46,15 +46,20 @@ namespace Content.Server.Chemistry.EntitySystems SubscribeLocalEvent(OnClearContainerSolutionMessage); } - private void UpdateUiState(ReagentDispenserComponent reagentDispenser) + private void SubscribeUpdateUiState(Entity ent, ref T ev) { - var outputContainer = _itemSlotsSystem.GetItemOrNull(reagentDispenser.Owner, SharedReagentDispenser.OutputSlotName); + UpdateUiState(ent); + } + + private void UpdateUiState(Entity reagentDispenser) + { + var outputContainer = _itemSlotsSystem.GetItemOrNull(reagentDispenser, SharedReagentDispenser.OutputSlotName); var outputContainerInfo = BuildOutputContainerInfo(outputContainer); var inventory = GetInventory(reagentDispenser); - var state = new ReagentDispenserBoundUserInterfaceState(outputContainerInfo, inventory, reagentDispenser.DispenseAmount); - _userInterfaceSystem.TrySetUiState(reagentDispenser.Owner, ReagentDispenserUiKey.Key, state); + var state = new ReagentDispenserBoundUserInterfaceState(outputContainerInfo, inventory, reagentDispenser.Comp.DispenseAmount); + _userInterfaceSystem.TrySetUiState(reagentDispenser, ReagentDispenserUiKey.Key, state); } private ContainerInfo? BuildOutputContainerInfo(EntityUid? container) @@ -73,8 +78,9 @@ namespace Content.Server.Chemistry.EntitySystems return null; } - private List GetInventory(ReagentDispenserComponent reagentDispenser) + private List GetInventory(Entity ent) { + var reagentDispenser = ent.Comp; var inventory = new List(); if (reagentDispenser.PackPrototypeId is not null @@ -83,7 +89,7 @@ namespace Content.Server.Chemistry.EntitySystems inventory.AddRange(packPrototype.Inventory.Select(x => new ReagentId(x, null))); } - if (HasComp(reagentDispenser.Owner) + if (HasComp(ent) && reagentDispenser.EmagPackPrototypeId is not null && _prototypeManager.TryIndex(reagentDispenser.EmagPackPrototypeId, out ReagentDispenserInventoryPrototype? emagPackPrototype)) { @@ -93,32 +99,32 @@ namespace Content.Server.Chemistry.EntitySystems return inventory; } - private void OnEmagged(EntityUid uid, ReagentDispenserComponent reagentDispenser, ref GotEmaggedEvent args) + private void OnEmagged(Entity reagentDispenser, ref GotEmaggedEvent args) { // adding component manually to have correct state - EntityManager.AddComponent(uid); + EntityManager.AddComponent(reagentDispenser); UpdateUiState(reagentDispenser); args.Handled = true; } - private void OnSetDispenseAmountMessage(EntityUid uid, ReagentDispenserComponent reagentDispenser, ReagentDispenserSetDispenseAmountMessage message) + private void OnSetDispenseAmountMessage(Entity reagentDispenser, ref ReagentDispenserSetDispenseAmountMessage message) { - reagentDispenser.DispenseAmount = message.ReagentDispenserDispenseAmount; + reagentDispenser.Comp.DispenseAmount = message.ReagentDispenserDispenseAmount; UpdateUiState(reagentDispenser); ClickSound(reagentDispenser); } - private void OnDispenseReagentMessage(EntityUid uid, ReagentDispenserComponent reagentDispenser, ReagentDispenserDispenseReagentMessage message) + private void OnDispenseReagentMessage(Entity reagentDispenser, ref ReagentDispenserDispenseReagentMessage message) { // Ensure that the reagent is something this reagent dispenser can dispense. if (!GetInventory(reagentDispenser).Contains(message.ReagentId)) return; - var outputContainer = _itemSlotsSystem.GetItemOrNull(reagentDispenser.Owner, SharedReagentDispenser.OutputSlotName); + var outputContainer = _itemSlotsSystem.GetItemOrNull(reagentDispenser, SharedReagentDispenser.OutputSlotName); if (outputContainer is not {Valid: true} || !_solutionContainerSystem.TryGetFitsInDispenser(outputContainer.Value, out var solution)) return; - if (_solutionContainerSystem.TryAddReagent(outputContainer.Value, solution, message.ReagentId, (int)reagentDispenser.DispenseAmount, out var dispensedAmount) + if (_solutionContainerSystem.TryAddReagent(outputContainer.Value, solution, message.ReagentId, (int)reagentDispenser.Comp.DispenseAmount, out var dispensedAmount) && message.Session.AttachedEntity is not null) { _adminLogger.Add(LogType.ChemicalReaction, LogImpact.Medium, @@ -129,9 +135,9 @@ namespace Content.Server.Chemistry.EntitySystems ClickSound(reagentDispenser); } - private void OnClearContainerSolutionMessage(EntityUid uid, ReagentDispenserComponent reagentDispenser, ReagentDispenserClearContainerSolutionMessage message) + private void OnClearContainerSolutionMessage(Entity reagentDispenser, ref ReagentDispenserClearContainerSolutionMessage message) { - var outputContainer = _itemSlotsSystem.GetItemOrNull(reagentDispenser.Owner, SharedReagentDispenser.OutputSlotName); + var outputContainer = _itemSlotsSystem.GetItemOrNull(reagentDispenser, SharedReagentDispenser.OutputSlotName); if (outputContainer is not {Valid: true} || !_solutionContainerSystem.TryGetFitsInDispenser(outputContainer.Value, out var solution)) return; @@ -140,9 +146,9 @@ namespace Content.Server.Chemistry.EntitySystems ClickSound(reagentDispenser); } - private void ClickSound(ReagentDispenserComponent reagentDispenser) + private void ClickSound(Entity reagentDispenser) { - _audioSystem.PlayPvs(reagentDispenser.ClickSound, reagentDispenser.Owner, AudioParams.Default.WithVolume(-2f)); + _audioSystem.PlayPvs(reagentDispenser.Comp.ClickSound, reagentDispenser, AudioParams.Default.WithVolume(-2f)); } } } diff --git a/Content.Server/Chemistry/EntitySystems/SolutionInjectOnCollideSystem.cs b/Content.Server/Chemistry/EntitySystems/SolutionInjectOnCollideSystem.cs index 20d9246739..dcfc57a9b2 100644 --- a/Content.Server/Chemistry/EntitySystems/SolutionInjectOnCollideSystem.cs +++ b/Content.Server/Chemistry/EntitySystems/SolutionInjectOnCollideSystem.cs @@ -1,15 +1,12 @@ using Content.Server.Body.Components; using Content.Server.Body.Systems; using Content.Server.Chemistry.Components; -using Content.Shared.Chemistry.Components.SolutionManager; using Content.Shared.Chemistry.EntitySystems; using Content.Shared.Inventory; using JetBrains.Annotations; -using Robust.Shared.Physics.Dynamics; using Robust.Shared.Physics.Events; using Robust.Shared.Prototypes; - namespace Content.Server.Chemistry.EntitySystems { [UsedImplicitly] @@ -26,13 +23,17 @@ namespace Content.Server.Chemistry.EntitySystems SubscribeLocalEvent(HandleInjection); } - private void HandleInjection(EntityUid uid, SolutionInjectOnCollideComponent component, ref StartCollideEvent args) + private void HandleInjection(Entity ent, ref StartCollideEvent args) { + var component = ent.Comp; var target = args.OtherEntity; if (!args.OtherBody.Hard || !EntityManager.TryGetComponent(target, out var bloodstream) || - !_solutionsSystem.TryGetInjectableSolution(component.Owner, out var solution)) return; + !_solutionsSystem.TryGetInjectableSolution(ent, out var solution)) + { + return; + } if (component.BlockSlots != 0x0 && TryComp(target, out var inventory)) { diff --git a/Content.Server/Chemistry/EntitySystems/VaporSystem.cs b/Content.Server/Chemistry/EntitySystems/VaporSystem.cs index f9256c8ce7..02788d5a47 100644 --- a/Content.Server/Chemistry/EntitySystems/VaporSystem.cs +++ b/Content.Server/Chemistry/EntitySystems/VaporSystem.cs @@ -7,7 +7,6 @@ using Content.Shared.Chemistry.EntitySystems; using Content.Shared.Chemistry.Reagent; using Content.Shared.FixedPoint; using Content.Shared.Physics; -using Robust.Shared.Spawners; using Content.Shared.Throwing; using JetBrains.Annotations; using Robust.Shared.Map; @@ -16,7 +15,7 @@ using Robust.Shared.Physics.Components; using Robust.Shared.Physics.Events; using Robust.Shared.Physics.Systems; using Robust.Shared.Prototypes; -using TimedDespawnComponent = Robust.Shared.Spawners.TimedDespawnComponent; +using Robust.Shared.Spawners; namespace Content.Server.Chemistry.EntitySystems { @@ -57,19 +56,19 @@ namespace Content.Server.Chemistry.EntitySystems } } - public void Start(VaporComponent vapor, TransformComponent vaporXform, Vector2 dir, float speed, MapCoordinates target, float aliveTime, EntityUid? user = null) + public void Start(Entity vapor, TransformComponent vaporXform, Vector2 dir, float speed, MapCoordinates target, float aliveTime, EntityUid? user = null) { - vapor.Active = true; - var despawn = EnsureComp(vapor.Owner); + vapor.Comp.Active = true; + var despawn = EnsureComp(vapor); despawn.Lifetime = aliveTime; // Set Move - if (EntityManager.TryGetComponent(vapor.Owner, out PhysicsComponent? physics)) + if (EntityManager.TryGetComponent(vapor, out PhysicsComponent? physics)) { _physics.SetLinearDamping(physics, 0f); _physics.SetAngularDamping(physics, 0f); - _throwing.TryThrow(vapor.Owner, dir, speed, user: user); + _throwing.TryThrow(vapor, dir, speed, user: user); var distance = (target.Position - vaporXform.WorldPosition).Length(); var time = (distance / physics.LinearVelocity.Length()); @@ -77,41 +76,40 @@ namespace Content.Server.Chemistry.EntitySystems } } - internal bool TryAddSolution(VaporComponent vapor, Solution solution) + internal bool TryAddSolution(Entity vapor, Solution solution) { if (solution.Volume == 0) { return false; } - if (!_solutionContainerSystem.TryGetSolution(vapor.Owner, VaporComponent.SolutionName, + if (!_solutionContainerSystem.TryGetSolution(vapor, VaporComponent.SolutionName, out var vaporSolution)) { return false; } - return _solutionContainerSystem.TryAddSolution(vapor.Owner, vaporSolution, solution); + return _solutionContainerSystem.TryAddSolution(vapor, vaporSolution, solution); } public override void Update(float frameTime) { - foreach (var (vaporComp, solution, xform) in EntityManager - .EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var vaporComp, out var solution, out var xform)) { foreach (var (_, value) in solution.Solutions) { - Update(frameTime, vaporComp, value, xform); + Update(frameTime, (uid, vaporComp), value, xform); } } } - private void Update(float frameTime, VaporComponent vapor, Solution contents, TransformComponent xform) + private void Update(float frameTime, Entity ent, Solution contents, TransformComponent xform) { + var (entity, vapor) = ent; if (!vapor.Active) return; - var entity = vapor.Owner; - vapor.ReactTimer += frameTime; if (vapor.ReactTimer >= ReactTime && TryComp(xform.GridUid, out MapGridComponent? gridComp)) @@ -133,7 +131,7 @@ namespace Content.Server.Chemistry.EntitySystems reaction = reagentQuantity.Quantity; } - _solutionContainerSystem.RemoveReagent(vapor.Owner, contents, reagentQuantity.Reagent, reaction); + _solutionContainerSystem.RemoveReagent(entity, contents, reagentQuantity.Reagent, reaction); } } diff --git a/Content.Server/Chemistry/ReagentEffects/Oxygenate.cs b/Content.Server/Chemistry/ReagentEffects/Oxygenate.cs index 00ac03181d..28356bbd30 100644 --- a/Content.Server/Chemistry/ReagentEffects/Oxygenate.cs +++ b/Content.Server/Chemistry/ReagentEffects/Oxygenate.cs @@ -19,7 +19,7 @@ public sealed partial class Oxygenate : ReagentEffect if (args.EntityManager.TryGetComponent(args.SolutionEntity, out var resp)) { var respSys = EntitySystem.Get(); - respSys.UpdateSaturation(resp.Owner, args.Quantity.Float() * Factor, resp); + respSys.UpdateSaturation(args.SolutionEntity, args.Quantity.Float() * Factor, resp); } } } diff --git a/Content.Server/Chunking/ChunkingSystem.cs b/Content.Server/Chunking/ChunkingSystem.cs index f204b5cf72..4ef44d1678 100644 --- a/Content.Server/Chunking/ChunkingSystem.cs +++ b/Content.Server/Chunking/ChunkingSystem.cs @@ -1,3 +1,4 @@ +using System.Linq; using Content.Shared.Decals; using Microsoft.Extensions.ObjectPool; using Robust.Server.Player; @@ -5,8 +6,8 @@ using Robust.Shared; using Robust.Shared.Configuration; using Robust.Shared.Enums; using Robust.Shared.Map; +using Robust.Shared.Map.Components; using Robust.Shared.Utility; -using System.Linq; namespace Content.Shared.Chunking; @@ -87,10 +88,12 @@ public sealed class ChunkingSystem : EntitySystem var pos = _transform.GetWorldPosition(xform); var bounds = _baseViewBounds.Translated(pos).Enlarged(viewEnlargement); + var grids = new List>(); + _mapManager.FindGridsIntersecting(xform.MapID, bounds, ref grids, true); - foreach (var grid in _mapManager.FindGridsIntersecting(xform.MapID, bounds, true)) + foreach (var grid in grids) { - var netGrid = GetNetEntity(grid.Owner); + var netGrid = GetNetEntity(grid); if (!chunks.TryGetValue(netGrid, out var set)) { @@ -98,7 +101,7 @@ public sealed class ChunkingSystem : EntitySystem DebugTools.Assert(set.Count == 0); } - var enumerator = new ChunkIndicesEnumerator(_transform.GetInvWorldMatrix(grid.Owner).TransformBox(bounds), chunkSize); + var enumerator = new ChunkIndicesEnumerator(_transform.GetInvWorldMatrix(grid).TransformBox(bounds), chunkSize); while (enumerator.MoveNext(out var indices)) { diff --git a/Content.Server/Cloning/CloningConsoleSystem.cs b/Content.Server/Cloning/CloningConsoleSystem.cs index 29f42bf6c2..0be9b64134 100644 --- a/Content.Server/Cloning/CloningConsoleSystem.cs +++ b/Content.Server/Cloning/CloningConsoleSystem.cs @@ -170,7 +170,7 @@ namespace Content.Server.Cloning if (mind.UserId.HasValue == false || mind.Session == null) return; - if (_cloningSystem.TryCloning(cloningPodUid, body.Value, mind, cloningPod, scannerComp.CloningFailChanceMultiplier)) + if (_cloningSystem.TryCloning(cloningPodUid, body.Value, (mindId, mind), cloningPod, scannerComp.CloningFailChanceMultiplier)) _adminLogger.Add(LogType.Action, LogImpact.Medium, $"{ToPrettyString(uid)} successfully cloned {ToPrettyString(body.Value)}."); } diff --git a/Content.Server/Cloning/CloningSystem.cs b/Content.Server/Cloning/CloningSystem.cs index e94f0d1183..c81651c512 100644 --- a/Content.Server/Cloning/CloningSystem.cs +++ b/Content.Server/Cloning/CloningSystem.cs @@ -22,7 +22,6 @@ using Content.Shared.Emag.Systems; using Content.Shared.Examine; using Content.Shared.GameTicking; using Content.Shared.Humanoid; -using Content.Shared.Humanoid.Prototypes; using Content.Shared.Mind; using Content.Shared.Mind.Components; using Content.Shared.Mobs.Systems; @@ -154,7 +153,7 @@ namespace Content.Server.Cloning args.PushMarkup(Loc.GetString("cloning-pod-biomass", ("number", _material.GetMaterialAmount(uid, component.RequiredMaterial)))); } - public bool TryCloning(EntityUid uid, EntityUid bodyToClone, MindComponent mind, CloningPodComponent? clonePod, float failChanceModifier = 1) + public bool TryCloning(EntityUid uid, EntityUid bodyToClone, Entity mindEnt, CloningPodComponent? clonePod, float failChanceModifier = 1) { if (!Resolve(uid, ref clonePod)) return false; @@ -162,12 +161,13 @@ namespace Content.Server.Cloning if (HasComp(uid)) return false; + var mind = mindEnt.Comp; if (ClonesWaitingForMind.TryGetValue(mind, out var clone)) { if (EntityManager.EntityExists(clone) && !_mobStateSystem.IsDead(clone) && TryComp(clone, out var cloneMindComp) && - (cloneMindComp.Mind == null || cloneMindComp.Mind == mind.Owner)) + (cloneMindComp.Mind == null || cloneMindComp.Mind == mindEnt)) return false; // Mind already has clone ClonesWaitingForMind.Remove(mind); @@ -183,7 +183,7 @@ namespace Content.Server.Cloning if (!TryComp(bodyToClone, out var humanoid)) return false; // whatever body was to be cloned, was not a humanoid - if (!_prototype.TryIndex(humanoid.Species, out var speciesPrototype)) + if (!_prototype.TryIndex(humanoid.Species, out var speciesPrototype)) return false; if (!TryComp(bodyToClone, out var physics)) @@ -198,9 +198,12 @@ namespace Content.Server.Cloning if (TryComp(bodyToClone, out _)) { if (clonePod.ConnectedConsole != null) + { _chatSystem.TrySendInGameICMessage(clonePod.ConnectedConsole.Value, Loc.GetString("cloning-console-uncloneable-trait-error"), InGameICChatType.Speak, false); + } + return false; } @@ -253,14 +256,13 @@ namespace Content.Server.Cloning clonePod.BodyContainer.Insert(mob); ClonesWaitingForMind.Add(mind, mob); UpdateStatus(uid, CloningPodStatus.NoMind, clonePod); - var mindId = mind.Owner; - _euiManager.OpenEui(new AcceptCloningEui(mindId, mind, this), client); + _euiManager.OpenEui(new AcceptCloningEui(mindEnt, mind, this), client); AddComp(uid); // TODO: Ideally, components like this should be components on the mind entity so this isn't necessary. // Add on special job components to the mob. - if (_jobs.MindTryGetJob(mindId, out _, out var prototype)) + if (_jobs.MindTryGetJob(mindEnt, out _, out var prototype)) { foreach (var special in prototype.Special) { diff --git a/Content.Server/Clothing/MaskSystem.cs b/Content.Server/Clothing/MaskSystem.cs index fbf6ac6077..776979106f 100644 --- a/Content.Server/Clothing/MaskSystem.cs +++ b/Content.Server/Clothing/MaskSystem.cs @@ -43,12 +43,13 @@ namespace Content.Server.Clothing args.AddAction(ref component.ToggleActionEntity, component.ToggleAction); } - private void OnToggleMask(EntityUid uid, MaskComponent mask, ToggleMaskEvent args) + private void OnToggleMask(Entity ent, ref ToggleMaskEvent args) { + var (uid, mask) = ent; if (mask.ToggleActionEntity == null) return; - if (!_inventorySystem.TryGetSlotEntity(args.Performer, "mask", out var existing) || !mask.Owner.Equals(existing)) + if (!_inventorySystem.TryGetSlotEntity(args.Performer, "mask", out var existing) || !uid.Equals(existing)) return; mask.IsToggled ^= true; @@ -58,9 +59,9 @@ namespace Content.Server.Clothing _identity.QueueIdentityUpdate(args.Performer); if (mask.IsToggled) - _popupSystem.PopupEntity(Loc.GetString("action-mask-pull-down-popup-message", ("mask", mask.Owner)), args.Performer, args.Performer); + _popupSystem.PopupEntity(Loc.GetString("action-mask-pull-down-popup-message", ("mask", uid)), args.Performer, args.Performer); else - _popupSystem.PopupEntity(Loc.GetString("action-mask-pull-up-popup-message", ("mask", mask.Owner)), args.Performer, args.Performer); + _popupSystem.PopupEntity(Loc.GetString("action-mask-pull-up-popup-message", ("mask", uid)), args.Performer, args.Performer); ToggleMaskComponents(uid, mask, args.Performer); } @@ -115,7 +116,7 @@ namespace Content.Server.Clothing if (TryComp(wearer, out InternalsComponent? internals)) { breathTool.ConnectedInternalsEntity = wearer; - _internals.ConnectBreathTool(internals, uid); + _internals.ConnectBreathTool((wearer, internals), uid); } } } diff --git a/Content.Server/Communications/CommunicationsConsoleSystem.cs b/Content.Server/Communications/CommunicationsConsoleSystem.cs index b5c9385492..b2945c2a11 100644 --- a/Content.Server/Communications/CommunicationsConsoleSystem.cs +++ b/Content.Server/Communications/CommunicationsConsoleSystem.cs @@ -255,7 +255,7 @@ namespace Content.Server.Communications if (_idCardSystem.TryFindIdCard(mob, out var id)) { - author = $"{id.FullName} ({CultureInfo.CurrentCulture.TextInfo.ToTitleCase(id.JobTitle ?? string.Empty)})".Trim(); + author = $"{id.Comp.FullName} ({CultureInfo.CurrentCulture.TextInfo.ToTitleCase(id.Comp.JobTitle ?? string.Empty)})".Trim(); } } diff --git a/Content.Server/Construction/Commands/FixRotationsCommand.cs b/Content.Server/Construction/Commands/FixRotationsCommand.cs index 02429fcaa6..d23fa0a31b 100644 --- a/Content.Server/Construction/Commands/FixRotationsCommand.cs +++ b/Content.Server/Construction/Commands/FixRotationsCommand.cs @@ -5,7 +5,7 @@ using Content.Shared.Construction; using Content.Shared.Tag; using Robust.Server.Player; using Robust.Shared.Console; -using Robust.Shared.Map; +using Robust.Shared.Map.Components; namespace Content.Server.Construction.Commands { @@ -13,7 +13,6 @@ namespace Content.Server.Construction.Commands public sealed class FixRotationsCommand : IConsoleCommand { [Dependency] private readonly IEntityManager _entManager = default!; - [Dependency] private readonly IMapManager _mapManager = default!; // ReSharper disable once StringLiteralTypo public string Command => "fixrotations"; @@ -51,13 +50,13 @@ namespace Content.Server.Construction.Commands return; } - if (!_mapManager.TryGetGrid(gridId, out var grid)) + if (!_entManager.TryGetComponent(gridId, out MapGridComponent? grid)) { shell.WriteError($"No grid exists with id {gridId}"); return; } - if (!_entManager.EntityExists(grid.Owner)) + if (!_entManager.EntityExists(gridId)) { shell.WriteError($"Grid {gridId} doesn't have an associated grid entity."); return; @@ -66,7 +65,7 @@ namespace Content.Server.Construction.Commands var changed = 0; var tagSystem = _entManager.EntitySysManager.GetEntitySystem(); - foreach (var child in xformQuery.GetComponent(grid.Owner).ChildEntities) + foreach (var child in xformQuery.GetComponent(gridId.Value).ChildEntities) { if (!_entManager.EntityExists(child)) { diff --git a/Content.Server/Construction/Commands/TileReplaceCommand.cs b/Content.Server/Construction/Commands/TileReplaceCommand.cs index 7de6c510d4..ed1fba2424 100644 --- a/Content.Server/Construction/Commands/TileReplaceCommand.cs +++ b/Content.Server/Construction/Commands/TileReplaceCommand.cs @@ -3,6 +3,7 @@ using Content.Shared.Administration; using Robust.Server.Player; using Robust.Shared.Console; using Robust.Shared.Map; +using Robust.Shared.Map.Components; namespace Content.Server.Construction.Commands; @@ -10,7 +11,6 @@ namespace Content.Server.Construction.Commands; sealed class TileReplaceCommand : IConsoleCommand { [Dependency] private readonly IEntityManager _entManager = default!; - [Dependency] private readonly IMapManager _mapManager = default!; [Dependency] private readonly ITileDefinitionManager _tileDef = default!; // ReSharper disable once StringLiteralTypo @@ -58,13 +58,13 @@ sealed class TileReplaceCommand : IConsoleCommand var tileA = _tileDef[tileIdA]; var tileB = _tileDef[tileIdB]; - if (!_mapManager.TryGetGrid(gridId, out var grid)) + if (!_entManager.TryGetComponent(gridId, out MapGridComponent? grid)) { shell.WriteLine($"No grid exists with id {gridId}"); return; } - if (!_entManager.EntityExists(grid.Owner)) + if (!_entManager.EntityExists(gridId)) { shell.WriteLine($"Grid {gridId} doesn't have an associated grid entity."); return; diff --git a/Content.Server/Construction/Commands/TileWallsCommand.cs b/Content.Server/Construction/Commands/TileWallsCommand.cs index e919350364..55389e41cc 100644 --- a/Content.Server/Construction/Commands/TileWallsCommand.cs +++ b/Content.Server/Construction/Commands/TileWallsCommand.cs @@ -2,9 +2,11 @@ using Content.Server.Administration; using Content.Shared.Administration; using Content.Shared.Maps; using Content.Shared.Tag; +using Robust.Server.GameObjects; using Robust.Server.Player; using Robust.Shared.Console; using Robust.Shared.Map; +using Robust.Shared.Map.Components; namespace Content.Server.Construction.Commands { @@ -12,7 +14,6 @@ namespace Content.Server.Construction.Commands sealed class TileWallsCommand : IConsoleCommand { [Dependency] private readonly IEntityManager _entManager = default!; - [Dependency] private readonly IMapManager _mapManager = default!; [Dependency] private readonly ITileDefinitionManager _tileDefManager = default!; // ReSharper disable once StringLiteralTypo @@ -56,13 +57,13 @@ namespace Content.Server.Construction.Commands return; } - if (!_mapManager.TryGetGrid(gridId, out var grid)) + if (!_entManager.TryGetComponent(gridId, out MapGridComponent? grid)) { shell.WriteLine($"No grid exists with id {gridId}"); return; } - if (!_entManager.EntityExists(grid.Owner)) + if (!_entManager.EntityExists(gridId)) { shell.WriteLine($"Grid {gridId} doesn't have an associated grid entity."); return; @@ -72,7 +73,7 @@ namespace Content.Server.Construction.Commands var underplating = _tileDefManager[TilePrototypeId]; var underplatingTile = new Tile(underplating.TileId); var changed = 0; - foreach (var child in _entManager.GetComponent(grid.Owner).ChildEntities) + foreach (var child in _entManager.GetComponent(gridId.Value).ChildEntities) { if (!_entManager.EntityExists(child)) { @@ -91,7 +92,8 @@ namespace Content.Server.Construction.Commands continue; } - var tile = grid.GetTileRef(childTransform.Coordinates); + var mapSystem = _entManager.System(); + var tile = mapSystem.GetTileRef(gridId.Value, grid, childTransform.Coordinates); var tileDef = (ContentTileDefinition) _tileDefManager[tile.Tile.TypeId]; if (tileDef.ID == TilePrototypeId) diff --git a/Content.Server/Construction/ConstructionSystem.Computer.cs b/Content.Server/Construction/ConstructionSystem.Computer.cs index df96c0a6f8..edc1d26b6d 100644 --- a/Content.Server/Construction/ConstructionSystem.Computer.cs +++ b/Content.Server/Construction/ConstructionSystem.Computer.cs @@ -27,7 +27,7 @@ public sealed partial class ConstructionSystem } } - private void OnCompMapInit(EntityUid uid, ComputerComponent component, MapInitEvent args) + private void OnCompMapInit(Entity component, ref MapInitEvent args) { CreateComputerBoard(component); } @@ -42,25 +42,26 @@ public sealed partial class ConstructionSystem /// This exists so when you deconstruct computers that were serialized with the map, /// you can retrieve the computer board. /// - private void CreateComputerBoard(ComputerComponent component) + private void CreateComputerBoard(Entity ent) { + var component = ent.Comp; // Ensure that the construction component is aware of the board container. - if (TryComp(component.Owner, out var construction)) - AddContainer(component.Owner, "board", construction); + if (TryComp(ent, out var construction)) + AddContainer(ent, "board", construction); // We don't do anything if this is null or empty. if (string.IsNullOrEmpty(component.BoardPrototype)) return; - var container = _container.EnsureContainer(component.Owner, "board"); + var container = _container.EnsureContainer(ent, "board"); // We already contain a board. Note: We don't check if it's the right one! if (container.ContainedEntities.Count != 0) return; - var board = EntityManager.SpawnEntity(component.BoardPrototype, Transform(component.Owner).Coordinates); + var board = EntityManager.SpawnEntity(component.BoardPrototype, Transform(ent).Coordinates); - if(!container.Insert(board)) - Logger.Warning($"Couldn't insert board {board} to computer {component.Owner}!"); + if (!container.Insert(board)) + Log.Warning($"Couldn't insert board {board} to computer {ent}!"); } } diff --git a/Content.Server/Construction/ConstructionSystem.cs b/Content.Server/Construction/ConstructionSystem.cs index 237540f9fe..76d37432cb 100644 --- a/Content.Server/Construction/ConstructionSystem.cs +++ b/Content.Server/Construction/ConstructionSystem.cs @@ -44,17 +44,18 @@ namespace Content.Server.Construction SubscribeLocalEvent(OnConstructionStartup); } - private void OnConstructionInit(EntityUid uid, ConstructionComponent construction, ComponentInit args) + private void OnConstructionInit(Entity ent, ref ComponentInit args) { - if (GetCurrentGraph(uid, construction) is not {} graph) + var construction = ent.Comp; + if (GetCurrentGraph(ent, construction) is not {} graph) { - _sawmill.Warning($"Prototype {EntityManager.GetComponent(construction.Owner).EntityPrototype?.ID}'s construction component has an invalid graph specified."); + _sawmill.Warning($"Prototype {EntityManager.GetComponent(ent).EntityPrototype?.ID}'s construction component has an invalid graph specified."); return; } if (GetNodeFromGraph(graph, construction.Node) is not {} node) { - _sawmill.Warning($"Prototype {EntityManager.GetComponent(construction.Owner).EntityPrototype?.ID}'s construction component has an invalid node specified."); + _sawmill.Warning($"Prototype {EntityManager.GetComponent(ent).EntityPrototype?.ID}'s construction component has an invalid node specified."); return; } @@ -63,7 +64,7 @@ namespace Content.Server.Construction { if (GetEdgeFromNode(node, edgeIndex) is not {} currentEdge) { - _sawmill.Warning($"Prototype {EntityManager.GetComponent(construction.Owner).EntityPrototype?.ID}'s construction component has an invalid edge index specified."); + _sawmill.Warning($"Prototype {EntityManager.GetComponent(ent).EntityPrototype?.ID}'s construction component has an invalid edge index specified."); return; } @@ -74,11 +75,11 @@ namespace Content.Server.Construction { if (GetNodeFromGraph(graph, targetNodeId) is not { } targetNode) { - _sawmill.Warning($"Prototype {EntityManager.GetComponent(construction.Owner).EntityPrototype?.ID}'s construction component has an invalid target node specified."); + _sawmill.Warning($"Prototype {EntityManager.GetComponent(ent).EntityPrototype?.ID}'s construction component has an invalid target node specified."); return; } - UpdatePathfinding(uid, graph, node, targetNode, edge, construction); + UpdatePathfinding(ent, graph, node, targetNode, edge, construction); } } diff --git a/Content.Server/CrewManifest/CrewManifestSystem.cs b/Content.Server/CrewManifest/CrewManifestSystem.cs index fa00648c55..aed0575324 100644 --- a/Content.Server/CrewManifest/CrewManifestSystem.cs +++ b/Content.Server/CrewManifest/CrewManifestSystem.cs @@ -270,14 +270,13 @@ public sealed class CrewManifestCommand : IConsoleCommand return CompletionResult.Empty; } - var stations = _entityManager - .EntityQuery() - .Select(stationData => - { - var meta = _entityManager.GetComponent(stationData.Owner); - - return new CompletionOption(stationData.Owner.ToString(), meta.EntityName); - }); + var stations = new List(); + var query = _entityManager.EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out _)) + { + var meta = _entityManager.GetComponent(uid); + stations.Add(new CompletionOption(uid.ToString(), meta.EntityName)); + } return CompletionResult.FromHintOptions(stations, null); } diff --git a/Content.Server/Decals/Commands/AddDecalCommand.cs b/Content.Server/Decals/Commands/AddDecalCommand.cs index b780f0686d..2d9c5a1b25 100644 --- a/Content.Server/Decals/Commands/AddDecalCommand.cs +++ b/Content.Server/Decals/Commands/AddDecalCommand.cs @@ -3,8 +3,10 @@ using Content.Server.Administration; using Content.Shared.Administration; using Content.Shared.Decals; using Content.Shared.Maps; +using Robust.Server.GameObjects; using Robust.Shared.Console; using Robust.Shared.Map; +using Robust.Shared.Map.Components; using Robust.Shared.Prototypes; namespace Content.Server.Decals.Commands @@ -13,7 +15,6 @@ namespace Content.Server.Decals.Commands public sealed class AddDecalCommand : IConsoleCommand { [Dependency] private readonly IEntityManager _entManager = default!; - [Dependency] private readonly IMapManager _mapManager = default!; [Dependency] private readonly IPrototypeManager _protoManager = default!; public string Command => "adddecal"; @@ -46,14 +47,15 @@ namespace Content.Server.Decals.Commands if (!NetEntity.TryParse(args[3], out var gridIdNet) || !_entManager.TryGetEntity(gridIdNet, out var gridIdRaw) || - !_mapManager.TryGetGrid(gridIdRaw, out var grid)) + !_entManager.TryGetComponent(gridIdRaw, out MapGridComponent? grid)) { shell.WriteError($"Failed parsing gridId '{args[3]}'."); return; } - var coordinates = new EntityCoordinates(grid.Owner, new Vector2(x, y)); - if (grid.GetTileRef(coordinates).IsSpace()) + var mapSystem = _entManager.System(); + var coordinates = new EntityCoordinates(gridIdRaw.Value, new Vector2(x, y)); + if (mapSystem.GetTileRef(gridIdRaw.Value, grid, coordinates).IsSpace()) { shell.WriteError($"Cannot create decal on space tile at {coordinates}."); return; diff --git a/Content.Server/Decals/DecalSystem.cs b/Content.Server/Decals/DecalSystem.cs index 6f40ebae3a..d5a5bf9aff 100644 --- a/Content.Server/Decals/DecalSystem.cs +++ b/Content.Server/Decals/DecalSystem.cs @@ -9,11 +9,13 @@ using Content.Shared.Database; using Content.Shared.Decals; using Content.Shared.Maps; using Microsoft.Extensions.ObjectPool; +using Robust.Server.GameObjects; using Robust.Server.Player; using Robust.Shared; using Robust.Shared.Configuration; using Robust.Shared.Enums; using Robust.Shared.Map; +using Robust.Shared.Map.Components; using Robust.Shared.Threading; using Robust.Shared.Timing; using Robust.Shared.Utility; @@ -31,6 +33,7 @@ namespace Content.Server.Decals [Dependency] private readonly IConfigurationManager _conf = default!; [Dependency] private readonly IGameTiming _timing = default!; [Dependency] private readonly IAdminLogManager _adminLogger = default!; + [Dependency] private readonly MapSystem _mapSystem = default!; private readonly Dictionary> _dirtyChunks = new(); private readonly Dictionary>> _previousSentChunks = new(); @@ -283,10 +286,10 @@ namespace Content.Server.Decals return false; var gridId = coordinates.GetGridUid(EntityManager); - if (!MapManager.TryGetGrid(gridId, out var grid)) + if (!TryComp(gridId, out MapGridComponent? grid)) return false; - if (grid.GetTileRef(coordinates).IsSpace(_tileDefMan)) + if (_mapSystem.GetTileRef(gridId.Value, grid, coordinates).IsSpace(_tileDefMan)) return false; if (!TryComp(gridId, out DecalGridComponent? comp)) diff --git a/Content.Server/DeviceLinking/Systems/AutoLinkSystem.cs b/Content.Server/DeviceLinking/Systems/AutoLinkSystem.cs index d6169479f8..875f29785d 100644 --- a/Content.Server/DeviceLinking/Systems/AutoLinkSystem.cs +++ b/Content.Server/DeviceLinking/Systems/AutoLinkSystem.cs @@ -19,17 +19,18 @@ public sealed class AutoLinkSystem : EntitySystem { var xform = Transform(uid); - foreach (var receiver in EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var receiverUid, out var receiver)) { if (receiver.AutoLinkChannel != component.AutoLinkChannel) continue; // Not ours. - var rxXform = Transform(receiver.Owner); + var rxXform = Transform(receiverUid); if (rxXform.GridUid != xform.GridUid) continue; - _deviceLinkSystem.LinkDefaults(null, uid, receiver.Owner); + _deviceLinkSystem.LinkDefaults(null, uid, receiverUid); } } } diff --git a/Content.Server/Doors/Systems/DoorSystem.cs b/Content.Server/Doors/Systems/DoorSystem.cs index 5899baf2fc..560149f228 100644 --- a/Content.Server/Doors/Systems/DoorSystem.cs +++ b/Content.Server/Doors/Systems/DoorSystem.cs @@ -59,7 +59,7 @@ public sealed class DoorSystem : SharedDoorSystem return; if (door.ChangeAirtight && TryComp(uid, out AirtightComponent? airtight)) - _airtightSystem.SetAirblocked(uid, airtight, collidable); + _airtightSystem.SetAirblocked((uid, airtight), collidable); // Pathfinding / AI stuff. RaiseLocalEvent(new AccessReaderChangeEvent(uid, collidable)); @@ -201,14 +201,14 @@ public sealed class DoorSystem : SharedDoorSystem } } - protected override void CheckDoorBump(DoorComponent component, PhysicsComponent body) + protected override void CheckDoorBump(Entity ent) { - var uid = body.Owner; - if (component.BumpOpen) + var (uid, door, physics) = ent; + if (door.BumpOpen) { - foreach (var other in PhysicsSystem.GetContactingEntities(uid, body, approximate: true)) + foreach (var other in PhysicsSystem.GetContactingEntities(uid, physics, approximate: true)) { - if (Tags.HasTag(other, "DoorBumpOpener") && TryOpen(uid, component, other, false, quiet: true)) + if (Tags.HasTag(other, "DoorBumpOpener") && TryOpen(uid, door, other, quiet: true)) break; } } diff --git a/Content.Server/Doors/Systems/FirelockSystem.cs b/Content.Server/Doors/Systems/FirelockSystem.cs index e2f25c63ab..3d4c8a4ec5 100644 --- a/Content.Server/Doors/Systems/FirelockSystem.cs +++ b/Content.Server/Doors/Systems/FirelockSystem.cs @@ -4,9 +4,7 @@ using Content.Server.Atmos.Monitor.Systems; using Content.Server.Popups; using Content.Server.Power.Components; using Content.Server.Power.EntitySystems; -using Content.Server.Remotes; using Content.Server.Shuttles.Components; -using Content.Shared.Access.Components; using Content.Shared.Access.Systems; using Content.Shared.Atmos; using Content.Shared.Atmos.Monitor; @@ -14,11 +12,8 @@ using Content.Shared.Doors; using Content.Shared.Doors.Components; using Content.Shared.Doors.Systems; using Content.Shared.Popups; -using Microsoft.Extensions.Options; -using Robust.Server.GameObjects; -using Robust.Shared.Map.Components; -using Robust.Shared.Player; using Content.Shared.Prying.Components; +using Robust.Shared.Map.Components; namespace Content.Server.Doors.Systems { @@ -72,7 +67,8 @@ namespace Content.Server.Doors.Systems var appearanceQuery = GetEntityQuery(); var xformQuery = GetEntityQuery(); - foreach (var (firelock, door) in EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var firelock, out var door)) { // only bother to check pressure on doors that are some variation of closed. if (door.State != DoorState.Closed @@ -82,7 +78,6 @@ namespace Content.Server.Doors.Systems continue; } - var uid = door.Owner; if (airtightQuery.TryGetComponent(uid, out var airtight) && xformQuery.TryGetComponent(uid, out var xform) && appearanceQuery.TryGetComponent(uid, out var appearance)) @@ -128,9 +123,9 @@ namespace Content.Server.Doors.Systems if (door.State == DoorState.Open) { - if (_doorSystem.TryClose(door.Owner, door)) + if (_doorSystem.TryClose(uid, door)) { - return _doorSystem.OnPartialClose(door.Owner, door); + return _doorSystem.OnPartialClose(uid, door); } } return false; @@ -275,7 +270,7 @@ namespace Content.Server.Doors.Systems if (airtight.AirBlockedDirection != AtmosDirection.All) tiles.Add(pos); - var gasses = _atmosSystem.GetTileMixtures(gridAtmosphere.Owner, xform.MapUid, tiles); + var gasses = _atmosSystem.GetTileMixtures(xform.ParentUid, xform.MapUid, tiles); if (gasses == null) return (false, false); diff --git a/Content.Server/Engineering/EntitySystems/DisassembleOnAltVerbSystem.cs b/Content.Server/Engineering/EntitySystems/DisassembleOnAltVerbSystem.cs index 3085af0cdc..08bf68c4d2 100644 --- a/Content.Server/Engineering/EntitySystems/DisassembleOnAltVerbSystem.cs +++ b/Content.Server/Engineering/EntitySystems/DisassembleOnAltVerbSystem.cs @@ -3,6 +3,7 @@ using Content.Shared.DoAfter; using Content.Shared.Hands.EntitySystems; using Content.Shared.Verbs; using JetBrains.Annotations; + namespace Content.Server.Engineering.EntitySystems { [UsedImplicitly] @@ -52,17 +53,17 @@ namespace Content.Server.Engineering.EntitySystems return; } - if (component.Deleted || Deleted(component.Owner)) + if (component.Deleted || Deleted(uid)) return; - if (!TryComp(component.Owner, out var transformComp)) + if (!TryComp(uid, out var transformComp)) return; var entity = EntityManager.SpawnEntity(component.Prototype, transformComp.Coordinates); _handsSystem.TryPickup(user, entity); - EntityManager.DeleteEntity(component.Owner); + EntityManager.DeleteEntity(uid); } } } diff --git a/Content.Server/Engineering/EntitySystems/SpawnAfterInteractSystem.cs b/Content.Server/Engineering/EntitySystems/SpawnAfterInteractSystem.cs index 4893552c2c..61c4937a27 100644 --- a/Content.Server/Engineering/EntitySystems/SpawnAfterInteractSystem.cs +++ b/Content.Server/Engineering/EntitySystems/SpawnAfterInteractSystem.cs @@ -1,6 +1,6 @@ -using Content.Shared.Coordinates.Helpers; using Content.Server.Engineering.Components; using Content.Server.Stack; +using Content.Shared.Coordinates.Helpers; using Content.Shared.DoAfter; using Content.Shared.Interaction; using Content.Shared.Maps; @@ -58,7 +58,7 @@ namespace Content.Server.Engineering.EntitySystems if (component.Deleted || !IsTileClear()) return; - if (EntityManager.TryGetComponent(component.Owner, out StackComponent? stackComp) + if (EntityManager.TryGetComponent(uid, out StackComponent? stackComp) && component.RemoveOnInteract && !_stackSystem.Use(uid, 1, stackComp)) { return; @@ -66,8 +66,8 @@ namespace Content.Server.Engineering.EntitySystems EntityManager.SpawnEntity(component.Prototype, args.ClickLocation.SnapToGrid(grid)); - if (component.RemoveOnInteract && stackComp == null && !((!EntityManager.EntityExists(component.Owner) ? EntityLifeStage.Deleted : EntityManager.GetComponent(component.Owner).EntityLifeStage) >= EntityLifeStage.Deleted)) - EntityManager.DeleteEntity(component.Owner); + if (component.RemoveOnInteract && stackComp == null && !((!EntityManager.EntityExists(uid) ? EntityLifeStage.Deleted : EntityManager.GetComponent(component.Owner).EntityLifeStage) >= EntityLifeStage.Deleted)) + EntityManager.DeleteEntity(uid); } } } diff --git a/Content.Server/Explosion/EntitySystems/ClusterGrenadeSystem.cs b/Content.Server/Explosion/EntitySystems/ClusterGrenadeSystem.cs index e05056a68c..9467966cb6 100644 --- a/Content.Server/Explosion/EntitySystems/ClusterGrenadeSystem.cs +++ b/Content.Server/Explosion/EntitySystems/ClusterGrenadeSystem.cs @@ -4,7 +4,6 @@ using Content.Shared.Explosion; using Content.Shared.Interaction; using Content.Shared.Interaction.Events; using Content.Shared.Throwing; -using Robust.Server.GameObjects; using Robust.Shared.Containers; using Robust.Shared.Random; @@ -32,18 +31,22 @@ public sealed class ClusterGrenadeSystem : EntitySystem component.GrenadesContainer = _container.EnsureContainer(uid, "cluster-flash"); } - private void OnClugStartup(EntityUid uid, ClusterGrenadeComponent component, ComponentStartup args) + private void OnClugStartup(Entity clug, ref ComponentStartup args) { + var component = clug.Comp; if (component.FillPrototype != null) { component.UnspawnedCount = Math.Max(0, component.MaxGrenades - component.GrenadesContainer.ContainedEntities.Count); - UpdateAppearance(uid, component); + UpdateAppearance(clug); } } - private void OnClugUsing(EntityUid uid, ClusterGrenadeComponent component, InteractUsingEvent args) + private void OnClugUsing(Entity clug, ref InteractUsingEvent args) { - if (args.Handled) return; + if (args.Handled) + return; + + var component = clug.Comp; // TODO: Should use whitelist. if (component.GrenadesContainer.ContainedEntities.Count >= component.MaxGrenades || @@ -51,7 +54,7 @@ public sealed class ClusterGrenadeSystem : EntitySystem return; component.GrenadesContainer.Insert(args.Used); - UpdateAppearance(uid, component); + UpdateAppearance(clug); args.Handled = true; } @@ -63,7 +66,7 @@ public sealed class ClusterGrenadeSystem : EntitySystem // TODO: Should be an Update loop uid.SpawnTimer((int) (component.Delay * 1000), () => { - if (Deleted(component.Owner)) + if (Deleted(uid)) return; component.CountDown = true; @@ -71,7 +74,7 @@ public sealed class ClusterGrenadeSystem : EntitySystem var grenadesInserted = component.GrenadesContainer.ContainedEntities.Count + component.UnspawnedCount; var thrownCount = 0; var segmentAngle = 360 / grenadesInserted; - while (TryGetGrenade(component, out var grenade)) + while (TryGetGrenade((uid, component), out var grenade)) { var angleMin = segmentAngle * thrownCount; var angleMax = segmentAngle * (thrownCount + 1); @@ -99,14 +102,15 @@ public sealed class ClusterGrenadeSystem : EntitySystem args.Handled = true; } - private bool TryGetGrenade(ClusterGrenadeComponent component, out EntityUid grenade) + private bool TryGetGrenade(Entity ent, out EntityUid grenade) { grenade = default; + var component = ent.Comp; if (component.UnspawnedCount > 0) { component.UnspawnedCount--; - grenade = EntityManager.SpawnEntity(component.FillPrototype, Transform(component.Owner).MapPosition); + grenade = EntityManager.SpawnEntity(component.FillPrototype, Transform(ent).MapPosition); return true; } @@ -124,10 +128,12 @@ public sealed class ClusterGrenadeSystem : EntitySystem return false; } - private void UpdateAppearance(EntityUid uid, ClusterGrenadeComponent component) + private void UpdateAppearance(Entity ent) { - if (!TryComp(component.Owner, out var appearance)) return; + var component = ent.Comp; + if (!TryComp(ent, out var appearance)) + return; - _appearance.SetData(uid, ClusterGrenadeVisuals.GrenadesCounter, component.GrenadesContainer.ContainedEntities.Count + component.UnspawnedCount, appearance); + _appearance.SetData(ent, ClusterGrenadeVisuals.GrenadesCounter, component.GrenadesContainer.ContainedEntities.Count + component.UnspawnedCount, appearance); } } diff --git a/Content.Server/Explosion/EntitySystems/ExplosionSystem.GridMap.cs b/Content.Server/Explosion/EntitySystems/ExplosionSystem.GridMap.cs index 79985d233b..34028ab435 100644 --- a/Content.Server/Explosion/EntitySystems/ExplosionSystem.GridMap.cs +++ b/Content.Server/Explosion/EntitySystems/ExplosionSystem.GridMap.cs @@ -59,8 +59,8 @@ public sealed partial class ExplosionSystem : EntitySystem // if the explosion is centered on some grid (and not just space), get the transforms. if (referenceGrid != null) { - var targetGrid = _mapManager.GetGrid(referenceGrid.Value); - var xform = Transform(targetGrid.Owner); + var targetGrid = Comp(referenceGrid.Value); + var xform = Transform(referenceGrid.Value); targetAngle = xform.WorldRotation; targetMatrix = xform.InvWorldMatrix; tileSize = targetGrid.TileSize; @@ -84,17 +84,17 @@ public sealed partial class ExplosionSystem : EntitySystem if (!_gridEdges.TryGetValue(gridToTransform, out var edges)) continue; - if (!_mapManager.TryGetGrid(gridToTransform, out var grid)) + if (!TryComp(gridToTransform, out MapGridComponent? grid)) continue; if (grid.TileSize != tileSize) { - Logger.Error($"Explosions do not support grids with different grid sizes. GridIds: {gridToTransform} and {referenceGrid}"); + Log.Error($"Explosions do not support grids with different grid sizes. GridIds: {gridToTransform} and {referenceGrid}"); continue; } var xforms = EntityManager.GetEntityQuery(); - var xform = xforms.GetComponent(grid.Owner); + var xform = xforms.GetComponent(gridToTransform); var (_, gridWorldRotation, gridWorldMatrix, invGridWorldMatrid) = xform.GetWorldPositionRotationMatrixWithInv(xforms); var localEpicentre = (Vector2i) invGridWorldMatrid.Transform(epicentre.Position); @@ -228,7 +228,7 @@ public sealed partial class ExplosionSystem : EntitySystem if (!ev.NewTile.Tile.IsEmpty && !ev.OldTile.IsEmpty) return; - if (!_mapManager.TryGetGrid(ev.Entity, out var grid)) + if (!TryComp(ev.Entity, out MapGridComponent? grid)) return; var tileRef = ev.NewTile; diff --git a/Content.Server/Explosion/EntitySystems/TriggerSystem.Voice.cs b/Content.Server/Explosion/EntitySystems/TriggerSystem.Voice.cs index 28c627e143..c00f591d92 100644 --- a/Content.Server/Explosion/EntitySystems/TriggerSystem.Voice.cs +++ b/Content.Server/Explosion/EntitySystems/TriggerSystem.Voice.cs @@ -4,7 +4,6 @@ using Content.Server.Speech.Components; using Content.Shared.Database; using Content.Shared.Examine; using Content.Shared.Verbs; -using Robust.Shared.Player; namespace Content.Server.Explosion.EntitySystems { @@ -26,39 +25,43 @@ namespace Content.Server.Explosion.EntitySystems RemCompDeferred(uid); } - private void OnListen(EntityUid uid, TriggerOnVoiceComponent component, ListenEvent args) + private void OnListen(Entity ent, ref ListenEvent args) { + var component = ent.Comp; var message = args.Message.Trim(); if (component.IsRecording) { if (message.Length >= component.MinLength || message.Length <= component.MaxLength) - FinishRecording(component, args.Source, args.Message); + FinishRecording(ent, args.Source, args.Message); return; } if (!string.IsNullOrWhiteSpace(component.KeyPhrase) && message.Contains(component.KeyPhrase, StringComparison.InvariantCultureIgnoreCase)) { _adminLogger.Add(LogType.Trigger, LogImpact.High, - $"A voice-trigger on {ToPrettyString(uid):entity} was triggered by {ToPrettyString(args.Source):speaker} speaking the key-phrase {component.KeyPhrase}."); - Trigger(uid, args.Source); + $"A voice-trigger on {ToPrettyString(ent):entity} was triggered by {ToPrettyString(args.Source):speaker} speaking the key-phrase {component.KeyPhrase}."); + Trigger(ent, args.Source); } } - private void OnVoiceGetAltVerbs(EntityUid uid, TriggerOnVoiceComponent component, GetVerbsEvent args) + private void OnVoiceGetAltVerbs(Entity ent, ref GetVerbsEvent args) { if (!args.CanInteract || !args.CanAccess) return; + var component = ent.Comp; + + var @event = args; args.Verbs.Add(new AlternativeVerb() { Text = Loc.GetString(component.IsRecording ? "verb-trigger-voice-record-stop" : "verb-trigger-voice-record"), Act = () => { if (component.IsRecording) - StopRecording(component); + StopRecording(ent); else - StartRecording(component, args.User); + StartRecording(ent, @event.User); }, Priority = 1 }); @@ -73,40 +76,43 @@ namespace Content.Server.Explosion.EntitySystems { component.KeyPhrase = null; component.IsRecording = false; - RemComp(uid); + RemComp(ent); } }); } - public void StartRecording(TriggerOnVoiceComponent component, EntityUid user) + public void StartRecording(Entity ent, EntityUid user) { + var component = ent.Comp; component.IsRecording = true; - EnsureComp(component.Owner).Range = component.ListenRange; + EnsureComp(ent).Range = component.ListenRange; _adminLogger.Add(LogType.Trigger, LogImpact.Low, - $"A voice-trigger on {ToPrettyString(component.Owner):entity} has started recording. User: {ToPrettyString(user):user}"); + $"A voice-trigger on {ToPrettyString(ent):entity} has started recording. User: {ToPrettyString(user):user}"); - _popupSystem.PopupEntity(Loc.GetString("popup-trigger-voice-start-recording"), component.Owner); + _popupSystem.PopupEntity(Loc.GetString("popup-trigger-voice-start-recording"), ent); } - public void StopRecording(TriggerOnVoiceComponent component) + public void StopRecording(Entity ent) { + var component = ent.Comp; component.IsRecording = false; if (string.IsNullOrWhiteSpace(component.KeyPhrase)) - RemComp(component.Owner); + RemComp(ent); - _popupSystem.PopupEntity(Loc.GetString("popup-trigger-voice-stop-recording"), component.Owner); + _popupSystem.PopupEntity(Loc.GetString("popup-trigger-voice-stop-recording"), ent); } - public void FinishRecording(TriggerOnVoiceComponent component, EntityUid source, string message) + public void FinishRecording(Entity ent, EntityUid source, string message) { + var component = ent.Comp; component.KeyPhrase = message; component.IsRecording = false; _adminLogger.Add(LogType.Trigger, LogImpact.Low, - $"A voice-trigger on {ToPrettyString(component.Owner):entity} has recorded a new keyphrase: '{component.KeyPhrase}'. Recorded from {ToPrettyString(source):speaker}"); + $"A voice-trigger on {ToPrettyString(ent):entity} has recorded a new keyphrase: '{component.KeyPhrase}'. Recorded from {ToPrettyString(source):speaker}"); - _popupSystem.PopupEntity(Loc.GetString("popup-trigger-voice-recorded", ("keyphrase", component.KeyPhrase!)), component.Owner); + _popupSystem.PopupEntity(Loc.GetString("popup-trigger-voice-recorded", ("keyphrase", component.KeyPhrase!)), ent); } private void OnVoiceExamine(EntityUid uid, TriggerOnVoiceComponent component, ExaminedEvent args) diff --git a/Content.Server/Fluids/EntitySystems/DrainSystem.cs b/Content.Server/Fluids/EntitySystems/DrainSystem.cs index cefc918b17..ea3df2f8c4 100644 --- a/Content.Server/Fluids/EntitySystems/DrainSystem.cs +++ b/Content.Server/Fluids/EntitySystems/DrainSystem.cs @@ -1,19 +1,18 @@ -using Content.Server.Fluids.Components; -using Content.Server.Chemistry.EntitySystems; using Content.Server.DoAfter; +using Content.Server.Fluids.Components; using Content.Server.Popups; -using Content.Shared.FixedPoint; using Content.Shared.Audio; using Content.Shared.Chemistry.Components.SolutionManager; using Content.Shared.Chemistry.EntitySystems; using Content.Shared.Database; using Content.Shared.DoAfter; using Content.Shared.Examine; +using Content.Shared.FixedPoint; using Content.Shared.Fluids; +using Content.Shared.Fluids.Components; using Content.Shared.Interaction; using Content.Shared.Tag; using Content.Shared.Verbs; -using Content.Shared.Fluids.Components; using Robust.Shared.Collections; using Robust.Shared.Random; using Robust.Shared.Utility; @@ -96,7 +95,7 @@ public sealed class DrainSystem : SharedDrainSystem if (drainSolution.MaxVolume == drainSolution.Volume) { - _puddleSystem.TrySpillAt(Transform(target).Coordinates, containerSolution, out var puddle); + _puddleSystem.TrySpillAt(Transform(target).Coordinates, containerSolution, out _); _popupSystem.PopupEntity( Loc.GetString("drain-component-empty-verb-target-is-full-message", ("object", target)), container); @@ -111,7 +110,8 @@ public sealed class DrainSystem : SharedDrainSystem var puddleQuery = GetEntityQuery(); var puddles = new ValueList<(EntityUid Entity, string Solution)>(); - foreach (var drain in EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var drain)) { drain.Accumulator += frameTime; if (drain.Accumulator < drain.DrainFrequency) @@ -123,32 +123,32 @@ public sealed class DrainSystem : SharedDrainSystem // Disable ambient sound from emptying manually if (!drain.AutoDrain) { - _ambientSoundSystem.SetAmbience(drain.Owner, false); + _ambientSoundSystem.SetAmbience(uid, false); continue; } - if (!managerQuery.TryGetComponent(drain.Owner, out var manager)) + if (!managerQuery.TryGetComponent(uid, out var manager)) continue; // Best to do this one every second rather than once every tick... - _solutionSystem.TryGetSolution(drain.Owner, DrainComponent.SolutionName, out var drainSolution, manager); + _solutionSystem.TryGetSolution(uid, DrainComponent.SolutionName, out var drainSolution, manager); if (drainSolution is null) continue; if (drainSolution.AvailableVolume <= 0) { - _ambientSoundSystem.SetAmbience(drain.Owner, false); + _ambientSoundSystem.SetAmbience(uid, false); continue; } // Remove a bit from the buffer - _solutionSystem.SplitSolution(drain.Owner, drainSolution, (drain.UnitsDestroyedPerSecond * drain.DrainFrequency)); + _solutionSystem.SplitSolution(uid, drainSolution, (drain.UnitsDestroyedPerSecond * drain.DrainFrequency)); // This will ensure that UnitsPerSecond is per second... var amount = drain.UnitsPerSecond * drain.DrainFrequency; - if (!xformQuery.TryGetComponent(drain.Owner, out var xform)) + if (!xformQuery.TryGetComponent(uid, out var xform)) continue; puddles.Clear(); @@ -165,11 +165,11 @@ public sealed class DrainSystem : SharedDrainSystem if (puddles.Count == 0) { - _ambientSoundSystem.SetAmbience(drain.Owner, false); + _ambientSoundSystem.SetAmbience(uid, false); continue; } - _ambientSoundSystem.SetAmbience(drain.Owner, true); + _ambientSoundSystem.SetAmbience(uid, true); amount /= puddles.Count; @@ -190,7 +190,7 @@ public sealed class DrainSystem : SharedDrainSystem var transferSolution = _solutionSystem.SplitSolution(puddle, puddleSolution, FixedPoint2.Min(FixedPoint2.New(amount), puddleSolution.Volume, drainSolution.AvailableVolume)); - _solutionSystem.TryAddSolution(drain.Owner, drainSolution, transferSolution); + _solutionSystem.TryAddSolution(uid, drainSolution, transferSolution); if (puddleSolution.Volume <= 0) { @@ -203,13 +203,15 @@ public sealed class DrainSystem : SharedDrainSystem private void OnExamined(EntityUid uid, DrainComponent component, ExaminedEvent args) { if (!args.IsInDetailsRange || - !TryComp(uid, out SolutionContainerManagerComponent? solutionComp) || + !HasComp(uid) || !_solutionSystem.TryGetSolution(uid, DrainComponent.SolutionName, out var drainSolution)) - { return; } + { + return; + } - var text = drainSolution.AvailableVolume != 0 ? - Loc.GetString("drain-component-examine-volume", ("volume", drainSolution.AvailableVolume)) : - Loc.GetString("drain-component-examine-hint-full"); + var text = drainSolution.AvailableVolume != 0 + ? Loc.GetString("drain-component-examine-volume", ("volume", drainSolution.AvailableVolume)) + : Loc.GetString("drain-component-examine-hint-full"); args.Message.AddMarkup($"\n\n{text}"); } @@ -218,7 +220,9 @@ public sealed class DrainSystem : SharedDrainSystem if (!args.CanReach || args.Target == null || !_tagSystem.HasTag(args.Used, DrainComponent.PlungerTag) || !_solutionSystem.TryGetSolution(args.Target.Value, DrainComponent.SolutionName, out var drainSolution)) - { return; } + { + return; + } if (drainSolution.AvailableVolume > 0) { diff --git a/Content.Server/Fluids/EntitySystems/PuddleDebugDebugOverlaySystem.cs b/Content.Server/Fluids/EntitySystems/PuddleDebugDebugOverlaySystem.cs index ec4fb3b399..59f0a13695 100644 --- a/Content.Server/Fluids/EntitySystems/PuddleDebugDebugOverlaySystem.cs +++ b/Content.Server/Fluids/EntitySystems/PuddleDebugDebugOverlaySystem.cs @@ -1,9 +1,9 @@ using System.Numerics; -using Content.Server.Fluids.Components; using Content.Shared.Fluids; using Content.Shared.Fluids.Components; using Robust.Server.Player; using Robust.Shared.Map; +using Robust.Shared.Map.Components; using Robust.Shared.Timing; namespace Content.Server.Fluids.EntitySystems; @@ -15,7 +15,7 @@ public sealed class PuddleDebugDebugOverlaySystem : SharedPuddleDebugOverlaySyst [Dependency] private readonly PuddleSystem _puddle = default!; private readonly HashSet _playerObservers = new(); - + private List> _grids = new(); public bool ToggleObserver(IPlayerSession observer) { @@ -58,8 +58,10 @@ public sealed class PuddleDebugDebugOverlaySystem : SharedPuddleDebugOverlaySyst var worldBounds = Box2.CenteredAround(transform.WorldPosition, new Vector2(LocalViewRange, LocalViewRange)); + _grids.Clear(); + _mapManager.FindGridsIntersecting(transform.MapID, worldBounds, ref _grids); - foreach (var grid in _mapManager.FindGridsIntersecting(transform.MapID, worldBounds)) + foreach (var grid in _grids) { var data = new List(); var gridUid = grid.Owner; @@ -67,7 +69,7 @@ public sealed class PuddleDebugDebugOverlaySystem : SharedPuddleDebugOverlaySyst if (!Exists(gridUid)) continue; - foreach (var uid in grid.GetAnchoredEntities(worldBounds)) + foreach (var uid in grid.Comp.GetAnchoredEntities(worldBounds)) { PuddleComponent? puddle = null; TransformComponent? xform = null; diff --git a/Content.Server/Fluids/EntitySystems/PuddleSystem.cs b/Content.Server/Fluids/EntitySystems/PuddleSystem.cs index 4870f4286f..886cb9eff1 100644 --- a/Content.Server/Fluids/EntitySystems/PuddleSystem.cs +++ b/Content.Server/Fluids/EntitySystems/PuddleSystem.cs @@ -1,20 +1,25 @@ using Content.Server.Administration.Logs; using Content.Server.DoAfter; using Content.Server.Fluids.Components; -using Content.Shared.Chemistry; -using Content.Shared.Chemistry.Reaction; using Content.Server.Spreader; +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.Effects; using Content.Shared.Examine; using Content.Shared.FixedPoint; using Content.Shared.Fluids; -using Content.Shared.Popups; -using Content.Shared.Slippery; using Content.Shared.Fluids.Components; using Content.Shared.Friction; using Content.Shared.IdentityManagement; +using Content.Shared.Maps; +using Content.Shared.Movement.Components; +using Content.Shared.Movement.Systems; +using Content.Shared.Popups; +using Content.Shared.Slippery; using Content.Shared.StepTrigger.Components; using Content.Shared.StepTrigger.Systems; using Robust.Server.GameObjects; @@ -22,14 +27,9 @@ using Robust.Shared.Audio; using Robust.Shared.Map; using Robust.Shared.Map.Components; using Robust.Shared.Player; -using Solution = Content.Shared.Chemistry.Components.Solution; using Robust.Shared.Prototypes; using Robust.Shared.Random; using Robust.Shared.Timing; -using Content.Shared.Movement.Components; -using Content.Shared.Movement.Systems; -using Content.Shared.Maps; -using Content.Shared.Effects; namespace Content.Server.Fluids.EntitySystems; @@ -509,8 +509,11 @@ public sealed partial class PuddleSystem : SharedPuddleSystem return false; var targets = new List(); + var reactive = new HashSet>(); + _lookup.GetEntitiesInRange(coordinates, 1.0f, reactive); + // Get reactive entities nearby--if there are some, it'll spill a bit on them instead. - foreach (var ent in _lookup.GetComponentsInRange(coordinates, 1.0f)) + foreach (var ent in reactive) { // sorry! no overload for returning uid, so .owner must be used var owner = ent.Owner; diff --git a/Content.Server/Fluids/EntitySystems/SpraySystem.cs b/Content.Server/Fluids/EntitySystems/SpraySystem.cs index 8ae9b4b3da..f0afd43dd2 100644 --- a/Content.Server/Fluids/EntitySystems/SpraySystem.cs +++ b/Content.Server/Fluids/EntitySystems/SpraySystem.cs @@ -130,14 +130,15 @@ public sealed class SpraySystem : EntitySystem // Add the solution to the vapor and actually send the thing var vaporComponent = Comp(vapor); - _vapor.TryAddSolution(vaporComponent, newSolution); + var ent = (vapor, vaporComponent); + _vapor.TryAddSolution(ent, newSolution); // impulse direction is defined in world-coordinates, not local coordinates var impulseDirection = rotation.ToVec(); var time = diffLength / component.SprayVelocity; cooldownTime = MathF.Max(time, cooldownTime); - _vapor.Start(vaporComponent, vaporXform, impulseDirection * diffLength, component.SprayVelocity, target, time, args.User); + _vapor.Start(ent, vaporXform, impulseDirection * diffLength, component.SprayVelocity, target, time, args.User); if (TryComp(args.User, out var body)) { diff --git a/Content.Server/Forensics/Systems/ForensicScannerSystem.cs b/Content.Server/Forensics/Systems/ForensicScannerSystem.cs index 117717fca4..69704ddb56 100644 --- a/Content.Server/Forensics/Systems/ForensicScannerSystem.cs +++ b/Content.Server/Forensics/Systems/ForensicScannerSystem.cs @@ -1,8 +1,5 @@ using System.Linq; -using System.Text; // todo: remove this stinky LINQy -using Robust.Server.GameObjects; -using Robust.Shared.Audio; -using Robust.Shared.Timing; +using System.Text; using Content.Server.Paper; using Content.Server.Popups; using Content.Server.UserInterface; @@ -11,6 +8,10 @@ using Content.Shared.Forensics; using Content.Shared.Hands.EntitySystems; using Content.Shared.Interaction; using Content.Shared.Verbs; +using Robust.Server.GameObjects; +using Robust.Shared.Audio; +using Robust.Shared.Timing; +// todo: remove this stinky LINQy namespace Content.Server.Forensics { @@ -83,7 +84,7 @@ namespace Content.Server.Forensics scanner.LastScannedName = MetaData(args.Args.Target.Value).EntityName; } - OpenUserInterface(args.Args.User, scanner); + OpenUserInterface(args.Args.User, (uid, scanner)); } /// @@ -160,14 +161,14 @@ namespace Content.Server.Forensics UpdateUserInterface(uid, component); } - private void OpenUserInterface(EntityUid user, ForensicScannerComponent component) + private void OpenUserInterface(EntityUid user, Entity scanner) { if (!TryComp(user, out var actor)) return; - UpdateUserInterface(component.Owner, component); + UpdateUserInterface(scanner, scanner.Comp); - _uiSystem.TryOpen(component.Owner, ForensicScannerUiKey.Key, actor.PlayerSession); + _uiSystem.TryOpen(scanner, ForensicScannerUiKey.Key, actor.PlayerSession); } private void OnPrint(EntityUid uid, ForensicScannerComponent component, ForensicScannerPrintMessage args) @@ -192,7 +193,7 @@ namespace Content.Server.Forensics var printed = EntityManager.SpawnEntity(component.MachineOutput, Transform(uid).Coordinates); _handsSystem.PickupOrDrop(args.Session.AttachedEntity, printed, checkActionBlocker: false); - if (!TryComp(printed, out var paper)) + if (!HasComp(printed)) { _sawmill.Error("Printed paper did not have PaperComponent."); return; diff --git a/Content.Server/GameTicking/GameTicker.Spawning.cs b/Content.Server/GameTicking/GameTicker.Spawning.cs index 1c784641e3..0c59f93bb0 100644 --- a/Content.Server/GameTicking/GameTicker.Spawning.cs +++ b/Content.Server/GameTicking/GameTicker.Spawning.cs @@ -15,6 +15,7 @@ using Content.Shared.Roles.Jobs; using JetBrains.Annotations; using Robust.Server.Player; using Robust.Shared.Map; +using Robust.Shared.Map.Components; using Robust.Shared.Network; using Robust.Shared.Prototypes; using Robust.Shared.Random; @@ -34,11 +35,23 @@ namespace Content.Server.GameTicking /// How many players have joined the round through normal methods. /// Useful for game rules to look at. Doesn't count observers, people in lobby, etc. /// - public int PlayersJoinedRoundNormally = 0; + public int PlayersJoinedRoundNormally; // Mainly to avoid allocations. private readonly List _possiblePositions = new(); + private List GetSpawnableStations() + { + var spawnableStations = new List(); + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out _, out _)) + { + spawnableStations.Add(uid); + } + + return spawnableStations; + } + private void SpawnPlayers(List readyPlayers, Dictionary profiles, bool force) { // Allow game rules to spawn players by themselves if needed. (For example, nuke ops or wizard) @@ -66,8 +79,7 @@ namespace Content.Server.GameTicking } } - var spawnableStations = EntityQuery().Select(x => x.Item1.Owner).ToList(); - + var spawnableStations = GetSpawnableStations(); var assignedJobs = _stationJobs.AssignJobs(profiles, spawnableStations); _stationJobs.AssignOverflowJobs(ref assignedJobs, playerNetIds, profiles, spawnableStations); @@ -125,7 +137,7 @@ namespace Content.Server.GameTicking if (station == EntityUid.Invalid) { - var stations = EntityQuery().Select(x => x.Item1.Owner).ToList(); + var stations = GetSpawnableStations(); _robustRandom.Shuffle(stations); if (stations.Count == 0) station = EntityUid.Invalid; @@ -161,7 +173,8 @@ namespace Content.Server.GameTicking restrictedRoles.UnionWith(getDisallowed); var jobBans = _banManager.GetJobBans(player.UserId); - if(jobBans != null) restrictedRoles.UnionWith(jobBans); + if (jobBans != null) + restrictedRoles.UnionWith(jobBans); // Pick best job best on prefs. jobId ??= _stationJobs.PickBestAvailableJobWithPriority(station, character.JobPriorities, true, @@ -350,15 +363,16 @@ namespace Content.Server.GameTicking // Fallback to a random grid. if (_possiblePositions.Count == 0) { - foreach (var grid in _mapManager.GetAllGrids()) + var query = AllEntityQuery(); + while (query.MoveNext(out var uid, out var grid)) { - if (!metaQuery.TryGetComponent(grid.Owner, out var meta) || + if (!metaQuery.TryGetComponent(uid, out var meta) || meta.EntityPaused) { continue; } - _possiblePositions.Add(new EntityCoordinates(grid.Owner, Vector2.Zero)); + _possiblePositions.Add(new EntityCoordinates(uid, Vector2.Zero)); } } diff --git a/Content.Server/GameTicking/Rules/NukeopsRuleSystem.cs b/Content.Server/GameTicking/Rules/NukeopsRuleSystem.cs index 3bd3d13d27..13d4ed71c8 100644 --- a/Content.Server/GameTicking/Rules/NukeopsRuleSystem.cs +++ b/Content.Server/GameTicking/Rules/NukeopsRuleSystem.cs @@ -330,13 +330,17 @@ public sealed class NukeopsRuleSystem : GameRuleSystem // we can only currently guarantee that NT stations are the only station to // exist in the base game. - var eligible = EntityQuery() - .Where(x => - _npcFaction.IsFactionHostile(component.Faction, x.Item2.Owner, x.Item2)) - .Select(x => x.Item1.Owner) - .ToList(); + var eligible = new List>(); + var eligibleQuery = EntityQueryEnumerator(); + while (eligibleQuery.MoveNext(out var eligibleUid, out var eligibleComp, out var member)) + { + if (!_npcFaction.IsFactionFriendly(component.Faction, eligibleUid, member)) + continue; + + eligible.Add((eligibleUid, eligibleComp, member)); + } - if (!eligible.Any()) + if (eligible.Count == 0) return; component.TargetStation = _random.Pick(eligible); diff --git a/Content.Server/Ghost/Roles/GhostRoleSystem.cs b/Content.Server/Ghost/Roles/GhostRoleSystem.cs index 671b91392c..5a4cc176f2 100644 --- a/Content.Server/Ghost/Roles/GhostRoleSystem.cs +++ b/Content.Server/Ghost/Roles/GhostRoleSystem.cs @@ -40,12 +40,12 @@ namespace Content.Server.Ghost.Roles private uint _nextRoleIdentifier; private bool _needsUpdateGhostRoleCount = true; - private readonly Dictionary _ghostRoles = new(); + private readonly Dictionary> _ghostRoles = new(); private readonly Dictionary _openUis = new(); private readonly Dictionary _openMakeGhostRoleUis = new(); [ViewVariables] - public IReadOnlyCollection GhostRoles => _ghostRoles.Values; + public IReadOnlyCollection> GhostRoles => _ghostRoles.Values; public override void Initialize() { @@ -65,9 +65,9 @@ namespace Content.Server.Ghost.Roles _playerManager.PlayerStatusChanged += PlayerStatusChanged; } - private void OnMobStateChanged(EntityUid uid, GhostTakeoverAvailableComponent component, MobStateChangedEvent args) + private void OnMobStateChanged(Entity component, ref MobStateChangedEvent args) { - if (!TryComp(uid, out GhostRoleComponent? ghostRole)) + if (!TryComp(component, out GhostRoleComponent? ghostRole)) return; switch (args.NewMobState) @@ -75,12 +75,12 @@ namespace Content.Server.Ghost.Roles case MobState.Alive: { if (!ghostRole.Taken) - RegisterGhostRole(ghostRole); + RegisterGhostRole((component, ghostRole)); break; } case MobState.Critical: case MobState.Dead: - UnregisterGhostRole(ghostRole); + UnregisterGhostRole((component, ghostRole)); break; } } @@ -126,7 +126,8 @@ namespace Content.Server.Ghost.Roles public void CloseEui(ICommonSession session) { - if (!_openUis.ContainsKey(session)) return; + if (!_openUis.ContainsKey(session)) + return; _openUis.Remove(session, out var eui); @@ -176,47 +177,57 @@ namespace Content.Server.Ghost.Roles } } - public void RegisterGhostRole(GhostRoleComponent role) + public void RegisterGhostRole(Entity role) { - if (_ghostRoles.ContainsValue(role)) return; - _ghostRoles[role.Identifier = GetNextRoleIdentifier()] = role; - UpdateAllEui(); + if (_ghostRoles.ContainsValue(role)) + return; + _ghostRoles[role.Comp.Identifier = GetNextRoleIdentifier()] = role; + UpdateAllEui(); } - public void UnregisterGhostRole(GhostRoleComponent role) + public void UnregisterGhostRole(Entity role) { - if (!_ghostRoles.ContainsKey(role.Identifier) || _ghostRoles[role.Identifier] != role) return; - _ghostRoles.Remove(role.Identifier); + var comp = role.Comp; + if (!_ghostRoles.ContainsKey(comp.Identifier) || _ghostRoles[comp.Identifier] != role) + return; + + _ghostRoles.Remove(comp.Identifier); UpdateAllEui(); } public void Takeover(ICommonSession player, uint identifier) { - if (!_ghostRoles.TryGetValue(identifier, out var role)) return; + if (!_ghostRoles.TryGetValue(identifier, out var role)) + return; var ev = new TakeGhostRoleEvent(player); - RaiseLocalEvent(role.Owner, ref ev); + RaiseLocalEvent(role, ref ev); - if (!ev.TookRole) return; + if (!ev.TookRole) + return; if (player.AttachedEntity != null) - _adminLogger.Add(LogType.GhostRoleTaken, LogImpact.Low, $"{player:player} took the {role.RoleName:roleName} ghost role {ToPrettyString(player.AttachedEntity.Value):entity}"); + _adminLogger.Add(LogType.GhostRoleTaken, LogImpact.Low, $"{player:player} took the {role.Comp.RoleName:roleName} ghost role {ToPrettyString(player.AttachedEntity.Value):entity}"); CloseEui(player); } public void Follow(ICommonSession player, uint identifier) { - if (!_ghostRoles.TryGetValue(identifier, out var role)) return; - if (player.AttachedEntity == null) return; + if (!_ghostRoles.TryGetValue(identifier, out var role)) + return; + + if (player.AttachedEntity == null) + return; - _followerSystem.StartFollowingEntity(player.AttachedEntity.Value, role.Owner); + _followerSystem.StartFollowingEntity(player.AttachedEntity.Value, role); } public void GhostRoleInternalCreateMindAndTransfer(ICommonSession player, EntityUid roleUid, EntityUid mob, GhostRoleComponent? role = null) { - if (!Resolve(roleUid, ref role)) return; + if (!Resolve(roleUid, ref role)) + return; DebugTools.AssertNotNull(player.ContentData()); @@ -233,10 +244,8 @@ namespace Content.Server.Ghost.Roles var roles = new List(); var metaQuery = GetEntityQuery(); - foreach (var (id, role) in _ghostRoles) + foreach (var (id, (uid, role)) in _ghostRoles) { - var uid = role.Owner; - if (metaQuery.GetComponent(uid).EntityPaused) continue; @@ -249,8 +258,12 @@ namespace Content.Server.Ghost.Roles private void OnPlayerAttached(PlayerAttachedEvent message) { // Close the session of any player that has a ghost roles window open and isn't a ghost anymore. - if (!_openUis.ContainsKey(message.Player)) return; - if (EntityManager.HasComponent(message.Entity)) return; + if (!_openUis.ContainsKey(message.Player)) + return; + + if (HasComp(message.Entity)) + return; + CloseEui(message.Player); } @@ -260,7 +273,7 @@ namespace Content.Server.Ghost.Roles return; ghostRole.Taken = true; - UnregisterGhostRole(ghostRole); + UnregisterGhostRole((uid, ghostRole)); } private void OnMindRemoved(EntityUid uid, GhostTakeoverAvailableComponent component, MindRemovedMessage args) @@ -273,7 +286,7 @@ namespace Content.Server.Ghost.Roles return; ghostRole.Taken = false; - RegisterGhostRole(ghostRole); + RegisterGhostRole((uid, ghostRole)); } public void Reset(RoundRestartCleanupEvent ev) @@ -304,20 +317,21 @@ namespace Content.Server.Ghost.Roles UpdateAllEui(); } - private void OnInit(EntityUid uid, GhostRoleComponent role, ComponentInit args) + private void OnInit(Entity ent, ref ComponentInit args) { + var role = ent.Comp; if (role.Probability < 1f && !_random.Prob(role.Probability)) { - RemComp(uid); + RemComp(ent); return; } if (role.RoleRules == "") role.RoleRules = Loc.GetString("ghost-role-component-default-rules"); - RegisterGhostRole(role); + RegisterGhostRole(ent); } - private void OnShutdown(EntityUid uid, GhostRoleComponent role, ComponentShutdown args) + private void OnShutdown(Entity role, ref ComponentShutdown args) { UnregisterGhostRole(role); } @@ -391,7 +405,7 @@ namespace Content.Server.Ghost.Roles MakeSentientCommand.MakeSentient(uid, EntityManager, ghostRole.AllowMovement, ghostRole.AllowSpeech); GhostRoleInternalCreateMindAndTransfer(args.Player, uid, uid, ghostRole); - UnregisterGhostRole(ghostRole); + UnregisterGhostRole((uid, ghostRole)); args.TookRole = true; } diff --git a/Content.Server/Gravity/GravityGeneratorSystem.cs b/Content.Server/Gravity/GravityGeneratorSystem.cs index 1a9b2ad6e9..48002fb823 100644 --- a/Content.Server/Gravity/GravityGeneratorSystem.cs +++ b/Content.Server/Gravity/GravityGeneratorSystem.cs @@ -1,13 +1,12 @@ using Content.Server.Administration.Logs; using Content.Server.Audio; +using Content.Server.Construction; using Content.Server.Power.Components; using Content.Shared.Database; using Content.Shared.Gravity; using Content.Shared.Interaction; using Robust.Server.GameObjects; -using Robust.Server.Player; using Robust.Shared.Players; -using Content.Server.Construction; namespace Content.Server.Gravity { @@ -56,9 +55,10 @@ namespace Content.Server.Gravity { base.Update(frameTime); - foreach (var (gravGen, powerReceiver) in EntityManager - .EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var gravGen, out var powerReceiver)) { + var ent = (uid, gravGen, powerReceiver); if (!gravGen.Intact) continue; @@ -108,15 +108,15 @@ namespace Content.Server.Gravity var updateUI = gravGen.NeedUIUpdate; if (!MathHelper.CloseTo(lastCharge, gravGen.Charge)) { - UpdateState(gravGen, powerReceiver); + UpdateState(ent); updateUI = true; } if (updateUI) - UpdateUI(gravGen, powerReceiver, chargeRate); + UpdateUI(ent, chargeRate); if (active != gravGen.GravityActive && - TryComp(gravGen.Owner, out var xform) && + TryComp(uid, out var xform) && TryComp(xform.ParentUid, out var gravity)) { // Force it on in the faster path. @@ -153,12 +153,10 @@ namespace Content.Server.Gravity powerReceiver.Load = component.SwitchedOn ? component.ActivePowerUse : component.IdlePowerUse; } - private void UpdateUI( - GravityGeneratorComponent component, - ApcPowerReceiverComponent powerReceiver, - float chargeRate) + private void UpdateUI(Entity ent, float chargeRate) { - if (!_uiSystem.IsUiOpen(component.Owner, SharedGravityGeneratorComponent.GravityGeneratorUiKey.Key)) + var (_, component, powerReceiver) = ent; + if (!_uiSystem.IsUiOpen(ent, SharedGravityGeneratorComponent.GravityGeneratorUiKey.Key)) return; var chargeTarget = chargeRate < 0 ? 0 : component.MaxCharge; @@ -194,21 +192,21 @@ namespace Content.Server.Gravity ); _uiSystem.TrySetUiState( - component.Owner, + ent, SharedGravityGeneratorComponent.GravityGeneratorUiKey.Key, state); component.NeedUIUpdate = false; } - private void OnCompInit(EntityUid uid, GravityGeneratorComponent component, ComponentInit args) + private void OnCompInit(Entity ent, ref ComponentInit args) { ApcPowerReceiverComponent? powerReceiver = null; - if (!Resolve(uid, ref powerReceiver, false)) + if (!Resolve(ent, ref powerReceiver, false)) return; - UpdatePowerState(component, powerReceiver); - UpdateState(component, powerReceiver); + UpdatePowerState(ent, powerReceiver); + UpdateState((ent, ent.Comp, powerReceiver)); } private void OnInteractHand(EntityUid uid, GravityGeneratorComponent component, InteractHandEvent args) @@ -228,9 +226,9 @@ namespace Content.Server.Gravity component.NeedUIUpdate = true; } - public void UpdateState(GravityGeneratorComponent grav, ApcPowerReceiverComponent powerReceiver) + public void UpdateState(Entity ent) { - var uid = grav.Owner; + var (uid, grav, powerReceiver) = ent; var appearance = EntityManager.GetComponentOrNull(uid); _appearance.SetData(uid, GravityGeneratorVisuals.Charge, grav.Charge, appearance); @@ -242,19 +240,19 @@ namespace Content.Server.Gravity if (!grav.Intact) { - MakeBroken(uid, grav, appearance); + MakeBroken((uid, grav), appearance); } else if (powerReceiver.PowerReceived < grav.IdlePowerUse) { - MakeUnpowered(uid, grav, appearance); + MakeUnpowered((uid, grav), appearance); } else if (!grav.SwitchedOn) { - MakeOff(uid, grav, appearance); + MakeOff((uid, grav), appearance); } else { - MakeOn(uid, grav, appearance); + MakeOn((uid, grav), appearance); } } @@ -264,32 +262,32 @@ namespace Content.Server.Gravity component.MaxCharge = maxChargeMultipler * 1; } - private void MakeBroken(EntityUid uid, GravityGeneratorComponent component, AppearanceComponent? appearance) + private void MakeBroken(Entity ent, AppearanceComponent? appearance) { - _ambientSoundSystem.SetAmbience(component.Owner, false); + _ambientSoundSystem.SetAmbience(ent, false); - _appearance.SetData(uid, GravityGeneratorVisuals.State, GravityGeneratorStatus.Broken); + _appearance.SetData(ent, GravityGeneratorVisuals.State, GravityGeneratorStatus.Broken); } - private void MakeUnpowered(EntityUid uid, GravityGeneratorComponent component, AppearanceComponent? appearance) + private void MakeUnpowered(Entity ent, AppearanceComponent? appearance) { - _ambientSoundSystem.SetAmbience(component.Owner, false); + _ambientSoundSystem.SetAmbience(ent, false); - _appearance.SetData(uid, GravityGeneratorVisuals.State, GravityGeneratorStatus.Unpowered, appearance); + _appearance.SetData(ent, GravityGeneratorVisuals.State, GravityGeneratorStatus.Unpowered, appearance); } - private void MakeOff(EntityUid uid, GravityGeneratorComponent component, AppearanceComponent? appearance) + private void MakeOff(Entity ent, AppearanceComponent? appearance) { - _ambientSoundSystem.SetAmbience(component.Owner, false); + _ambientSoundSystem.SetAmbience(ent, false); - _appearance.SetData(uid, GravityGeneratorVisuals.State, GravityGeneratorStatus.Off, appearance); + _appearance.SetData(ent, GravityGeneratorVisuals.State, GravityGeneratorStatus.Off, appearance); } - private void MakeOn(EntityUid uid, GravityGeneratorComponent component, AppearanceComponent? appearance) + private void MakeOn(Entity ent, AppearanceComponent? appearance) { - _ambientSoundSystem.SetAmbience(component.Owner, true); + _ambientSoundSystem.SetAmbience(ent, true); - _appearance.SetData(uid, GravityGeneratorVisuals.State, GravityGeneratorStatus.On, appearance); + _appearance.SetData(ent, GravityGeneratorVisuals.State, GravityGeneratorStatus.On, appearance); } private void OnSwitchGenerator( diff --git a/Content.Server/Hands/Systems/HandsSystem.cs b/Content.Server/Hands/Systems/HandsSystem.cs index 298aa57ccf..b5b01ac001 100644 --- a/Content.Server/Hands/Systems/HandsSystem.cs +++ b/Content.Server/Hands/Systems/HandsSystem.cs @@ -18,14 +18,11 @@ using Content.Shared.Pulling.Components; using Content.Shared.Stacks; using Content.Shared.Storage; using Content.Shared.Throwing; -using JetBrains.Annotations; using Robust.Server.Player; -using Robust.Shared.Configuration; using Robust.Shared.Containers; using Robust.Shared.GameStates; using Robust.Shared.Input.Binding; using Robust.Shared.Map; -using Robust.Shared.Player; using Robust.Shared.Players; using Robust.Shared.Utility; @@ -97,7 +94,7 @@ namespace Content.Server.Hands.Systems base.HandleEntityRemoved(uid, hands, args); if (!Deleted(args.Entity) && TryComp(args.Entity, out HandVirtualItemComponent? @virtual)) - _virtualSystem.Delete(@virtual, uid); + _virtualSystem.Delete((args.Entity, @virtual), uid); } private void HandleBodyPartAdded(EntityUid uid, HandsComponent component, ref BodyPartAddedEvent args) diff --git a/Content.Server/Holiday/Christmas/RandomGiftSystem.cs b/Content.Server/Holiday/Christmas/RandomGiftSystem.cs index 29ec823aa7..4581d378f6 100644 --- a/Content.Server/Holiday/Christmas/RandomGiftSystem.cs +++ b/Content.Server/Holiday/Christmas/RandomGiftSystem.cs @@ -57,7 +57,7 @@ public sealed class RandomGiftSystem : EntitySystem var coords = Transform(args.User).Coordinates; var handsEnt = Spawn(component.SelectedEntity, coords); - _adminLogger.Add(LogType.EntitySpawn, LogImpact.Low, $"{ToPrettyString(args.User)} used {ToPrettyString(component.Owner)} which spawned {ToPrettyString(handsEnt)}"); + _adminLogger.Add(LogType.EntitySpawn, LogImpact.Low, $"{ToPrettyString(args.User)} used {ToPrettyString(uid)} which spawned {ToPrettyString(handsEnt)}"); EnsureComp(handsEnt); // For insane mode. if (component.Wrapper is not null) Spawn(component.Wrapper, coords); diff --git a/Content.Server/IdentityManagement/IdentitySystem.cs b/Content.Server/IdentityManagement/IdentitySystem.cs index 3d4be31435..cdb4dc7c6c 100644 --- a/Content.Server/IdentityManagement/IdentitySystem.cs +++ b/Content.Server/IdentityManagement/IdentitySystem.cs @@ -4,14 +4,12 @@ using Content.Server.Humanoid; using Content.Shared.Database; using Content.Shared.Hands; using Content.Shared.Humanoid; -using Content.Shared.Humanoid.Prototypes; using Content.Shared.IdentityManagement; using Content.Shared.IdentityManagement.Components; using Content.Shared.Inventory; using Content.Shared.Inventory.Events; using Robust.Shared.Enums; using Robust.Shared.GameObjects.Components.Localization; -using Robust.Shared.Prototypes; namespace Content.Server.IdentityManagement; @@ -147,8 +145,8 @@ public class IdentitySystem : SharedIdentitySystem // Get their name and job from their ID for their presumed name. if (_idCard.TryFindIdCard(target, out var id)) { - presumedName = string.IsNullOrWhiteSpace(id.FullName) ? null : id.FullName; - presumedJob = id.JobTitle?.ToLowerInvariant(); + presumedName = string.IsNullOrWhiteSpace(id.Comp.FullName) ? null : id.Comp.FullName; + presumedJob = id.Comp.JobTitle?.ToLowerInvariant(); } // If it didn't find a job, that's fine. diff --git a/Content.Server/IgnitionSource/IgnitionSourceSystem.cs b/Content.Server/IgnitionSource/IgnitionSourceSystem.cs index 6984dbf56b..b70cf7a9a7 100644 --- a/Content.Server/IgnitionSource/IgnitionSourceSystem.cs +++ b/Content.Server/IgnitionSource/IgnitionSourceSystem.cs @@ -41,9 +41,9 @@ public sealed class IgnitionSourceSystem : EntitySystem { base.Update(frameTime); - foreach (var (component,transform) in EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var source, out var component, out var transform)) { - var source = component.Owner; if (!component.Ignited) continue; diff --git a/Content.Server/Kitchen/EntitySystems/ReagentGrinderSystem.cs b/Content.Server/Kitchen/EntitySystems/ReagentGrinderSystem.cs index d50ce8df1f..6ce53dc530 100644 --- a/Content.Server/Kitchen/EntitySystems/ReagentGrinderSystem.cs +++ b/Content.Server/Kitchen/EntitySystems/ReagentGrinderSystem.cs @@ -12,7 +12,6 @@ using Content.Shared.Interaction; using Content.Shared.Kitchen; using Content.Shared.Popups; using Content.Shared.Random; -using Content.Shared.Random.Helpers; using Content.Shared.Stacks; using JetBrains.Annotations; using Robust.Server.GameObjects; @@ -59,10 +58,9 @@ namespace Content.Server.Kitchen.EntitySystems { base.Update(frameTime); - foreach (var (active, reagentGrinder) in EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var active, out var reagentGrinder)) { - var uid = reagentGrinder.Owner; - if (active.EndTime > _timing.CurTime) continue; diff --git a/Content.Server/Light/EntitySystems/ExpendableLightSystem.cs b/Content.Server/Light/EntitySystems/ExpendableLightSystem.cs index 29f5dd7f41..f4db4216cf 100644 --- a/Content.Server/Light/EntitySystems/ExpendableLightSystem.cs +++ b/Content.Server/Light/EntitySystems/ExpendableLightSystem.cs @@ -9,8 +9,6 @@ using Content.Shared.Temperature; using Content.Shared.Verbs; using JetBrains.Annotations; using Robust.Server.GameObjects; -using Robust.Shared.Audio; -using Robust.Shared.Player; using Robust.Shared.Utility; namespace Content.Server.Light.EntitySystems @@ -36,15 +34,18 @@ namespace Content.Server.Light.EntitySystems public override void Update(float frameTime) { - foreach (var light in EntityManager.EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var light)) { - UpdateLight(light, frameTime); + UpdateLight((uid, light), frameTime); } } - private void UpdateLight(ExpendableLightComponent component, float frameTime) + private void UpdateLight(Entity ent, float frameTime) { - if (!component.Activated) return; + var component = ent.Comp; + if (!component.Activated) + return; component.StateExpiryTime -= frameTime; @@ -56,25 +57,25 @@ namespace Content.Server.Light.EntitySystems component.CurrentState = ExpendableLightState.Fading; component.StateExpiryTime = component.FadeOutDuration; - UpdateVisualizer(component); + UpdateVisualizer(ent); break; default: case ExpendableLightState.Fading: component.CurrentState = ExpendableLightState.Dead; - var meta = MetaData(component.Owner); - _metaData.SetEntityName(component.Owner, Loc.GetString(component.SpentName), meta); - _metaData.SetEntityDescription(component.Owner, Loc.GetString(component.SpentDesc), meta); + var meta = MetaData(ent); + _metaData.SetEntityName(ent, Loc.GetString(component.SpentName), meta); + _metaData.SetEntityDescription(ent, Loc.GetString(component.SpentDesc), meta); - _tagSystem.AddTag(component.Owner, "Trash"); + _tagSystem.AddTag(ent, "Trash"); - UpdateSounds(component); - UpdateVisualizer(component); + UpdateSounds(ent); + UpdateVisualizer(ent); - if (TryComp(component.Owner, out var item)) + if (TryComp(ent, out var item)) { - _item.SetHeldPrefix(component.Owner, "unlit", item); + _item.SetHeldPrefix(ent, "unlit", item); } break; @@ -85,20 +86,21 @@ namespace Content.Server.Light.EntitySystems /// /// Enables the light if it is not active. Once active it cannot be turned off. /// - public bool TryActivate(ExpendableLightComponent component) + public bool TryActivate(Entity ent) { + var component = ent.Comp; if (!component.Activated && component.CurrentState == ExpendableLightState.BrandNew) { - if (TryComp(component.Owner, out var item)) + if (TryComp(ent, out var item)) { - _item.SetHeldPrefix(component.Owner, "lit", item); + _item.SetHeldPrefix(ent, "lit", item); } component.CurrentState = ExpendableLightState.Lit; component.StateExpiryTime = component.GlowDuration; - UpdateSounds(component); - UpdateVisualizer(component); + UpdateSounds(ent); + UpdateVisualizer(ent); return true; } @@ -106,49 +108,51 @@ namespace Content.Server.Light.EntitySystems return false; } - private void UpdateVisualizer(ExpendableLightComponent component, AppearanceComponent? appearance = null) + private void UpdateVisualizer(Entity ent, AppearanceComponent? appearance = null) { - if (!Resolve(component.Owner, ref appearance, false)) return; + var component = ent.Comp; + if (!Resolve(ent, ref appearance, false)) + return; - _appearance.SetData(appearance.Owner, ExpendableLightVisuals.State, component.CurrentState, appearance); + _appearance.SetData(ent, ExpendableLightVisuals.State, component.CurrentState, appearance); switch (component.CurrentState) { case ExpendableLightState.Lit: - _appearance.SetData(appearance.Owner, ExpendableLightVisuals.Behavior, component.TurnOnBehaviourID, appearance); + _appearance.SetData(ent, ExpendableLightVisuals.Behavior, component.TurnOnBehaviourID, appearance); break; case ExpendableLightState.Fading: - _appearance.SetData(appearance.Owner, ExpendableLightVisuals.Behavior, component.FadeOutBehaviourID, appearance); + _appearance.SetData(ent, ExpendableLightVisuals.Behavior, component.FadeOutBehaviourID, appearance); break; case ExpendableLightState.Dead: - _appearance.SetData(appearance.Owner, ExpendableLightVisuals.Behavior, string.Empty, appearance); + _appearance.SetData(ent, ExpendableLightVisuals.Behavior, string.Empty, appearance); var isHotEvent = new IsHotEvent() {IsHot = true}; - RaiseLocalEvent(component.Owner, isHotEvent); + RaiseLocalEvent(ent, isHotEvent); break; } } - private void UpdateSounds(ExpendableLightComponent component) + private void UpdateSounds(Entity ent) { - var uid = component.Owner; + var component = ent.Comp; switch (component.CurrentState) { case ExpendableLightState.Lit: - _audio.PlayPvs(component.LitSound, uid); + _audio.PlayPvs(component.LitSound, ent); break; case ExpendableLightState.Fading: break; default: - _audio.PlayPvs(component.DieSound, uid); + _audio.PlayPvs(component.DieSound, ent); break; } - if (TryComp(uid, out var clothing)) + if (TryComp(ent, out var clothing)) { - _clothing.SetEquippedPrefix(uid, component.Activated ? "Activated" : string.Empty, clothing); + _clothing.SetEquippedPrefix(ent, component.Activated ? "Activated" : string.Empty, clothing); } } @@ -163,21 +167,23 @@ namespace Content.Server.Light.EntitySystems EntityManager.EnsureComponent(uid); } - private void OnExpLightUse(EntityUid uid, ExpendableLightComponent component, UseInHandEvent args) + private void OnExpLightUse(Entity ent, ref UseInHandEvent args) { - if (args.Handled) return; + if (args.Handled) + return; + var isHotEvent = new IsHotEvent() {IsHot = true}; - RaiseLocalEvent(uid, isHotEvent); - if (TryActivate(component)) + RaiseLocalEvent(ent, isHotEvent); + if (TryActivate(ent)) args.Handled = true; } - private void AddIgniteVerb(EntityUid uid, ExpendableLightComponent component, GetVerbsEvent args) + private void AddIgniteVerb(Entity ent, ref GetVerbsEvent args) { if (!args.CanAccess || !args.CanInteract) return; - if (component.CurrentState != ExpendableLightState.BrandNew) + if (ent.Comp.CurrentState != ExpendableLightState.BrandNew) return; // Ignite the flare or make the glowstick glow. @@ -186,7 +192,7 @@ namespace Content.Server.Light.EntitySystems { Text = Loc.GetString("expendable-light-start-verb"), Icon = new SpriteSpecifier.Texture(new ("/Textures/Interface/VerbIcons/light.svg.192dpi.png")), - Act = () => TryActivate(component) + Act = () => TryActivate(ent) }; args.Verbs.Add(verb); } diff --git a/Content.Server/Light/EntitySystems/HandheldLightSystem.cs b/Content.Server/Light/EntitySystems/HandheldLightSystem.cs index ff3c61bc61..f3e7eaca0e 100644 --- a/Content.Server/Light/EntitySystems/HandheldLightSystem.cs +++ b/Content.Server/Light/EntitySystems/HandheldLightSystem.cs @@ -9,18 +9,14 @@ using Content.Shared.Light.Components; using Content.Shared.Rounding; using Content.Shared.Toggleable; using Content.Shared.Verbs; -using JetBrains.Annotations; -using Robust.Server.GameObjects; using Robust.Shared.Containers; using Robust.Shared.GameStates; -using Robust.Shared.Prototypes; using Robust.Shared.Utility; namespace Content.Server.Light.EntitySystems { public sealed class HandheldLightSystem : SharedHandheldLightSystem { - [Dependency] private readonly IPrototypeManager _proto = default!; [Dependency] private readonly ActionsSystem _actions = default!; [Dependency] private readonly ActionContainerSystem _actionContainer = default!; [Dependency] private readonly PopupSystem _popup = default!; @@ -31,7 +27,7 @@ namespace Content.Server.Light.EntitySystems // TODO: Ideally you'd be able to subscribe to power stuff to get events at certain percentages.. or something? // But for now this will be better anyway. - private readonly HashSet _activeLights = new(); + private readonly HashSet> _activeLights = new(); public override void Initialize() { @@ -55,22 +51,16 @@ namespace Content.Server.Light.EntitySystems SubscribeLocalEvent(OnEntRemoved); } - private void OnEntInserted( - EntityUid uid, - HandheldLightComponent component, - EntInsertedIntoContainerMessage args) + private void OnEntInserted(Entity ent, ref EntInsertedIntoContainerMessage args) { // Not guaranteed to be the correct container for our slot, I don't care. - UpdateLevel(uid, component); + UpdateLevel(ent); } - private void OnEntRemoved( - EntityUid uid, - HandheldLightComponent component, - EntRemovedFromContainerMessage args) + private void OnEntRemoved(Entity ent, ref EntRemovedFromContainerMessage args) { // Ditto above - UpdateLevel(uid, component); + UpdateLevel(ent); } private void OnGetActions(EntityUid uid, HandheldLightComponent component, GetItemActionsEvent args) @@ -78,28 +68,29 @@ namespace Content.Server.Light.EntitySystems args.AddAction(ref component.ToggleActionEntity, component.ToggleAction); } - private void OnToggleAction(EntityUid uid, HandheldLightComponent component, ToggleActionEvent args) + private void OnToggleAction(Entity ent, ref ToggleActionEvent args) { if (args.Handled) return; - if (component.Activated) - TurnOff(uid, component); + if (ent.Comp.Activated) + TurnOff(ent); else - TurnOn(args.Performer, uid, component); + TurnOn(args.Performer, ent); args.Handled = true; } - private void OnGetState(EntityUid uid, HandheldLightComponent component, ref ComponentGetState args) + private void OnGetState(Entity ent, ref ComponentGetState args) { - args.State = new HandheldLightComponent.HandheldLightComponentState(component.Activated, GetLevel(uid, component)); + args.State = new HandheldLightComponent.HandheldLightComponentState(ent.Comp.Activated, GetLevel(ent)); } - private void OnMapInit(EntityUid uid, HandheldLightComponent component, MapInitEvent args) + private void OnMapInit(Entity ent, ref MapInitEvent args) { - _actionContainer.EnsureAction(uid, ref component.ToggleActionEntity, component.ToggleAction); - _actions.AddAction(uid, ref component.SelfToggleActionEntity, component.ToggleAction); + var component = ent.Comp; + _actionContainer.EnsureAction(ent, ref component.ToggleActionEntity, component.ToggleAction); + _actions.AddAction(ent, ref component.SelfToggleActionEntity, component.ToggleAction); } private void OnShutdown(EntityUid uid, HandheldLightComponent component, ComponentShutdown args) @@ -108,31 +99,31 @@ namespace Content.Server.Light.EntitySystems _actions.RemoveAction(uid, component.SelfToggleActionEntity); } - private byte? GetLevel(EntityUid uid, HandheldLightComponent component) + private byte? GetLevel(Entity ent) { // Curently every single flashlight has the same number of levels for status and that's all it uses the charge for // Thus we'll just check if the level changes. - if (!_powerCell.TryGetBatteryFromSlot(uid, out var battery)) + if (!_powerCell.TryGetBatteryFromSlot(ent, out var battery)) return null; - if (MathHelper.CloseToPercent(battery.CurrentCharge, 0) || component.Wattage > battery.CurrentCharge) + if (MathHelper.CloseToPercent(battery.CurrentCharge, 0) || ent.Comp.Wattage > battery.CurrentCharge) return 0; return (byte?) ContentHelpers.RoundToNearestLevels(battery.CurrentCharge / battery.MaxCharge * 255, 255, HandheldLightComponent.StatusLevels); } - private void OnRemove(EntityUid uid, HandheldLightComponent component, ComponentRemove args) + private void OnRemove(Entity ent, ref ComponentRemove args) { - _activeLights.Remove(component); + _activeLights.Remove(ent); } - private void OnActivate(EntityUid uid, HandheldLightComponent component, ActivateInWorldEvent args) + private void OnActivate(Entity ent, ref ActivateInWorldEvent args) { - if (args.Handled || !component.ToggleOnInteract) + if (args.Handled || !ent.Comp.ToggleOnInteract) return; - if (ToggleStatus(args.User, uid, component)) + if (ToggleStatus(args.User, ent)) args.Handled = true; } @@ -140,9 +131,9 @@ namespace Content.Server.Light.EntitySystems /// Illuminates the light if it is not active, extinguishes it if it is active. /// /// True if the light's status was toggled, false otherwise. - public bool ToggleStatus(EntityUid user, EntityUid uid, HandheldLightComponent component) + public bool ToggleStatus(EntityUid user, Entity ent) { - return component.Activated ? TurnOff(uid, component) : TurnOn(user, uid, component); + return ent.Comp.Activated ? TurnOff(ent) : TurnOn(user, ent); } private void OnExamine(EntityUid uid, HandheldLightComponent component, ExaminedEvent args) @@ -160,20 +151,20 @@ namespace Content.Server.Light.EntitySystems public override void Update(float frameTime) { - var toRemove = new RemQueue(); + var toRemove = new RemQueue>(); foreach (var handheld in _activeLights) { - var uid = handheld.Owner; - - if (handheld.Deleted) + if (handheld.Comp.Deleted) { toRemove.Add(handheld); continue; } - if (Paused(uid)) continue; - TryUpdate(uid, handheld, frameTime); + if (Paused(handheld)) + continue; + + TryUpdate(handheld, frameTime); } foreach (var light in toRemove) @@ -182,39 +173,41 @@ namespace Content.Server.Light.EntitySystems } } - private void AddToggleLightVerb(EntityUid uid, HandheldLightComponent component, GetVerbsEvent args) + private void AddToggleLightVerb(Entity ent, ref GetVerbsEvent args) { - if (!args.CanAccess || !args.CanInteract || !component.ToggleOnInteract) + if (!args.CanAccess || !args.CanInteract || !ent.Comp.ToggleOnInteract) return; + var @event = args; ActivationVerb verb = new() { Text = Loc.GetString("verb-common-toggle-light"), Icon = new SpriteSpecifier.Texture(new ("/Textures/Interface/VerbIcons/light.svg.192dpi.png")), - Act = component.Activated - ? () => TurnOff(uid, component) - : () => TurnOn(args.User, uid, component) + Act = ent.Comp.Activated + ? () => TurnOff(ent) + : () => TurnOn(@event.User, ent) }; args.Verbs.Add(verb); } - public bool TurnOff(EntityUid uid, HandheldLightComponent component, bool makeNoise = true) + public bool TurnOff(Entity ent, bool makeNoise = true) { - if (!component.Activated || !_lights.TryGetLight(uid, out var pointLightComponent)) + if (!ent.Comp.Activated || !_lights.TryGetLight(ent, out var pointLightComponent)) { return false; } - _lights.SetEnabled(uid, false, pointLightComponent); - SetActivated(uid, false, component, makeNoise); - component.Level = null; - _activeLights.Remove(component); + _lights.SetEnabled(ent, false, pointLightComponent); + SetActivated(ent, false, ent, makeNoise); + ent.Comp.Level = null; + _activeLights.Remove(ent); return true; } - public bool TurnOn(EntityUid user, EntityUid uid, HandheldLightComponent component) + public bool TurnOn(EntityUid user, Entity uid) { + var component = uid.Comp; if (component.Activated || !_lights.TryGetLight(uid, out var pointLightComponent)) { return false; @@ -240,17 +233,18 @@ namespace Content.Server.Light.EntitySystems _lights.SetEnabled(uid, true, pointLightComponent); SetActivated(uid, true, component, true); - _activeLights.Add(component); + _activeLights.Add(uid); return true; } - public void TryUpdate(EntityUid uid, HandheldLightComponent component, float frameTime) + public void TryUpdate(Entity uid, float frameTime) { + var component = uid.Comp; if (!_powerCell.TryGetBatteryFromSlot(uid, out var battery) && !TryComp(uid, out battery)) { - TurnOff(uid, component, false); + TurnOff(uid, false); return; } @@ -271,20 +265,20 @@ namespace Content.Server.Light.EntitySystems } if (component.Activated && !battery.TryUseCharge(component.Wattage * frameTime)) - TurnOff(uid, component, false); + TurnOff(uid, false); - UpdateLevel(uid, component); + UpdateLevel(uid); } - private void UpdateLevel(EntityUid uid, HandheldLightComponent comp) + private void UpdateLevel(Entity ent) { - var level = GetLevel(uid, comp); + var level = GetLevel(ent); - if (level == comp.Level) + if (level == ent.Comp.Level) return; - comp.Level = level; - Dirty(comp); + ent.Comp.Level = level; + Dirty(ent); } } } diff --git a/Content.Server/Light/EntitySystems/MatchboxSystem.cs b/Content.Server/Light/EntitySystems/MatchboxSystem.cs index 606b2c0022..9a73e44f87 100644 --- a/Content.Server/Light/EntitySystems/MatchboxSystem.cs +++ b/Content.Server/Light/EntitySystems/MatchboxSystem.cs @@ -21,7 +21,7 @@ namespace Content.Server.Light.EntitySystems && EntityManager.TryGetComponent(args.Used, out MatchstickComponent? matchstick) && matchstick.CurrentState == SmokableState.Unlit) { - _stickSystem.Ignite(args.Used, matchstick, args.User); + _stickSystem.Ignite((args.Used, matchstick), args.User); args.Handled = true; } } diff --git a/Content.Server/Light/EntitySystems/MatchstickSystem.cs b/Content.Server/Light/EntitySystems/MatchstickSystem.cs index 7fe8aa9237..88f416ce9d 100644 --- a/Content.Server/Light/EntitySystems/MatchstickSystem.cs +++ b/Content.Server/Light/EntitySystems/MatchstickSystem.cs @@ -19,7 +19,7 @@ namespace Content.Server.Light.EntitySystems [Dependency] private readonly SharedPointLightSystem _lights = default!; [Dependency] private readonly TransformSystem _transformSystem = default!; - private HashSet _litMatches = new(); + private readonly HashSet> _litMatches = new(); public override void Initialize() { @@ -29,42 +29,43 @@ namespace Content.Server.Light.EntitySystems SubscribeLocalEvent(OnShutdown); } - private void OnShutdown(EntityUid uid, MatchstickComponent component, ComponentShutdown args) + private void OnShutdown(Entity ent, ref ComponentShutdown args) { - _litMatches.Remove(component); + _litMatches.Remove(ent); } public override void Update(float frameTime) { base.Update(frameTime); + foreach (var match in _litMatches) { - if (match.CurrentState != SmokableState.Lit || Paused(match.Owner) || match.Deleted) + if (match.Comp.CurrentState != SmokableState.Lit || Paused(match) || match.Comp.Deleted) continue; - var xform = Transform(match.Owner); + var xform = Transform(match); if (xform.GridUid is not {} gridUid) return; - var position = _transformSystem.GetGridOrMapTilePosition(match.Owner, xform); + var position = _transformSystem.GetGridOrMapTilePosition(match, xform); - _atmosphereSystem.HotspotExpose(gridUid, position, 400, 50, match.Owner, true); + _atmosphereSystem.HotspotExpose(gridUid, position, 400, 50, match, true); } } - private void OnInteractUsing(EntityUid uid, MatchstickComponent component, InteractUsingEvent args) + private void OnInteractUsing(Entity ent, ref InteractUsingEvent args) { - if (args.Handled || component.CurrentState != SmokableState.Unlit) + if (args.Handled || ent.Comp.CurrentState != SmokableState.Unlit) return; var isHotEvent = new IsHotEvent(); - RaiseLocalEvent(args.Used, isHotEvent, false); + RaiseLocalEvent(args.Used, isHotEvent); if (!isHotEvent.IsHot) return; - Ignite(uid, component, args.User); + Ignite(ent, args.User); args.Handled = true; } @@ -73,19 +74,21 @@ namespace Content.Server.Light.EntitySystems args.IsHot = component.CurrentState == SmokableState.Lit; } - public void Ignite(EntityUid uid, MatchstickComponent component, EntityUid user) + public void Ignite(Entity matchstick, EntityUid user) { + var component = matchstick.Comp; + // Play Sound - SoundSystem.Play(component.IgniteSound.GetSound(), Filter.Pvs(component.Owner), - component.Owner, AudioHelpers.WithVariation(0.125f).WithVolume(-0.125f)); + SoundSystem.Play(component.IgniteSound.GetSound(), Filter.Pvs(matchstick), + matchstick, AudioHelpers.WithVariation(0.125f).WithVolume(-0.125f)); // Change state - SetState(uid, component, SmokableState.Lit); - _litMatches.Add(component); - component.Owner.SpawnTimer(component.Duration * 1000, delegate + SetState(matchstick, component, SmokableState.Lit); + _litMatches.Add(matchstick); + matchstick.Owner.SpawnTimer(component.Duration * 1000, delegate { - SetState(uid, component, SmokableState.Burnt); - _litMatches.Remove(component); + SetState(matchstick, component, SmokableState.Burnt); + _litMatches.Remove(matchstick); }); } diff --git a/Content.Server/Light/EntitySystems/PoweredLightSystem.cs b/Content.Server/Light/EntitySystems/PoweredLightSystem.cs index 69d9b66955..cd4322aa26 100644 --- a/Content.Server/Light/EntitySystems/PoweredLightSystem.cs +++ b/Content.Server/Light/EntitySystems/PoweredLightSystem.cs @@ -1,16 +1,20 @@ using Content.Server.Administration.Logs; using Content.Server.Clothing.Components; +using Content.Server.DeviceLinking.Events; +using Content.Server.DeviceLinking.Systems; using Content.Server.DeviceNetwork; using Content.Server.DeviceNetwork.Systems; +using Content.Server.Emp; using Content.Server.Ghost; using Content.Server.Light.Components; using Content.Server.Power.Components; -using Content.Server.Temperature.Components; using Content.Shared.Audio; using Content.Shared.Damage; using Content.Shared.Database; +using Content.Shared.DoAfter; using Content.Shared.Hands.EntitySystems; using Content.Shared.Interaction; +using Content.Shared.Inventory; using Content.Shared.Light; using Content.Shared.Light.Components; using Content.Shared.Popups; @@ -19,11 +23,6 @@ using Robust.Shared.Audio; using Robust.Shared.Containers; using Robust.Shared.Player; using Robust.Shared.Timing; -using Content.Shared.DoAfter; -using Content.Server.Emp; -using Content.Server.DeviceLinking.Events; -using Content.Server.DeviceLinking.Systems; -using Content.Shared.Inventory; namespace Content.Server.Light.EntitySystems { @@ -333,7 +332,7 @@ namespace Content.Server.Light.EntitySystems light.LastGhostBlink = time; ToggleBlinkingLight(uid, light, true); - light.Owner.SpawnTimer(light.GhostBlinkingTime, () => + uid.SpawnTimer(light.GhostBlinkingTime, () => { ToggleBlinkingLight(uid, light, false); }); diff --git a/Content.Server/Magic/MagicSystem.cs b/Content.Server/Magic/MagicSystem.cs index 9cca5fa32c..4fbd9e3ec7 100644 --- a/Content.Server/Magic/MagicSystem.cs +++ b/Content.Server/Magic/MagicSystem.cs @@ -16,13 +16,13 @@ using Content.Shared.Magic; using Content.Shared.Magic.Events; using Content.Shared.Maps; using Content.Shared.Physics; -using Robust.Shared.Spawners; using Content.Shared.Storage; using Robust.Server.GameObjects; using Robust.Shared.Audio; using Robust.Shared.Map; using Robust.Shared.Random; using Robust.Shared.Serialization.Manager; +using Robust.Shared.Spawners; namespace Content.Server.Magic; @@ -309,7 +309,7 @@ public sealed class MagicSystem : EntitySystem _boltsSystem.SetBoltsDown(entity, bolts, false); if (TryComp(entity, out var doorComp) && doorComp.State is not DoorState.Open) - _doorSystem.StartOpening(doorComp.Owner); + _doorSystem.StartOpening(entity); } } diff --git a/Content.Server/MassMedia/Systems/NewsSystem.cs b/Content.Server/MassMedia/Systems/NewsSystem.cs index f5b17fefb8..98bfe702b6 100644 --- a/Content.Server/MassMedia/Systems/NewsSystem.cs +++ b/Content.Server/MassMedia/Systems/NewsSystem.cs @@ -1,25 +1,24 @@ +using System.Linq; +using Content.Server.Administration.Logs; +using Content.Server.CartridgeLoader; +using Content.Server.CartridgeLoader.Cartridges; +using Content.Server.GameTicking; using Content.Server.MassMedia.Components; using Content.Server.PDA.Ringer; +using Content.Server.Popups; +using Content.Server.StationRecords.Systems; using Content.Shared.Access.Components; using Content.Shared.Access.Systems; +using Content.Shared.CartridgeLoader; +using Content.Shared.CartridgeLoader.Cartridges; +using Content.Shared.Database; using Content.Shared.GameTicking; using Content.Shared.MassMedia.Components; using Content.Shared.MassMedia.Systems; using Content.Shared.PDA; using Robust.Server.GameObjects; -using System.Linq; -using Content.Server.Administration.Logs; -using Content.Server.CartridgeLoader.Cartridges; -using Content.Shared.CartridgeLoader; -using Content.Shared.CartridgeLoader.Cartridges; -using Content.Server.CartridgeLoader; -using Content.Server.GameTicking; -using Robust.Shared.Timing; -using Content.Server.Popups; -using Content.Server.StationRecords.Systems; -using Content.Shared.Database; using Robust.Shared.Containers; -using Robust.Shared.Utility; +using Robust.Shared.Timing; namespace Content.Server.MassMedia.Systems; @@ -222,7 +221,7 @@ public sealed class NewsSystem : EntitySystem while (query.MoveNext(out var owner, out var comp)) { if (EntityManager.TryGetComponent(comp.ActiveProgram, out var cartridge)) - UpdateReadUi(cartridge.Owner, comp.Owner, cartridge); + UpdateReadUi(comp.ActiveProgram.Value, owner, cartridge); } } @@ -267,14 +266,14 @@ public sealed class NewsSystem : EntitySystem base.Update(frameTime); var query = EntityQueryEnumerator(); - while (query.MoveNext(out var comp)) + while (query.MoveNext(out var uid, out var comp)) { if (comp.ShareAvalible || _timing.CurTime < comp.NextShare) continue; comp.ShareAvalible = true; - UpdateWriteUi(comp.Owner, comp); + UpdateWriteUi(uid, comp); } } } diff --git a/Content.Server/Mech/Systems/MechSystem.Filtering.cs b/Content.Server/Mech/Systems/MechSystem.Filtering.cs index 930a2afbd1..3de151ba70 100644 --- a/Content.Server/Mech/Systems/MechSystem.Filtering.cs +++ b/Content.Server/Mech/Systems/MechSystem.Filtering.cs @@ -3,7 +3,6 @@ using Content.Server.Atmos.Piping.Components; using Content.Server.Mech.Components; using Content.Shared.Atmos; using Content.Shared.Mech.Components; -using Robust.Shared.GameObjects; namespace Content.Server.Mech.Systems; @@ -58,9 +57,9 @@ public sealed partial class MechSystem var coordinates = Transform(uid).MapPosition; GasMixture? destination = null; - if (_map.TryFindGridAt(coordinates, out _, out var grid)) + if (_map.TryFindGridAt(coordinates, out var gridId, out var grid)) { - var tile = grid.GetTileRef(coordinates); + var tile = _mapSystem.GetTileRef(gridId, grid, coordinates); destination = _atmosphere.GetTileMixture(tile.GridUid, null, tile.GridIndices, true); } diff --git a/Content.Server/Mech/Systems/MechSystem.cs b/Content.Server/Mech/Systems/MechSystem.cs index 8c34f875bf..fd8f8fd767 100644 --- a/Content.Server/Mech/Systems/MechSystem.cs +++ b/Content.Server/Mech/Systems/MechSystem.cs @@ -32,6 +32,7 @@ public sealed partial class MechSystem : SharedMechSystem [Dependency] private readonly ContainerSystem _container = default!; [Dependency] private readonly DamageableSystem _damageable = default!; [Dependency] private readonly IMapManager _map = default!; + [Dependency] private readonly MapSystem _mapSystem = default!; [Dependency] private readonly SharedDoAfterSystem _doAfter = default!; [Dependency] private readonly SharedPopupSystem _popup = default!; [Dependency] private readonly UserInterfaceSystem _ui = default!; diff --git a/Content.Server/Medical/BiomassReclaimer/BiomassReclaimerSystem.cs b/Content.Server/Medical/BiomassReclaimer/BiomassReclaimerSystem.cs index 45f8d2ed98..f16d13c23c 100644 --- a/Content.Server/Medical/BiomassReclaimer/BiomassReclaimerSystem.cs +++ b/Content.Server/Medical/BiomassReclaimer/BiomassReclaimerSystem.cs @@ -51,7 +51,8 @@ namespace Content.Server.Medical.BiomassReclaimer { base.Update(frameTime); - foreach (var (_, reclaimer) in EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var _, out var reclaimer)) { reclaimer.ProcessingTimer -= frameTime; reclaimer.RandomMessTimer -= frameTime; @@ -62,11 +63,11 @@ namespace Content.Server.Medical.BiomassReclaimer { Solution blood = new(); blood.AddReagent(reclaimer.BloodReagent, 50); - _puddleSystem.TrySpillAt(reclaimer.Owner, blood, out _); + _puddleSystem.TrySpillAt(uid, blood, out _); } if (_robustRandom.Prob(0.03f) && reclaimer.SpawnedEntities.Count > 0) { - var thrown = Spawn(_robustRandom.Pick(reclaimer.SpawnedEntities).PrototypeId, Transform(reclaimer.Owner).Coordinates); + var thrown = Spawn(_robustRandom.Pick(reclaimer.SpawnedEntities).PrototypeId, Transform(uid).Coordinates); var direction = new Vector2(_robustRandom.Next(-30, 30), _robustRandom.Next(-30, 30)); _throwing.TryThrow(thrown, direction, _robustRandom.Next(1, 10)); } @@ -78,11 +79,11 @@ namespace Content.Server.Medical.BiomassReclaimer continue; } - _material.SpawnMultipleFromMaterial(reclaimer.CurrentExpectedYield, "Biomass", Transform(reclaimer.Owner).Coordinates); + _material.SpawnMultipleFromMaterial(reclaimer.CurrentExpectedYield, "Biomass", Transform(uid).Coordinates); reclaimer.BloodReagent = null; reclaimer.SpawnedEntities.Clear(); - RemCompDeferred(reclaimer.Owner); + RemCompDeferred(uid); } } public override void Initialize() @@ -100,19 +101,19 @@ namespace Content.Server.Medical.BiomassReclaimer SubscribeLocalEvent(OnDoAfter); } - private void OnSuicide(EntityUid uid, BiomassReclaimerComponent component, SuicideEvent args) + private void OnSuicide(Entity ent, ref SuicideEvent args) { if (args.Handled) return; - if (HasComp(uid)) + if (HasComp(ent)) return; - if (TryComp(uid, out var power) && !power.Powered) + if (TryComp(ent, out var power) && !power.Powered) return; - _popup.PopupEntity(Loc.GetString("biomass-reclaimer-suicide-others", ("victim", args.Victim)), uid, PopupType.LargeCaution); - StartProcessing(args.Victim, component); + _popup.PopupEntity(Loc.GetString("biomass-reclaimer-suicide-others", ("victim", args.Victim)), ent, PopupType.LargeCaution); + StartProcessing(args.Victim, ent); args.SetHandled(SuicideKind.Blunt); } @@ -137,22 +138,22 @@ namespace Content.Server.Medical.BiomassReclaimer EnsureComp(uid); } else - RemComp(component.Owner); + RemComp(uid); } private void OnUnanchorAttempt(EntityUid uid, ActiveBiomassReclaimerComponent component, UnanchorAttemptEvent args) { args.Cancel(); } - private void OnAfterInteractUsing(EntityUid uid, BiomassReclaimerComponent component, AfterInteractUsingEvent args) + private void OnAfterInteractUsing(Entity reclaimer, ref AfterInteractUsingEvent args) { if (!args.CanReach || args.Target == null) return; - if (!HasComp(args.Used) || !CanGib(uid, args.Used, component)) + if (!HasComp(args.Used) || !CanGib(reclaimer, args.Used)) return; - _doAfterSystem.TryStartDoAfter(new DoAfterArgs(EntityManager, args.User, 7f, new ReclaimerDoAfterEvent(), uid, target: args.Target, used: args.Used) + _doAfterSystem.TryStartDoAfter(new DoAfterArgs(EntityManager, args.User, 7f, new ReclaimerDoAfterEvent(), reclaimer, target: args.Target, used: args.Used) { BreakOnTargetMove = true, BreakOnUserMove = true, @@ -160,17 +161,17 @@ namespace Content.Server.Medical.BiomassReclaimer }); } - private void OnClimbedOn(EntityUid uid, BiomassReclaimerComponent component, ref ClimbedOnEvent args) + private void OnClimbedOn(Entity reclaimer, ref ClimbedOnEvent args) { - if (!CanGib(uid, args.Climber, component)) + if (!CanGib(reclaimer, args.Climber)) { var direction = new Vector2(_robustRandom.Next(-2, 2), _robustRandom.Next(-2, 2)); _throwing.TryThrow(args.Climber, direction, 0.5f); return; } - _adminLogger.Add(LogType.Action, LogImpact.Extreme, $"{ToPrettyString(args.Instigator):player} used a biomass reclaimer to gib {ToPrettyString(args.Climber):target} in {ToPrettyString(uid):reclaimer}"); + _adminLogger.Add(LogType.Action, LogImpact.Extreme, $"{ToPrettyString(args.Instigator):player} used a biomass reclaimer to gib {ToPrettyString(args.Climber):target} in {ToPrettyString(reclaimer):reclaimer}"); - StartProcessing(args.Climber, component); + StartProcessing(args.Climber, reclaimer); } private void OnRefreshParts(EntityUid uid, BiomassReclaimerComponent component, RefreshPartsEvent args) @@ -193,23 +194,24 @@ namespace Content.Server.Medical.BiomassReclaimer args.AddPercentageUpgrade("biomass-reclaimer-component-upgrade-biomass-yield", component.YieldPerUnitMass / component.BaseYieldPerUnitMass); } - private void OnDoAfter(EntityUid uid, BiomassReclaimerComponent component, DoAfterEvent args) + private void OnDoAfter(Entity reclaimer, ref ReclaimerDoAfterEvent args) { if (args.Handled || args.Cancelled || args.Args.Target == null || HasComp(args.Args.Target.Value)) return; - _adminLogger.Add(LogType.Action, LogImpact.Extreme, $"{ToPrettyString(args.Args.User):player} used a biomass reclaimer to gib {ToPrettyString(args.Args.Target.Value):target} in {ToPrettyString(uid):reclaimer}"); - StartProcessing(args.Args.Target.Value, component); + _adminLogger.Add(LogType.Action, LogImpact.Extreme, $"{ToPrettyString(args.Args.User):player} used a biomass reclaimer to gib {ToPrettyString(args.Args.Target.Value):target} in {ToPrettyString(reclaimer):reclaimer}"); + StartProcessing(args.Args.Target.Value, reclaimer); args.Handled = true; } - private void StartProcessing(EntityUid toProcess, BiomassReclaimerComponent component, PhysicsComponent? physics = null) + private void StartProcessing(EntityUid toProcess, Entity ent, PhysicsComponent? physics = null) { if (!Resolve(toProcess, ref physics)) return; - AddComp(component.Owner); + var component = ent.Comp; + AddComp(ent); if (TryComp(toProcess, out var stream)) { @@ -225,21 +227,21 @@ namespace Content.Server.Medical.BiomassReclaimer QueueDel(toProcess); } - private bool CanGib(EntityUid uid, EntityUid dragged, BiomassReclaimerComponent component) + private bool CanGib(Entity reclaimer, EntityUid dragged) { - if (HasComp(uid)) + if (HasComp(reclaimer)) return false; if (!HasComp(dragged)) return false; - if (!Transform(uid).Anchored) + if (!Transform(reclaimer).Anchored) return false; - if (TryComp(uid, out var power) && !power.Powered) + if (TryComp(reclaimer, out var power) && !power.Powered) return false; - if (component.SafetyEnabled && !_mobState.IsDead(dragged)) + if (reclaimer.Comp.SafetyEnabled && !_mobState.IsDead(dragged)) return false; // Reject souled bodies in easy mode. diff --git a/Content.Server/Medical/CryoPodSystem.cs b/Content.Server/Medical/CryoPodSystem.cs index 7dbaf03a2e..b94d6de6de 100644 --- a/Content.Server/Medical/CryoPodSystem.cs +++ b/Content.Server/Medical/CryoPodSystem.cs @@ -11,12 +11,14 @@ using Content.Server.NodeContainer.EntitySystems; using Content.Server.NodeContainer.NodeGroups; using Content.Server.NodeContainer.Nodes; using Content.Server.Power.Components; +using Content.Server.Temperature.Components; using Content.Server.UserInterface; 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.Climbing.Systems; using Content.Shared.Containers.ItemSlots; using Content.Shared.Database; using Content.Shared.DoAfter; @@ -30,8 +32,6 @@ using Content.Shared.Tools; using Content.Shared.Verbs; using Robust.Server.GameObjects; using Robust.Shared.Timing; -using Content.Server.Temperature.Components; -using Content.Shared.Climbing.Systems; namespace Content.Server.Medical; @@ -83,18 +83,20 @@ public sealed partial class CryoPodSystem: SharedCryoPodSystem var itemSlotsQuery = GetEntityQuery(); var fitsInDispenserQuery = GetEntityQuery(); var solutionContainerManagerQuery = GetEntityQuery(); - foreach (var (_, cryoPod) in EntityQuery()) + var query = EntityQueryEnumerator(); + + while (query.MoveNext(out var uid, out _, out var cryoPod)) { - metaDataQuery.TryGetComponent(cryoPod.Owner, out var metaDataComponent); - if (curTime < cryoPod.NextInjectionTime + _metaDataSystem.GetPauseTime(cryoPod.Owner, metaDataComponent)) + metaDataQuery.TryGetComponent(uid, out var metaDataComponent); + if (curTime < cryoPod.NextInjectionTime + _metaDataSystem.GetPauseTime(uid, metaDataComponent)) continue; cryoPod.NextInjectionTime = curTime + TimeSpan.FromSeconds(cryoPod.BeakerTransferTime); - if (!itemSlotsQuery.TryGetComponent(cryoPod.Owner, out var itemSlotsComponent)) + if (!itemSlotsQuery.TryGetComponent(uid, out var itemSlotsComponent)) { continue; } - var container = _itemSlotsSystem.GetItemOrNull(cryoPod.Owner, cryoPod.SolutionContainerName, itemSlotsComponent); + var container = _itemSlotsSystem.GetItemOrNull(uid, cryoPod.SolutionContainerName, itemSlotsComponent); var patient = cryoPod.BodyContainer.ContainedEntity; if (container != null && container.Value.Valid diff --git a/Content.Server/Medical/SuitSensors/SuitSensorSystem.cs b/Content.Server/Medical/SuitSensors/SuitSensorSystem.cs index ae28db3f29..f382d520ff 100644 --- a/Content.Server/Medical/SuitSensors/SuitSensorSystem.cs +++ b/Content.Server/Medical/SuitSensors/SuitSensorSystem.cs @@ -304,10 +304,10 @@ namespace Content.Server.Medical.SuitSensors var userJob = Loc.GetString("suit-sensor-component-unknown-job"); if (_idCardSystem.TryFindIdCard(sensor.User.Value, out var card)) { - if (card.FullName != null) - userName = card.FullName; - if (card.JobTitle != null) - userJob = card.JobTitle; + if (card.Comp.FullName != null) + userName = card.Comp.FullName; + if (card.Comp.JobTitle != null) + userJob = card.Comp.JobTitle; } // get health mob state diff --git a/Content.Server/Mind/Commands/RenameCommand.cs b/Content.Server/Mind/Commands/RenameCommand.cs index afdd1caf9b..5674da4ffd 100644 --- a/Content.Server/Mind/Commands/RenameCommand.cs +++ b/Content.Server/Mind/Commands/RenameCommand.cs @@ -61,12 +61,12 @@ public sealed class RenameCommand : IConsoleCommand { if (idCardSystem.TryFindIdCard(entityUid.Value, out var idCard)) { - idCardSystem.TryChangeFullName(idCard.Owner, name, idCard); + idCardSystem.TryChangeFullName(idCard, name, idCard); // Records // This is done here because ID cards are linked to station records if (_entManager.TrySystem(out var recordsSystem) - && _entManager.TryGetComponent(idCard.Owner, out StationRecordKeyStorageComponent? keyStorage) + && _entManager.TryGetComponent(idCard, out StationRecordKeyStorageComponent? keyStorage) && keyStorage.Key != null) { var origin = keyStorage.Key.Value.OriginStation; diff --git a/Content.Server/Morgue/CrematoriumSystem.cs b/Content.Server/Morgue/CrematoriumSystem.cs index d713b43f27..8d05d0abd1 100644 --- a/Content.Server/Morgue/CrematoriumSystem.cs +++ b/Content.Server/Morgue/CrematoriumSystem.cs @@ -174,12 +174,13 @@ public sealed class CrematoriumSystem : EntitySystem { base.Update(frameTime); - foreach (var (act, crem) in EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var act, out var crem)) { act.Accumulator += frameTime; if (act.Accumulator >= crem.CookTime) - FinishCooking(act.Owner, crem); + FinishCooking(uid, crem); } } } diff --git a/Content.Server/Morgue/MorgueSystem.cs b/Content.Server/Morgue/MorgueSystem.cs index 131689a139..b300336cd2 100644 --- a/Content.Server/Morgue/MorgueSystem.cs +++ b/Content.Server/Morgue/MorgueSystem.cs @@ -1,4 +1,3 @@ -using Content.Server.Morgue.Components; using Content.Server.Storage.Components; using Content.Shared.Body.Components; using Content.Shared.Examine; @@ -79,20 +78,21 @@ public sealed class MorgueSystem : EntitySystem { base.Update(frameTime); - foreach (var (comp, storage, appearance) in EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var comp, out var storage, out var appearance)) { comp.AccumulatedFrameTime += frameTime; - CheckContents(comp.Owner, comp, storage); + CheckContents(uid, comp, storage); if (comp.AccumulatedFrameTime < comp.BeepTime) continue; comp.AccumulatedFrameTime -= comp.BeepTime; - if (comp.DoSoulBeep && _appearance.TryGetData(appearance.Owner, MorgueVisuals.Contents, out var contents, appearance) && contents == MorgueContents.HasSoul) + if (comp.DoSoulBeep && _appearance.TryGetData(uid, MorgueVisuals.Contents, out var contents, appearance) && contents == MorgueContents.HasSoul) { - _audio.PlayPvs(comp.OccupantHasSoulAlarmSound, comp.Owner); + _audio.PlayPvs(comp.OccupantHasSoulAlarmSound, uid); } } } diff --git a/Content.Server/Movement/Systems/JetpackSystem.cs b/Content.Server/Movement/Systems/JetpackSystem.cs index 79b365be41..546336890f 100644 --- a/Content.Server/Movement/Systems/JetpackSystem.cs +++ b/Content.Server/Movement/Systems/JetpackSystem.cs @@ -26,11 +26,12 @@ public sealed class JetpackSystem : SharedJetpackSystem var toDisable = new ValueList<(EntityUid Uid, JetpackComponent Component)>(); var query = EntityQueryEnumerator(); - while (query.MoveNext(out var uid, out var active, out var comp, out var gasTank)) + while (query.MoveNext(out var uid, out var active, out var comp, out var gasTankComp)) { if (_timing.CurTime < active.TargetTime) continue; + var gasTank = (uid, gasTankComp); active.TargetTime = _timing.CurTime + TimeSpan.FromSeconds(active.EffectCooldown); var usedAir = _gasTank.RemoveAir(gasTank, comp.MoleUsage); diff --git a/Content.Server/NPC/Pathfinding/PathfindingSystem.Grid.cs b/Content.Server/NPC/Pathfinding/PathfindingSystem.Grid.cs index 72d6606c91..c430c71958 100644 --- a/Content.Server/NPC/Pathfinding/PathfindingSystem.Grid.cs +++ b/Content.Server/NPC/Pathfinding/PathfindingSystem.Grid.cs @@ -1,24 +1,20 @@ using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Numerics; using System.Threading; using System.Threading.Tasks; using Content.Server.Destructible; using Content.Shared.Access.Components; -using Content.Shared.Climbing; +using Content.Shared.Climbing.Components; using Content.Shared.Doors.Components; using Content.Shared.NPC; using Content.Shared.Physics; -using Microsoft.Extensions.ObjectPool; using Robust.Shared.Collections; using Robust.Shared.Map; using Robust.Shared.Map.Components; using Robust.Shared.Physics; -using Robust.Shared.Physics.Components; using Robust.Shared.Physics.Events; using Robust.Shared.Timing; using Robust.Shared.Utility; -using ClimbableComponent = Content.Shared.Climbing.Components.ClimbableComponent; namespace Content.Server.NPC.Pathfinding; @@ -102,6 +98,7 @@ public sealed partial class PathfindingSystem while (query.MoveNext(out var uid, out var comp)) { + var pathfinding = new Entity(uid, comp); // TODO: Dump all this shit and just do it live it's probably fast enough. if (comp.DirtyChunks.Count == 0 || curTime < comp.NextUpdate || @@ -120,7 +117,7 @@ public sealed partial class PathfindingSystem foreach (var origin in comp.DirtyChunks) { - var chunk = GetChunk(origin, uid, comp); + var chunk = GetChunk(origin, uid, pathfinding); dirt[idx] = chunk; idx++; } @@ -155,7 +152,7 @@ public sealed partial class PathfindingSystem var climbableQuery = GetEntityQuery(); var fixturesQuery = GetEntityQuery(); var xformQuery = GetEntityQuery(); - BuildBreadcrumbs(dirt[i], mapGridComp, accessQuery, destructibleQuery, doorQuery, climbableQuery, + BuildBreadcrumbs(dirt[i], (uid, mapGridComp), accessQuery, destructibleQuery, doorQuery, climbableQuery, fixturesQuery, xformQuery); }); @@ -204,7 +201,7 @@ public sealed partial class PathfindingSystem if (index != it1) return; - BuildNavmesh(chunk, comp); + BuildNavmesh(chunk, pathfinding); #if DEBUG Interlocked.Increment(ref updateCount); #endif @@ -254,24 +251,24 @@ public sealed partial class PathfindingSystem private void OnCollisionChange(ref CollisionChangeEvent ev) { - var xform = Transform(ev.Body.Owner); + var xform = Transform(ev.BodyUid); if (xform.GridUid == null) return; // This will also rebuild on door open / closes which I think is good? - var aabb = _lookup.GetAABBNoContainer(ev.Body.Owner, xform.Coordinates.Position, xform.LocalRotation); + var aabb = _lookup.GetAABBNoContainer(ev.BodyUid, xform.Coordinates.Position, xform.LocalRotation); DirtyChunkArea(xform.GridUid.Value, aabb); } private void OnCollisionLayerChange(ref CollisionLayerChangeEvent ev) { - var xform = Transform(ev.Body.Owner); + var xform = Transform(ev.Body); if (xform.GridUid == null) return; - var aabb = _lookup.GetAABBNoContainer(ev.Body.Owner, xform.Coordinates.Position, xform.LocalRotation); + var aabb = _lookup.GetAABBNoContainer(ev.Body, xform.Coordinates.Position, xform.LocalRotation); DirtyChunkArea(xform.GridUid.Value, aabb); } @@ -417,7 +414,7 @@ public sealed partial class PathfindingSystem } private void BuildBreadcrumbs(GridPathfindingChunk chunk, - MapGridComponent grid, + Entity grid, EntityQuery accessQuery, EntityQuery destructibleQuery, EntityQuery doorQuery, @@ -450,7 +447,7 @@ public sealed partial class PathfindingSystem var tilePos = new Vector2i(x, y) + gridOrigin; tilePolys.Clear(); - var tile = grid.GetTileRef(tilePos); + var tile = grid.Comp.GetTileRef(tilePos); var flags = tile.Tile.IsEmpty ? PathfindingBreadcrumbFlag.Space : PathfindingBreadcrumbFlag.None; // var isBorder = x < 0 || y < 0 || x == ChunkSize - 1 || y == ChunkSize - 1; @@ -469,7 +466,7 @@ public sealed partial class PathfindingSystem var xform = xformQuery.GetComponent(ent); if (xform.ParentUid != grid.Owner || - grid.LocalToTile(xform.Coordinates) != tilePos) + grid.Comp.LocalToTile(xform.Coordinates) != tilePos) { continue; } @@ -648,13 +645,13 @@ public sealed partial class PathfindingSystem var polyData = points[x * SubStep + poly.Left, y * SubStep + poly.Bottom].Data; var neighbors = new HashSet(); - tilePoly.Add(new PathPoly(grid.Owner, chunk.Origin, GetIndex(x, y), box, polyData, neighbors)); + tilePoly.Add(new PathPoly(grid, chunk.Origin, GetIndex(x, y), box, polyData, neighbors)); } } } // Log.Debug($"Built breadcrumbs in {sw.Elapsed.TotalMilliseconds}ms"); - SendBreadcrumbs(chunk, grid.Owner); + SendBreadcrumbs(chunk, grid); } /// @@ -729,12 +726,13 @@ public sealed partial class PathfindingSystem } } - private void BuildNavmesh(GridPathfindingChunk chunk, GridPathfindingComponent component) + private void BuildNavmesh(GridPathfindingChunk chunk, Entity pathfinding) { var sw = new Stopwatch(); sw.Start(); var chunkPolys = chunk.Polygons; + var component = pathfinding.Comp; component.Chunks.TryGetValue(chunk.Origin + new Vector2i(-1, 0), out var leftChunk); component.Chunks.TryGetValue(chunk.Origin + new Vector2i(0, -1), out var bottomChunk); component.Chunks.TryGetValue(chunk.Origin + new Vector2i(1, 0), out var rightChunk); @@ -840,7 +838,7 @@ public sealed partial class PathfindingSystem } // Log.Debug($"Built navmesh in {sw.Elapsed.TotalMilliseconds}ms"); - SendPolys(chunk, component.Owner, chunkPolys); + SendPolys(chunk, pathfinding, chunkPolys); } private void AddNeighbors(PathPoly polyA, PathPoly polyB) diff --git a/Content.Server/NPC/Pathfinding/PathfindingSystem.cs b/Content.Server/NPC/Pathfinding/PathfindingSystem.cs index d8ecebc12c..bb0eff7b39 100644 --- a/Content.Server/NPC/Pathfinding/PathfindingSystem.cs +++ b/Content.Server/NPC/Pathfinding/PathfindingSystem.cs @@ -5,7 +5,6 @@ using System.Threading; using System.Threading.Tasks; using Content.Server.Administration.Managers; using Content.Server.Destructible; -using Content.Server.NPC.HTN; using Content.Server.NPC.Systems; using Content.Shared.Administration; using Content.Shared.NPC; @@ -577,9 +576,10 @@ namespace Content.Server.NPC.Pathfinding { var msg = new PathBreadcrumbsMessage(); - foreach (var comp in EntityQuery(true)) + var query = AllEntityQuery(); + while (query.MoveNext(out var uid, out var comp)) { - var netGrid = GetNetEntity(comp.Owner); + var netGrid = GetNetEntity(uid); msg.Breadcrumbs.Add(netGrid, new Dictionary>(comp.Chunks.Count)); @@ -626,9 +626,10 @@ namespace Content.Server.NPC.Pathfinding { var msg = new PathPolysMessage(); - foreach (var comp in EntityQuery(true)) + var query = AllEntityQuery(); + while (query.MoveNext(out var uid, out var comp)) { - var netGrid = GetNetEntity(comp.Owner); + var netGrid = GetNetEntity(uid); msg.Polys.Add(netGrid, new Dictionary>>(comp.Chunks.Count)); diff --git a/Content.Server/NPC/Systems/NPCPerceptionSystem.RecentlyInjected.cs b/Content.Server/NPC/Systems/NPCPerceptionSystem.RecentlyInjected.cs index 5b0955a206..dd4ff6c65f 100644 --- a/Content.Server/NPC/Systems/NPCPerceptionSystem.RecentlyInjected.cs +++ b/Content.Server/NPC/Systems/NPCPerceptionSystem.RecentlyInjected.cs @@ -10,14 +10,15 @@ public sealed partial class NPCPerceptionSystem /// private void UpdateRecentlyInjected(float frameTime) { - foreach (var entity in EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var entity)) { entity.Accumulator += frameTime; if (entity.Accumulator < entity.RemoveTime.TotalSeconds) continue; entity.Accumulator = 0; - RemComp(entity.Owner); + RemComp(uid); } } } diff --git a/Content.Server/NPC/Systems/NPCUtilitySystem.cs b/Content.Server/NPC/Systems/NPCUtilitySystem.cs index d8ba19d238..4a9df0e663 100644 --- a/Content.Server/NPC/Systems/NPCUtilitySystem.cs +++ b/Content.Server/NPC/Systems/NPCUtilitySystem.cs @@ -365,7 +365,7 @@ public sealed class NPCUtilitySystem : EntitySystem var compZero = comps[0]; comps.RemoveAt(0); - foreach (var comp in _lookup.GetComponentsInRange(compZero.Component.GetType(), mapPos, vision)) + foreach (var comp in _lookup.GetEntitiesInRange(compZero.Component.GetType(), mapPos, vision)) { var ent = comp.Owner; diff --git a/Content.Server/NPC/Systems/NpcFactionSystem.cs b/Content.Server/NPC/Systems/NpcFactionSystem.cs index d6c23ca6af..08c9353411 100644 --- a/Content.Server/NPC/Systems/NpcFactionSystem.cs +++ b/Content.Server/NPC/Systems/NpcFactionSystem.cs @@ -1,7 +1,7 @@ -using Content.Server.NPC.Components; -using Robust.Shared.Prototypes; using System.Linq; +using Content.Server.NPC.Components; using JetBrains.Annotations; +using Robust.Shared.Prototypes; namespace Content.Server.NPC.Systems; @@ -160,15 +160,15 @@ public sealed partial class NpcFactionSystem : EntitySystem if (!xformQuery.TryGetComponent(entity, out var entityXform)) yield break; - foreach (var comp in _lookup.GetComponentsInRange(entityXform.MapPosition, range)) + foreach (var ent in _lookup.GetEntitiesInRange(entityXform.MapPosition, range)) { - if (comp.Owner == entity) + if (ent.Owner == entity) continue; - if (!factions.Overlaps(comp.Factions)) + if (!factions.Overlaps(ent.Comp.Factions)) continue; - yield return comp.Owner; + yield return ent.Owner; } } diff --git a/Content.Server/NodeContainer/EntitySystems/NodeContainerSystem.cs b/Content.Server/NodeContainer/EntitySystems/NodeContainerSystem.cs index d207f99422..99d18aeb3f 100644 --- a/Content.Server/NodeContainer/EntitySystems/NodeContainerSystem.cs +++ b/Content.Server/NodeContainer/EntitySystems/NodeContainerSystem.cs @@ -1,8 +1,8 @@ -using Content.Server.NodeContainer.Nodes; +using System.Diagnostics.CodeAnalysis; using Content.Server.NodeContainer.NodeGroups; +using Content.Server.NodeContainer.Nodes; using Content.Shared.Examine; using JetBrains.Annotations; -using System.Diagnostics.CodeAnalysis; namespace Content.Server.NodeContainer.EntitySystems { @@ -51,7 +51,7 @@ namespace Content.Server.NodeContainer.EntitySystems foreach (var (key, node) in component.Nodes) { node.Name = key; - node.Initialize(component.Owner, EntityManager); + node.Initialize(uid, EntityManager); } } diff --git a/Content.Server/Nuke/Commands/SendNukeCodesCommand.cs b/Content.Server/Nuke/Commands/SendNukeCodesCommand.cs index 55dca4f70d..d0e83e4f75 100644 --- a/Content.Server/Nuke/Commands/SendNukeCodesCommand.cs +++ b/Content.Server/Nuke/Commands/SendNukeCodesCommand.cs @@ -1,7 +1,5 @@ -using System.Linq; -using Content.Server.Administration; +using Content.Server.Administration; using Content.Server.Station.Components; -using Content.Server.Station.Systems; using Content.Shared.Administration; using JetBrains.Annotations; using Robust.Shared.Console; @@ -42,14 +40,14 @@ namespace Content.Server.Nuke.Commands return CompletionResult.Empty; } - var stations = _entityManager - .EntityQuery() - .Select(stationData => - { - var meta = _entityManager.GetComponent(stationData.Owner); + var stations = new List(); + var query = _entityManager.EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var stationData)) + { + var meta = _entityManager.GetComponent(uid); - return new CompletionOption(stationData.Owner.ToString(), meta.EntityName); - }); + stations.Add(new CompletionOption(uid.ToString(), meta.EntityName)); + } return CompletionResult.FromHintOptions(stations, null); } diff --git a/Content.Server/Nuke/NukeCodePaperSystem.cs b/Content.Server/Nuke/NukeCodePaperSystem.cs index 85e388e600..8df25feebf 100644 --- a/Content.Server/Nuke/NukeCodePaperSystem.cs +++ b/Content.Server/Nuke/NukeCodePaperSystem.cs @@ -1,5 +1,4 @@ using System.Diagnostics.CodeAnalysis; -using System.Linq; using Content.Server.Chat.Systems; using Content.Server.Fax; using Content.Server.Paper; @@ -103,9 +102,16 @@ namespace Content.Server.Nuke var codesMessage = new FormattedMessage(); // Find the first nuke that matches the passed location. - var query = EntityQuery().ToList(); - _random.Shuffle(query); - foreach (var nuke in query) + var nukes = new List>(); + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var nukeUid, out var nuke)) + { + nukes.Add((nukeUid, nuke)); + } + + _random.Shuffle(nukes); + + foreach (var (nukeUid, nuke) in nukes) { if (!onlyCurrentStation && (owningStation == null && @@ -116,7 +122,7 @@ namespace Content.Server.Nuke } codesMessage.PushNewline(); - codesMessage.AddMarkup(Loc.GetString("nuke-codes-list", ("name", MetaData(nuke.Owner).EntityName), ("code", nuke.Code))); + codesMessage.AddMarkup(Loc.GetString("nuke-codes-list", ("name", MetaData(nukeUid).EntityName), ("code", nuke.Code))); break; } diff --git a/Content.Server/Nutrition/EntitySystems/AnimalHusbandrySystem.cs b/Content.Server/Nutrition/EntitySystems/AnimalHusbandrySystem.cs index 94a80c4bd5..875c328bcb 100644 --- a/Content.Server/Nutrition/EntitySystems/AnimalHusbandrySystem.cs +++ b/Content.Server/Nutrition/EntitySystems/AnimalHusbandrySystem.cs @@ -1,6 +1,5 @@ using Content.Server.Administration.Logs; using Content.Server.Interaction.Components; -using Content.Server.Nutrition.Components; using Content.Server.Popups; using Content.Shared.Database; using Content.Shared.IdentityManagement; @@ -84,7 +83,8 @@ public sealed class AnimalHusbandrySystem : EntitySystem var xform = Transform(uid); - var partners = _entityLookup.GetComponentsInRange(xform.Coordinates, component.BreedRange); + var partners = new HashSet>(); + _entityLookup.GetEntitiesInRange(xform.Coordinates, component.BreedRange, partners); if (partners.Count >= component.Capacity) return false; diff --git a/Content.Server/Nutrition/EntitySystems/SliceableFoodSystem.cs b/Content.Server/Nutrition/EntitySystems/SliceableFoodSystem.cs index 81bba0eb79..88916e4cf2 100644 --- a/Content.Server/Nutrition/EntitySystems/SliceableFoodSystem.cs +++ b/Content.Server/Nutrition/EntitySystems/SliceableFoodSystem.cs @@ -1,5 +1,3 @@ -using Content.Server.Chemistry.EntitySystems; -using Content.Server.Nutrition; using Content.Server.Nutrition.Components; using Content.Shared.Chemistry.Components; using Content.Shared.Chemistry.Components.SolutionManager; @@ -8,7 +6,6 @@ using Content.Shared.Examine; using Content.Shared.FixedPoint; using Content.Shared.Hands.EntitySystems; using Content.Shared.Interaction; -using Content.Shared.Item; using Robust.Shared.Audio; using Robust.Shared.Containers; using Robust.Shared.Player; @@ -74,7 +71,7 @@ namespace Content.Server.Nutrition.EntitySystems else { var xform = Transform(sliceUid); - _containerSystem.AttachParentToContainerOrGrid(xform); + _containerSystem.AttachParentToContainerOrGrid((sliceUid, xform)); xform.LocalRotation = 0; } @@ -113,7 +110,7 @@ namespace Content.Server.Nutrition.EntitySystems else { var xform = Transform(sliceUid); - _containerSystem.AttachParentToContainerOrGrid(xform); + _containerSystem.AttachParentToContainerOrGrid((sliceUid, xform)); xform.LocalRotation = 0; } diff --git a/Content.Server/Payload/EntitySystems/PayloadSystem.cs b/Content.Server/Payload/EntitySystems/PayloadSystem.cs index 6e0b5cc515..f57024087d 100644 --- a/Content.Server/Payload/EntitySystems/PayloadSystem.cs +++ b/Content.Server/Payload/EntitySystems/PayloadSystem.cs @@ -96,8 +96,6 @@ public sealed class PayloadSystem : EntitySystem if (_componentFactory.GetComponent(registration.Type) is not Component component) continue; - component.Owner = uid; - var temp = (object) component; _serializationManager.CopyTo(data.Component, ref temp); EntityManager.AddComponent(uid, (Component)temp!); diff --git a/Content.Server/Physics/Controllers/RandomWalkController.cs b/Content.Server/Physics/Controllers/RandomWalkController.cs index 8cffa32dba..dc5608887e 100644 --- a/Content.Server/Physics/Controllers/RandomWalkController.cs +++ b/Content.Server/Physics/Controllers/RandomWalkController.cs @@ -1,13 +1,12 @@ +using Content.Server.Physics.Components; +using Content.Shared.Follower.Components; +using Content.Shared.Throwing; using Robust.Server.GameObjects; using Robust.Shared.Physics.Components; using Robust.Shared.Physics.Controllers; using Robust.Shared.Random; using Robust.Shared.Timing; -using Content.Server.Physics.Components; -using Content.Shared.Follower.Components; -using Content.Shared.Throwing; - namespace Content.Server.Physics.Controllers; /// @@ -39,16 +38,17 @@ internal sealed class RandomWalkController : VirtualController { base.UpdateBeforeSolve(prediction, frameTime); - foreach(var (randomWalk, physics) in EntityManager.EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var randomWalk, out var physics)) { - if (EntityManager.HasComponent(randomWalk.Owner) - || EntityManager.HasComponent(randomWalk.Owner) - || EntityManager.HasComponent(randomWalk.Owner)) + if (EntityManager.HasComponent(uid) + || EntityManager.HasComponent(uid) + || EntityManager.HasComponent(uid)) continue; var curTime = _timing.CurTime; if (randomWalk.NextStepTime <= curTime) - Update(randomWalk.Owner, randomWalk, physics); + Update(uid, randomWalk, physics); } } @@ -65,7 +65,7 @@ internal sealed class RandomWalkController : VirtualController var curTime = _timing.CurTime; randomWalk.NextStepTime = curTime + TimeSpan.FromSeconds(_random.NextDouble(randomWalk.MinStepCooldown.TotalSeconds, randomWalk.MaxStepCooldown.TotalSeconds)); - if(!Resolve(randomWalk.Owner, ref physics)) + if(!Resolve(uid, ref physics)) return; var pushAngle = _random.NextAngle(); diff --git a/Content.Server/Pinpointer/ProximityBeeperSystem.cs b/Content.Server/Pinpointer/ProximityBeeperSystem.cs index 2083a3d985..b473d97372 100644 --- a/Content.Server/Pinpointer/ProximityBeeperSystem.cs +++ b/Content.Server/Pinpointer/ProximityBeeperSystem.cs @@ -64,11 +64,8 @@ public sealed class ProximityBeeperSystem : EntitySystem var xform = xformQuery.GetComponent(uid); var compType = EntityManager.ComponentFactory.GetRegistration(component.Component).Type; float? closestDistance = null; - foreach (var comp in _entityLookup.GetComponentsInRange(compType, xform.MapPosition, component.MaximumDistance)) + foreach (var ent in _entityLookup.GetEntitiesInRange(compType, xform.MapPosition, component.MaximumDistance)) { - // forgive me father, for i have sinned. - var ent = comp.Owner; - var dist = (_transform.GetWorldPosition(xform, xformQuery) - _transform.GetWorldPosition(ent, xformQuery)).Length(); if (dist >= (closestDistance ?? float.MaxValue)) continue; diff --git a/Content.Server/PneumaticCannon/PneumaticCannonSystem.cs b/Content.Server/PneumaticCannon/PneumaticCannonSystem.cs index cbfc263018..f16a327e6b 100644 --- a/Content.Server/PneumaticCannon/PneumaticCannonSystem.cs +++ b/Content.Server/PneumaticCannon/PneumaticCannonSystem.cs @@ -70,10 +70,11 @@ public sealed class PneumaticCannonSystem : SharedPneumaticCannonSystem args.Cancel(); } - private void OnShoot(EntityUid uid, PneumaticCannonComponent component, ref GunShotEvent args) + private void OnShoot(Entity cannon, ref GunShotEvent args) { + var (uid, component) = cannon; // require a gas tank if it uses gas - var gas = GetGas(uid); + var gas = GetGas(cannon); if (gas == null && component.GasUsage > 0f) return; @@ -82,7 +83,7 @@ public sealed class PneumaticCannonSystem : SharedPneumaticCannonSystem { _stun.TryParalyze(args.User, TimeSpan.FromSeconds(component.HighPowerStunTime), true, status); Popup.PopupEntity(Loc.GetString("pneumatic-cannon-component-power-stun", - ("cannon", component.Owner)), uid, args.User); + ("cannon", uid)), cannon, args.User); } // ignore gas stuff if the cannon doesn't use any @@ -90,14 +91,14 @@ public sealed class PneumaticCannonSystem : SharedPneumaticCannonSystem return; // this should always be possible, as we'll eject the gas tank when it no longer is - var environment = _atmos.GetContainingMixture(component.Owner, false, true); - var removed = _gasTank.RemoveAir(gas, component.GasUsage); + var environment = _atmos.GetContainingMixture(cannon, false, true); + var removed = _gasTank.RemoveAir(gas.Value, component.GasUsage); if (environment != null && removed != null) { _atmos.Merge(environment, removed); } - if (gas.Air.TotalMoles >= component.GasUsage) + if (gas.Value.Comp.Air.TotalMoles >= component.GasUsage) return; // eject gas tank @@ -107,13 +108,13 @@ public sealed class PneumaticCannonSystem : SharedPneumaticCannonSystem /// /// Returns whether the pneumatic cannon has enough gas to shoot an item, as well as the tank itself. /// - private GasTankComponent? GetGas(EntityUid uid) + private Entity? GetGas(EntityUid uid) { if (!Container.TryGetContainer(uid, PneumaticCannonComponent.TankSlotId, out var container) || container is not ContainerSlot slot || slot.ContainedEntity is not {} contained) return null; - return TryComp(contained, out var gasTank) ? gasTank : null; + return TryComp(contained, out var gasTank) ? (contained, gasTank) : null; } private float GetProjectileSpeedFromPower(PneumaticCannonComponent component) diff --git a/Content.Server/Pointing/EntitySystems/PointingSystem.cs b/Content.Server/Pointing/EntitySystems/PointingSystem.cs index 8f00125ea3..b253e32e37 100644 --- a/Content.Server/Pointing/EntitySystems/PointingSystem.cs +++ b/Content.Server/Pointing/EntitySystems/PointingSystem.cs @@ -166,7 +166,7 @@ namespace Content.Server.Pointing.EntitySystems { var arrowVisibility = EntityManager.EnsureComponent(arrow); layer = playerVisibility.Layer; - _visibilitySystem.SetLayer(arrowVisibility, layer); + _visibilitySystem.SetLayer(arrow, arrowVisibility, layer); } // Get players that are in range and whose visibility layer matches the arrow's. @@ -274,26 +274,28 @@ namespace Content.Server.Pointing.EntitySystems { var currentTime = _gameTiming.CurTime; - foreach (var component in EntityQuery(true)) + var query = AllEntityQuery(); + while (query.MoveNext(out var uid, out var component)) { - Update(component, currentTime); + Update((uid, component), currentTime); } } - private void Update(PointingArrowComponent component, TimeSpan currentTime) + private void Update(Entity pointing, TimeSpan currentTime) { // TODO: That pause PR + var component = pointing.Comp; if (component.EndTime > currentTime) return; if (component.Rogue) { - RemComp(component.Owner); - EnsureComp(component.Owner); + RemComp(pointing); + EnsureComp(pointing); return; } - Del(component.Owner); + Del(pointing); } } } diff --git a/Content.Server/Pointing/EntitySystems/RoguePointingSystem.cs b/Content.Server/Pointing/EntitySystems/RoguePointingSystem.cs index 160dc80fc3..be3ceb3b08 100644 --- a/Content.Server/Pointing/EntitySystems/RoguePointingSystem.cs +++ b/Content.Server/Pointing/EntitySystems/RoguePointingSystem.cs @@ -1,12 +1,8 @@ -using System.Linq; using Content.Server.Explosion.EntitySystems; using Content.Server.Pointing.Components; using Content.Shared.Pointing.Components; using JetBrains.Annotations; -using Robust.Server.GameObjects; -using Robust.Shared.Player; using Robust.Shared.Random; -using DrawDepth = Content.Shared.DrawDepth.DrawDepth; namespace Content.Server.Pointing.EntitySystems { @@ -22,14 +18,19 @@ namespace Content.Server.Pointing.EntitySystems if (!Resolve(uid, ref component, ref transform)) return null; - var targets = EntityQuery().ToList(); + var targets = new List>(); + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var angeringUid, out var angeringComp)) + { + targets.Add((angeringUid, angeringComp)); + } if (targets.Count == 0) return null; var angering = _random.Pick(targets); - angering.RemainingAnger -= 1; - if (angering.RemainingAnger <= 0) + angering.Comp.RemainingAnger -= 1; + if (angering.Comp.RemainingAnger <= 0) RemComp(uid); return angering.Owner; @@ -53,9 +54,9 @@ namespace Content.Server.Pointing.EntitySystems public override void Update(float frameTime) { - foreach (var (component, transform) in EntityManager.EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var component, out var transform)) { - var uid = component.Owner; component.Chasing ??= RandomNearbyPlayer(uid, component, transform); if (component.Chasing is not {Valid: true} chasing || Deleted(chasing)) @@ -68,7 +69,7 @@ namespace Content.Server.Pointing.EntitySystems if (component.TurningDelay > 0) { - var difference = EntityManager.GetComponent(chasing).WorldPosition - transform.WorldPosition; + var difference = Comp(chasing).WorldPosition - transform.WorldPosition; var angle = difference.ToAngle(); var adjusted = angle.Degrees + 90; var newAngle = Angle.FromDegrees(adjusted); @@ -83,7 +84,7 @@ namespace Content.Server.Pointing.EntitySystems UpdateAppearance(uid, component, transform); - var toChased = EntityManager.GetComponent(chasing).WorldPosition - transform.WorldPosition; + var toChased = Comp(chasing).WorldPosition - transform.WorldPosition; transform.WorldPosition += toChased * frameTime * component.ChasingSpeed; diff --git a/Content.Server/Polymorph/Systems/PolymorphSystem.cs b/Content.Server/Polymorph/Systems/PolymorphSystem.cs index 6a90928a44..fbf4961f4f 100644 --- a/Content.Server/Polymorph/Systems/PolymorphSystem.cs +++ b/Content.Server/Polymorph/Systems/PolymorphSystem.cs @@ -1,4 +1,3 @@ -using System.Linq; using Content.Server.Actions; using Content.Server.Humanoid; using Content.Server.Inventory; @@ -173,10 +172,9 @@ namespace Content.Server.Polymorph.Systems MakeSentientCommand.MakeSentient(child, EntityManager); var comp = _compFact.GetComponent(); - comp.Owner = child; comp.Parent = uid; comp.Prototype = proto.ID; - EntityManager.AddComponent(child, comp); + AddComp(child, comp); var childXform = Transform(child); childXform.LocalRotation = targetTransformComp.LocalRotation; diff --git a/Content.Server/Power/EntitySystems/CableSystem.Placer.cs b/Content.Server/Power/EntitySystems/CableSystem.Placer.cs index f4a38e7e65..c5ca36c3a1 100644 --- a/Content.Server/Power/EntitySystems/CableSystem.Placer.cs +++ b/Content.Server/Power/EntitySystems/CableSystem.Placer.cs @@ -1,11 +1,9 @@ using Content.Server.Administration.Logs; using Content.Server.Power.Components; -using Content.Server.Stack; using Content.Shared.Database; using Content.Shared.Interaction; using Content.Shared.Maps; using Content.Shared.Stacks; -using Robust.Shared.Map; namespace Content.Server.Power.EntitySystems; @@ -18,11 +16,14 @@ public sealed partial class CableSystem SubscribeLocalEvent(OnCablePlacerAfterInteract); } - private void OnCablePlacerAfterInteract(EntityUid uid, CablePlacerComponent component, AfterInteractEvent args) + private void OnCablePlacerAfterInteract(Entity placer, ref AfterInteractEvent args) { - if (args.Handled || !args.CanReach) return; + if (args.Handled || !args.CanReach) + return; - if (component.CablePrototypeId == null) return; + var component = placer.Comp; + if (component.CablePrototypeId == null) + return; if(!_mapManager.TryGetGrid(args.ClickLocation.GetGridUid(EntityManager), out var grid)) return; @@ -39,7 +40,7 @@ public sealed partial class CableSystem return; } - if (TryComp(component.Owner, out var stack) && !_stack.Use(component.Owner, 1, stack)) + if (TryComp(placer, out var stack) && !_stack.Use(placer, 1, stack)) return; var newCable = EntityManager.SpawnEntity(component.CablePrototypeId, grid.GridTileToLocal(snapPos)); diff --git a/Content.Server/Power/EntitySystems/ExtensionCableSystem.cs b/Content.Server/Power/EntitySystems/ExtensionCableSystem.cs index 0d88b442d3..9d68b60418 100644 --- a/Content.Server/Power/EntitySystems/ExtensionCableSystem.cs +++ b/Content.Server/Power/EntitySystems/ExtensionCableSystem.cs @@ -1,7 +1,7 @@ using System.Diagnostics.CodeAnalysis; -using System.Linq; using Content.Server.Power.Components; using Robust.Shared.Map; +using Robust.Shared.Map.Components; using Robust.Shared.Physics; using Robust.Shared.Physics.Components; @@ -50,9 +50,10 @@ namespace Content.Server.Power.EntitySystems var xform = Transform(uid); // If grid deleting no need to update power. - if (_mapManager.TryGetGrid(xform.GridUid, out var grid)) + if (HasComp(xform.GridUid) && + MetaData(xform.GridUid.Value).EntityLifeStage > EntityLifeStage.MapInitialized) { - if (MetaData(grid.Owner).EntityLifeStage > EntityLifeStage.MapInitialized) return; + return; } Disconnect(uid, provider); @@ -72,10 +73,10 @@ namespace Content.Server.Power.EntitySystems foreach (var receiver in FindAvailableReceivers(uid, provider.TransferRange)) { - receiver.Provider?.LinkedReceivers.Remove(receiver); - receiver.Provider = provider; + receiver.Comp.Provider?.LinkedReceivers.Remove(receiver); + receiver.Comp.Provider = provider; provider.LinkedReceivers.Add(receiver); - RaiseLocalEvent(receiver.Owner, new ProviderConnectedEvent(provider), broadcast: false); + RaiseLocalEvent(receiver, new ProviderConnectedEvent(provider), broadcast: false); RaiseLocalEvent(uid, new ReceiverConnectedEvent(receiver), broadcast: false); } } @@ -95,34 +96,37 @@ namespace Content.Server.Power.EntitySystems private void ResetReceivers(ExtensionCableProviderComponent provider) { + var providerId = provider.Owner; var receivers = provider.LinkedReceivers.ToArray(); provider.LinkedReceivers.Clear(); foreach (var receiver in receivers) { + var receiverId = receiver.Owner; receiver.Provider = null; - RaiseLocalEvent(receiver.Owner, new ProviderDisconnectedEvent(provider), broadcast: false); - RaiseLocalEvent(provider.Owner, new ReceiverDisconnectedEvent(receiver), broadcast: false); + RaiseLocalEvent(receiverId, new ProviderDisconnectedEvent(provider), broadcast: false); + RaiseLocalEvent(providerId, new ReceiverDisconnectedEvent((receiverId, receiver)), broadcast: false); } foreach (var receiver in receivers) { // No point resetting what the receiver is doing if it's deleting, plus significant perf savings // in not doing needless lookups - if (!EntityManager.IsQueuedForDeletion(receiver.Owner) - && MetaData(receiver.Owner).EntityLifeStage <= EntityLifeStage.MapInitialized) + var receiverId = receiver.Owner; + if (!EntityManager.IsQueuedForDeletion(receiverId) + && MetaData(receiverId).EntityLifeStage <= EntityLifeStage.MapInitialized) { TryFindAndSetProvider(receiver); } } } - private IEnumerable FindAvailableReceivers(EntityUid owner, float range) + private IEnumerable> FindAvailableReceivers(EntityUid owner, float range) { var xform = Transform(owner); var coordinates = xform.Coordinates; - if (!_mapManager.TryGetGrid(xform.GridUid, out var grid)) + if (!TryComp(xform.GridUid, out MapGridComponent? grid)) yield break; var nearbyEntities = grid.GetCellsInSquareArea(coordinates, (int) Math.Ceiling(range / grid.TileSize)); @@ -142,7 +146,7 @@ namespace Content.Server.Power.EntitySystems continue; if ((Transform(entity).LocalPosition - xform.LocalPosition).Length() < Math.Min(range, receiver.ReceptionRange)) - yield return receiver; + yield return (entity, receiver); } } @@ -161,7 +165,7 @@ namespace Content.Server.Power.EntitySystems if (provider != null) { - RaiseLocalEvent(provider.Owner, new ReceiverDisconnectedEvent(receiver), broadcast: false); + RaiseLocalEvent(provider.Owner, new ReceiverDisconnectedEvent((uid, receiver)), broadcast: false); provider.LinkedReceivers.Remove(receiver); } @@ -220,7 +224,7 @@ namespace Content.Server.Power.EntitySystems RaiseLocalEvent(uid, new ProviderDisconnectedEvent(receiver.Provider), broadcast: false); if (receiver.Provider != null) { - RaiseLocalEvent(receiver.Provider.Owner, new ReceiverDisconnectedEvent(receiver), broadcast: false); + RaiseLocalEvent(receiver.Provider.Owner, new ReceiverDisconnectedEvent((uid, receiver)), broadcast: false); receiver.Provider.LinkedReceivers.Remove(receiver); } @@ -229,19 +233,22 @@ namespace Content.Server.Power.EntitySystems private void TryFindAndSetProvider(ExtensionCableReceiverComponent receiver, TransformComponent? xform = null) { - if (!receiver.Connectable) return; + var uid = receiver.Owner; + if (!receiver.Connectable) + return; - if (!TryFindAvailableProvider(receiver.Owner, receiver.ReceptionRange, out var provider, xform)) return; + if (!TryFindAvailableProvider(uid, receiver.ReceptionRange, out var provider, xform)) + return; receiver.Provider = provider; provider.LinkedReceivers.Add(receiver); - RaiseLocalEvent(receiver.Owner, new ProviderConnectedEvent(provider), broadcast: false); - RaiseLocalEvent(provider.Owner, new ReceiverConnectedEvent(receiver), broadcast: false); + RaiseLocalEvent(uid, new ProviderConnectedEvent(provider), broadcast: false); + RaiseLocalEvent(provider.Owner, new ReceiverConnectedEvent((uid, receiver)), broadcast: false); } private bool TryFindAvailableProvider(EntityUid owner, float range, [NotNullWhen(true)] out ExtensionCableProviderComponent? foundProvider, TransformComponent? xform = null) { - if (!Resolve(owner, ref xform) || !_mapManager.TryGetGrid(xform.GridUid, out var grid)) + if (!Resolve(owner, ref xform) || !TryComp(xform.GridUid, out MapGridComponent? grid)) { foundProvider = null; return false; @@ -330,9 +337,9 @@ namespace Content.Server.Power.EntitySystems /// /// The that connected. /// - public ExtensionCableReceiverComponent Receiver; + public Entity Receiver; - public ReceiverConnectedEvent(ExtensionCableReceiverComponent receiver) + public ReceiverConnectedEvent(Entity receiver) { Receiver = receiver; } @@ -345,9 +352,9 @@ namespace Content.Server.Power.EntitySystems /// /// The that disconnected. /// - public ExtensionCableReceiverComponent Receiver; + public Entity Receiver; - public ReceiverDisconnectedEvent(ExtensionCableReceiverComponent receiver) + public ReceiverDisconnectedEvent(Entity receiver) { Receiver = receiver; } diff --git a/Content.Server/Power/EntitySystems/PowerNetSystem.cs b/Content.Server/Power/EntitySystems/PowerNetSystem.cs index 425f4637af..c39fc7e5fe 100644 --- a/Content.Server/Power/EntitySystems/PowerNetSystem.cs +++ b/Content.Server/Power/EntitySystems/PowerNetSystem.cs @@ -312,7 +312,7 @@ namespace Content.Server.Power.EntitySystems apcReceiver.PoweredLastUpdate = powered; var ev = new PowerChangedEvent(apcReceiver.Powered, apcReceiver.NetworkLoad.ReceivingPower); - RaiseLocalEvent(apcReceiver.Owner, ref ev); + RaiseLocalEvent(uid, ref ev); if (appearanceQuery.TryGetComponent(uid, out var appearance)) _appearance.SetData(uid, PowerDeviceVisuals.Powered, powered, appearance); @@ -342,7 +342,7 @@ namespace Content.Server.Power.EntitySystems private void UpdateNetworkBattery() { var enumerator = EntityQueryEnumerator(); - while (enumerator.MoveNext(out var powerNetBattery)) + while (enumerator.MoveNext(out var uid, out var powerNetBattery)) { var lastSupply = powerNetBattery.LastSupply; var currentSupply = powerNetBattery.CurrentSupply; @@ -350,12 +350,12 @@ namespace Content.Server.Power.EntitySystems if (lastSupply == 0f && currentSupply != 0f) { var ev = new PowerNetBatterySupplyEvent(true); - RaiseLocalEvent(powerNetBattery.Owner, ref ev); + RaiseLocalEvent(uid, ref ev); } else if (lastSupply > 0f && currentSupply == 0f) { var ev = new PowerNetBatterySupplyEvent(false); - RaiseLocalEvent(powerNetBattery.Owner, ref ev); + RaiseLocalEvent(uid, ref ev); } powerNetBattery.LastSupply = currentSupply; diff --git a/Content.Server/Power/EntitySystems/PowerReceiverSystem.cs b/Content.Server/Power/EntitySystems/PowerReceiverSystem.cs index 35412d1742..f1f8bf0616 100644 --- a/Content.Server/Power/EntitySystems/PowerReceiverSystem.cs +++ b/Content.Server/Power/EntitySystems/PowerReceiverSystem.cs @@ -73,35 +73,35 @@ namespace Content.Server.Power.EntitySystems component.LinkedReceivers.Clear(); } - private void OnProviderConnected(EntityUid uid, ApcPowerReceiverComponent receiver, ExtensionCableSystem.ProviderConnectedEvent args) + private void OnProviderConnected(Entity receiver, ref ExtensionCableSystem.ProviderConnectedEvent args) { var providerUid = args.Provider.Owner; if (!EntityManager.TryGetComponent(providerUid, out var provider)) return; - receiver.Provider = provider; + receiver.Comp.Provider = provider; ProviderChanged(receiver); } - private void OnProviderDisconnected(EntityUid uid, ApcPowerReceiverComponent receiver, ExtensionCableSystem.ProviderDisconnectedEvent args) + private void OnProviderDisconnected(Entity receiver, ref ExtensionCableSystem.ProviderDisconnectedEvent args) { - receiver.Provider = null; + receiver.Comp.Provider = null; ProviderChanged(receiver); } - private void OnReceiverConnected(EntityUid uid, ApcPowerProviderComponent provider, ExtensionCableSystem.ReceiverConnectedEvent args) + private void OnReceiverConnected(Entity provider, ref ExtensionCableSystem.ReceiverConnectedEvent args) { - if (EntityManager.TryGetComponent(args.Receiver.Owner, out ApcPowerReceiverComponent? receiver)) + if (EntityManager.TryGetComponent(args.Receiver, out ApcPowerReceiverComponent? receiver)) { - provider.AddReceiver(receiver); + provider.Comp.AddReceiver(receiver); } } private void OnReceiverDisconnected(EntityUid uid, ApcPowerProviderComponent provider, ExtensionCableSystem.ReceiverDisconnectedEvent args) { - if (EntityManager.TryGetComponent(args.Receiver.Owner, out ApcPowerReceiverComponent? receiver)) + if (EntityManager.TryGetComponent(args.Receiver, out ApcPowerReceiverComponent? receiver)) { provider.RemoveReceiver(receiver); } @@ -134,13 +134,14 @@ namespace Content.Server.Power.EntitySystems args.Verbs.Add(verb); } - private void ProviderChanged(ApcPowerReceiverComponent receiver) + private void ProviderChanged(Entity receiver) { - receiver.NetworkLoad.LinkedNetwork = default; - var ev = new PowerChangedEvent(receiver.Powered, receiver.NetworkLoad.ReceivingPower); + var comp = receiver.Comp; + comp.NetworkLoad.LinkedNetwork = default; + var ev = new PowerChangedEvent(comp.Powered, comp.NetworkLoad.ReceivingPower); - RaiseLocalEvent(receiver.Owner, ref ev); - _appearance.SetData(receiver.Owner, PowerDeviceVisuals.Powered, receiver.Powered); + RaiseLocalEvent(receiver, ref ev); + _appearance.SetData(receiver, PowerDeviceVisuals.Powered, comp.Powered); } /// diff --git a/Content.Server/Radiation/Systems/GeigerSystem.cs b/Content.Server/Radiation/Systems/GeigerSystem.cs index 640a257694..3a2fe12549 100644 --- a/Content.Server/Radiation/Systems/GeigerSystem.cs +++ b/Content.Server/Radiation/Systems/GeigerSystem.cs @@ -32,54 +32,54 @@ public sealed class GeigerSystem : SharedGeigerSystem SubscribeLocalEvent(OnUpdate); } - private void OnActivate(EntityUid uid, GeigerComponent component, ActivateInWorldEvent args) + private void OnActivate(Entity geiger, ref ActivateInWorldEvent args) { - if (args.Handled || component.AttachedToSuit) + if (args.Handled || geiger.Comp.AttachedToSuit) return; args.Handled = true; - SetEnabled(uid, component, !component.IsEnabled); + SetEnabled(geiger, !geiger.Comp.IsEnabled); } - private void OnEquipped(EntityUid uid, GeigerComponent component, GotEquippedEvent args) + private void OnEquipped(Entity geiger, ref GotEquippedEvent args) { - if (component.AttachedToSuit) - SetEnabled(uid, component, true); - SetUser(component, args.Equipee); + if (geiger.Comp.AttachedToSuit) + SetEnabled(geiger, true); + SetUser(geiger, args.Equipee); } - private void OnEquippedHand(EntityUid uid, GeigerComponent component, GotEquippedHandEvent args) + private void OnEquippedHand(Entity geiger, ref GotEquippedHandEvent args) { - if (component.AttachedToSuit) + if (geiger.Comp.AttachedToSuit) return; - SetUser(component, args.User); + SetUser(geiger, args.User); } - private void OnUnequipped(EntityUid uid, GeigerComponent component, GotUnequippedEvent args) + private void OnUnequipped(Entity geiger, ref GotUnequippedEvent args) { - if (component.AttachedToSuit) - SetEnabled(uid, component, false); - SetUser(component, null); + if (geiger.Comp.AttachedToSuit) + SetEnabled(geiger, false); + SetUser(geiger, null); } - private void OnUnequippedHand(EntityUid uid, GeigerComponent component, GotUnequippedHandEvent args) + private void OnUnequippedHand(Entity geiger, ref GotUnequippedHandEvent args) { - if (component.AttachedToSuit) + if (geiger.Comp.AttachedToSuit) return; - SetUser(component, null); + SetUser(geiger, null); } private void OnUpdate(RadiationSystemUpdatedEvent ev) { // update only active geiger counters // deactivated shouldn't have rad receiver component - var query = EntityQuery(); - foreach (var (geiger, receiver) in query) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var geiger, out var receiver)) { var rads = receiver.CurrentRadiation; - SetCurrentRadiation(geiger.Owner, geiger, rads); + SetCurrentRadiation(uid, geiger, rads); } } @@ -101,21 +101,22 @@ public sealed class GeigerSystem : SharedGeigerSystem UpdateSound(uid, component); } - Dirty(component); + Dirty(uid, component); } - private void SetUser(GeigerComponent component, EntityUid? user) + private void SetUser(Entity component, EntityUid? user) { - if (component.User == user) + if (component.Comp.User == user) return; - component.User = user; + component.Comp.User = user; Dirty(component); - UpdateSound(component.Owner, component); + UpdateSound(component, component); } - private void SetEnabled(EntityUid uid, GeigerComponent component, bool isEnabled) + private void SetEnabled(Entity geiger, bool isEnabled) { + var component = geiger.Comp; if (component.IsEnabled == isEnabled) return; @@ -126,11 +127,11 @@ public sealed class GeigerSystem : SharedGeigerSystem component.DangerLevel = GeigerDangerLevel.None; } - _radiation.SetCanReceive(uid, isEnabled); + _radiation.SetCanReceive(geiger, isEnabled); - UpdateAppearance(uid, component); - UpdateSound(uid, component); - Dirty(component); + UpdateAppearance(geiger, component); + UpdateSound(geiger, component); + Dirty(geiger, component); } private void UpdateAppearance(EntityUid uid, GeigerComponent? component = null, diff --git a/Content.Server/Radiation/Systems/RadiationSystem.GridCast.cs b/Content.Server/Radiation/Systems/RadiationSystem.GridCast.cs index fa132186a9..1be8f0fb04 100644 --- a/Content.Server/Radiation/Systems/RadiationSystem.GridCast.cs +++ b/Content.Server/Radiation/Systems/RadiationSystem.GridCast.cs @@ -1,3 +1,4 @@ +using System.Linq; using System.Numerics; using Content.Server.Radiation.Components; using Content.Server.Radiation.Events; @@ -9,7 +10,6 @@ using Robust.Shared.Containers; using Robust.Shared.Map.Components; using Robust.Shared.Timing; using Robust.Shared.Utility; -using System.Linq; namespace Content.Server.Radiation.Systems; @@ -31,7 +31,7 @@ public partial class RadiationSystem stopwatch.Start(); var sources = EntityQueryEnumerator(); - var destinations = EntityQuery(); + var destinations = EntityQueryEnumerator(); var resistanceQuery = GetEntityQuery(); var transformQuery = GetEntityQuery(); var gridQuery = GetEntityQuery(); @@ -51,8 +51,8 @@ public partial class RadiationSystem // trace all rays from rad source to rad receivers var rays = new List(); - var receiversTotalRads = new ValueList<(RadiationReceiverComponent, float)>(); - foreach (var (dest, destTrs) in destinations) + var receiversTotalRads = new ValueList<(Entity, float)>(); + while (destinations.MoveNext(out var destUid, out var dest, out var destTrs)) { var destWorld = _transform.GetWorldPosition(destTrs, transformQuery); @@ -64,7 +64,7 @@ public partial class RadiationSystem // send ray towards destination entity var ray = Irradiate(uid, sourceTrs, sourceWorld, - destTrs.Owner, destTrs, destWorld, + destUid, destTrs, destWorld, intensity, source.Slope, saveVisitedTiles, resistanceQuery, transformQuery, gridQuery); if (ray == null) continue; @@ -78,9 +78,9 @@ public partial class RadiationSystem } // Apply modifier if the destination entity is hidden within a radiation blocking container - rads = GetAdjustedRadiationIntensity(dest.Owner, rads); + rads = GetAdjustedRadiationIntensity(destUid, rads); - receiversTotalRads.Add((dest, rads)); + receiversTotalRads.Add(((destUid, dest), rads)); } // update information for debug overlay @@ -94,11 +94,11 @@ public partial class RadiationSystem { // update radiation value of receiver // if no radiation rays reached target, that will set it to 0 - receiver.CurrentRadiation = rads; + receiver.Comp.CurrentRadiation = rads; // also send an event with combination of total rad if (rads > 0) - IrradiateEntity(receiver.Owner, rads, GridcastUpdateRate); + IrradiateEntity(receiver, rads, GridcastUpdateRate); } // raise broadcast event that radiation system has updated @@ -145,20 +145,21 @@ public partial class RadiationSystem { if (!gridQuery.TryGetComponent(sourceTrs.GridUid.Value, out var gridComponent)) return ray; - return Gridcast(gridComponent, ray, saveVisitedTiles, resistanceQuery, sourceTrs, destTrs, transformQuery.GetComponent(sourceTrs.GridUid.Value)); + return Gridcast((sourceTrs.GridUid.Value, gridComponent), ray, saveVisitedTiles, resistanceQuery, sourceTrs, destTrs, transformQuery.GetComponent(sourceTrs.GridUid.Value)); } // lets check how many grids are between source and destination // do a box intersection test between target and destination // it's not very precise, but really cheap var box = Box2.FromTwoPoints(sourceWorld, destWorld); - var grids = _mapManager.FindGridsIntersecting(mapId, box, true); + var grids = new List>(); + _mapManager.FindGridsIntersecting(mapId, box, ref grids, true); // gridcast through each grid and try to hit some radiation blockers // the ray will be updated with each grid that has some blockers foreach (var grid in grids) { - ray = Gridcast(grid, ray, saveVisitedTiles, resistanceQuery, sourceTrs, destTrs, transformQuery.GetComponent(grid.Owner)); + ray = Gridcast(grid, ray, saveVisitedTiles, resistanceQuery, sourceTrs, destTrs, transformQuery.GetComponent(grid)); // looks like last grid blocked all radiation // we can return right now @@ -169,7 +170,7 @@ public partial class RadiationSystem return ray; } - private RadiationRay Gridcast(MapGridComponent grid, RadiationRay ray, bool saveVisitedTiles, + private RadiationRay Gridcast(Entity grid, RadiationRay ray, bool saveVisitedTiles, EntityQuery resistanceQuery, TransformComponent sourceTrs, TransformComponent destTrs, @@ -198,12 +199,12 @@ public partial class RadiationSystem : gridTrs.InvLocalMatrix.Transform(ray.Destination); Vector2i sourceGrid = new( - (int) Math.Floor(srcLocal.X / grid.TileSize), - (int) Math.Floor(srcLocal.Y / grid.TileSize)); + (int) Math.Floor(srcLocal.X / grid.Comp.TileSize), + (int) Math.Floor(srcLocal.Y / grid.Comp.TileSize)); Vector2i destGrid = new( - (int) Math.Floor(dstLocal.X / grid.TileSize), - (int) Math.Floor(dstLocal.Y / grid.TileSize)); + (int) Math.Floor(dstLocal.X / grid.Comp.TileSize), + (int) Math.Floor(dstLocal.Y / grid.Comp.TileSize)); // iterate tiles in grid line from source to destination var line = new GridLineEnumerator(sourceGrid, destGrid); diff --git a/Content.Server/Research/Systems/ResearchSystem.Client.cs b/Content.Server/Research/Systems/ResearchSystem.Client.cs index 1bb1882516..e813f09ff9 100644 --- a/Content.Server/Research/Systems/ResearchSystem.Client.cs +++ b/Content.Server/Research/Systems/ResearchSystem.Client.cs @@ -1,5 +1,4 @@ using System.Diagnostics.CodeAnalysis; -using System.Linq; using Content.Server.Power.EntitySystems; using Content.Shared.Research.Components; using Robust.Server.Player; @@ -58,9 +57,15 @@ public sealed partial class ResearchSystem private void OnClientMapInit(EntityUid uid, ResearchClientComponent component, MapInitEvent args) { - var allServers = EntityQuery(true).ToArray(); - if (allServers.Length > 0) - RegisterClient(uid, allServers[0].Owner, component, allServers[0]); + var allServers = new List>(); + var query = AllEntityQuery(); + while (query.MoveNext(out var serverUid, out var serverComp)) + { + allServers.Add((serverUid, serverComp)); + } + + if (allServers.Count > 0) + RegisterClient(uid, allServers[0], component, allServers[0]); } private void OnClientShutdown(EntityUid uid, ResearchClientComponent component, ComponentShutdown args) diff --git a/Content.Server/Research/Systems/ResearchSystem.PointSource.cs b/Content.Server/Research/Systems/ResearchSystem.PointSource.cs index ed8e2eb0a8..f069b1c80f 100644 --- a/Content.Server/Research/Systems/ResearchSystem.PointSource.cs +++ b/Content.Server/Research/Systems/ResearchSystem.PointSource.cs @@ -11,14 +11,14 @@ public sealed partial class ResearchSystem SubscribeLocalEvent(OnGetPointsPerSecond); } - private void OnGetPointsPerSecond(EntityUid uid, ResearchPointSourceComponent component, ref ResearchServerGetPointsPerSecondEvent args) + private void OnGetPointsPerSecond(Entity source, ref ResearchServerGetPointsPerSecondEvent args) { - if (CanProduce(component)) - args.Points += component.PointsPerSecond; + if (CanProduce(source)) + args.Points += source.Comp.PointsPerSecond; } - public bool CanProduce(ResearchPointSourceComponent component) + public bool CanProduce(Entity source) { - return component.Active && this.IsPowered(component.Owner, EntityManager); + return source.Comp.Active && this.IsPowered(source, EntityManager); } } diff --git a/Content.Server/Research/Systems/ResearchSystem.cs b/Content.Server/Research/Systems/ResearchSystem.cs index 7adc30ea29..e89b435800 100644 --- a/Content.Server/Research/Systems/ResearchSystem.cs +++ b/Content.Server/Research/Systems/ResearchSystem.cs @@ -42,11 +42,13 @@ namespace Content.Server.Research.Systems { serverUid = null; serverComponent = null; - foreach (var server in EntityQuery()) + + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var server)) { if (server.Id != id) continue; - serverUid = server.Owner; + serverUid = uid; serverComponent = server; return true; } @@ -89,13 +91,14 @@ namespace Content.Server.Research.Systems public override void Update(float frameTime) { - foreach (var server in EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var server)) { if (server.NextUpdateTime > _timing.CurTime) continue; server.NextUpdateTime = _timing.CurTime + server.ResearchConsoleUpdateTime; - UpdateServer(server.Owner, (int) server.ResearchConsoleUpdateTime.TotalSeconds, server); + UpdateServer(uid, (int) server.ResearchConsoleUpdateTime.TotalSeconds, server); } } } diff --git a/Content.Server/Resist/EscapeInventorySystem.cs b/Content.Server/Resist/EscapeInventorySystem.cs index ea603084b5..1249269de5 100644 --- a/Content.Server/Resist/EscapeInventorySystem.cs +++ b/Content.Server/Resist/EscapeInventorySystem.cs @@ -1,15 +1,15 @@ using Content.Server.Contests; -using Robust.Shared.Containers; using Content.Server.Popups; -using Content.Shared.Storage; -using Content.Shared.Inventory; -using Content.Shared.Hands.EntitySystems; +using Content.Server.Storage.Components; using Content.Shared.ActionBlocker; using Content.Shared.DoAfter; -using Content.Shared.Movement.Events; +using Content.Shared.Hands.EntitySystems; using Content.Shared.Interaction.Events; +using Content.Shared.Inventory; +using Content.Shared.Movement.Events; using Content.Shared.Resist; -using Content.Server.Storage.Components; +using Content.Shared.Storage; +using Robust.Shared.Containers; namespace Content.Server.Resist; @@ -93,7 +93,7 @@ public sealed class EscapeInventorySystem : EntitySystem if (args.Handled || args.Cancelled) return; - _containerSystem.AttachParentToContainerOrGrid(Transform(uid)); + _containerSystem.AttachParentToContainerOrGrid((uid, Transform(uid))); args.Handled = true; } diff --git a/Content.Server/Revenant/EntitySystems/CorporealSystem.cs b/Content.Server/Revenant/EntitySystems/CorporealSystem.cs index 350d082756..1d43cb3ac8 100644 --- a/Content.Server/Revenant/EntitySystems/CorporealSystem.cs +++ b/Content.Server/Revenant/EntitySystems/CorporealSystem.cs @@ -17,9 +17,9 @@ public sealed class CorporealSystem : SharedCorporealSystem if (TryComp(uid, out var visibility)) { - _visibilitySystem.RemoveLayer(visibility, (int) VisibilityFlags.Ghost, false); - _visibilitySystem.AddLayer(visibility, (int) VisibilityFlags.Normal, false); - _visibilitySystem.RefreshVisibility(visibility); + _visibilitySystem.RemoveLayer(uid, visibility, (int) VisibilityFlags.Ghost, false); + _visibilitySystem.AddLayer(uid, visibility, (int) VisibilityFlags.Normal, false); + _visibilitySystem.RefreshVisibility(uid, visibility); } } @@ -29,9 +29,9 @@ public sealed class CorporealSystem : SharedCorporealSystem if (TryComp(uid, out var visibility) && _ticker.RunLevel != GameRunLevel.PostRound) { - _visibilitySystem.AddLayer(visibility, (int) VisibilityFlags.Ghost, false); - _visibilitySystem.RemoveLayer(visibility, (int) VisibilityFlags.Normal, false); - _visibilitySystem.RefreshVisibility(visibility); + _visibilitySystem.AddLayer(uid, visibility, (int) VisibilityFlags.Ghost, false); + _visibilitySystem.RemoveLayer(uid, visibility, (int) VisibilityFlags.Normal, false); + _visibilitySystem.RefreshVisibility(uid, visibility); } } } diff --git a/Content.Server/Revenant/EntitySystems/RevenantOverloadedLightsSystem.cs b/Content.Server/Revenant/EntitySystems/RevenantOverloadedLightsSystem.cs index dadf1cfa6b..2a45b31234 100644 --- a/Content.Server/Revenant/EntitySystems/RevenantOverloadedLightsSystem.cs +++ b/Content.Server/Revenant/EntitySystems/RevenantOverloadedLightsSystem.cs @@ -11,12 +11,13 @@ public sealed class RevenantOverloadedLightsSystem : SharedRevenantOverloadedLig { [Dependency] private readonly BeamSystem _beam = default!; - protected override void OnZap(RevenantOverloadedLightsComponent component) + protected override void OnZap(Entity lights) { + var component = lights.Comp; if (component.Target == null) return; - var lxform = Transform(component.Owner); + var lxform = Transform(lights); var txform = Transform(component.Target.Value); if (!lxform.Coordinates.TryDistance(EntityManager, txform.Coordinates, out var distance)) @@ -24,6 +25,6 @@ public sealed class RevenantOverloadedLightsSystem : SharedRevenantOverloadedLig if (distance > component.ZapRange) return; - _beam.TryCreateBeam(component.Owner, component.Target.Value, component.ZapBeamEntityId); + _beam.TryCreateBeam(lights, component.Target.Value, component.ZapBeamEntityId); } } diff --git a/Content.Server/Revenant/EntitySystems/RevenantSystem.cs b/Content.Server/Revenant/EntitySystems/RevenantSystem.cs index 0026533c4a..d5e1ae1af8 100644 --- a/Content.Server/Revenant/EntitySystems/RevenantSystem.cs +++ b/Content.Server/Revenant/EntitySystems/RevenantSystem.cs @@ -77,9 +77,9 @@ public sealed partial class RevenantSystem : EntitySystem if (_ticker.RunLevel == GameRunLevel.PostRound && TryComp(uid, out var visibility)) { - _visibility.AddLayer(visibility, (int) VisibilityFlags.Ghost, false); - _visibility.RemoveLayer(visibility, (int) VisibilityFlags.Normal, false); - _visibility.RefreshVisibility(visibility); + _visibility.AddLayer(uid, visibility, (int) VisibilityFlags.Ghost, false); + _visibility.RemoveLayer(uid, visibility, (int) VisibilityFlags.Normal, false); + _visibility.RefreshVisibility(uid, visibility); } //ghost vision @@ -185,19 +185,20 @@ public sealed partial class RevenantSystem : EntitySystem public void MakeVisible(bool visible) { - foreach (var (_, vis) in EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out _, out var vis)) { if (visible) { - _visibility.AddLayer(vis, (int) VisibilityFlags.Normal, false); - _visibility.RemoveLayer(vis, (int) VisibilityFlags.Ghost, false); + _visibility.AddLayer(uid, vis, (int) VisibilityFlags.Normal, false); + _visibility.RemoveLayer(uid, vis, (int) VisibilityFlags.Ghost, false); } else { - _visibility.AddLayer(vis, (int) VisibilityFlags.Ghost, false); - _visibility.RemoveLayer(vis, (int) VisibilityFlags.Normal, false); + _visibility.AddLayer(uid, vis, (int) VisibilityFlags.Ghost, false); + _visibility.RemoveLayer(uid, vis, (int) VisibilityFlags.Normal, false); } - _visibility.RefreshVisibility(vis); + _visibility.RefreshVisibility(uid, vis); } } @@ -205,7 +206,8 @@ public sealed partial class RevenantSystem : EntitySystem { base.Update(frameTime); - foreach (var rev in EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var rev)) { rev.Accumulator += frameTime; @@ -215,7 +217,7 @@ public sealed partial class RevenantSystem : EntitySystem if (rev.Essence < rev.EssenceRegenCap) { - ChangeEssenceAmount(rev.Owner, rev.EssencePerSecond, rev, regenCap: true); + ChangeEssenceAmount(uid, rev.EssencePerSecond, rev, regenCap: true); } } } diff --git a/Content.Server/Salvage/SalvageRulerCommand.cs b/Content.Server/Salvage/SalvageRulerCommand.cs index 9dcf7fc36e..b0a64508c5 100644 --- a/Content.Server/Salvage/SalvageRulerCommand.cs +++ b/Content.Server/Salvage/SalvageRulerCommand.cs @@ -1,13 +1,8 @@ -using Content.Server.Preferences.Managers; using Content.Server.Administration; using Content.Shared.Administration; -using Content.Shared.Preferences; -using Content.Shared.Roles; -using Robust.Server.GameObjects; using Robust.Server.Player; using Robust.Shared.Console; using Robust.Shared.Map; -using Robust.Shared.IoC; namespace Content.Server.Salvage; @@ -48,9 +43,9 @@ sealed class SalvageRulerCommand : IConsoleCommand var entityTransform = _entities.GetComponent(entity.Value); var total = Box2.UnitCentered; var first = true; - foreach (var mapGrid in _maps.GetAllMapGrids(entityTransform.MapID)) + foreach (var mapGrid in _maps.GetAllGrids(entityTransform.MapID)) { - var aabb = _entities.GetComponent(mapGrid.Owner).WorldMatrix.TransformBox(mapGrid.LocalAABB); + var aabb = _entities.GetComponent(mapGrid).WorldMatrix.TransformBox(mapGrid.Comp.LocalAABB); if (first) { total = aabb; diff --git a/Content.Server/Salvage/SalvageSystem.ExpeditionConsole.cs b/Content.Server/Salvage/SalvageSystem.ExpeditionConsole.cs index d4241b2baf..237645dadf 100644 --- a/Content.Server/Salvage/SalvageSystem.ExpeditionConsole.cs +++ b/Content.Server/Salvage/SalvageSystem.ExpeditionConsole.cs @@ -1,5 +1,4 @@ using Content.Shared.Procedural; -using Content.Shared.Salvage; using Content.Shared.Salvage.Expeditions; namespace Content.Server.Salvage; @@ -24,34 +23,35 @@ public sealed partial class SalvageSystem UpdateConsoles(data); } - private void OnSalvageConsoleInit(EntityUid uid, SalvageExpeditionConsoleComponent component, ComponentInit args) + private void OnSalvageConsoleInit(Entity console, ref ComponentInit args) { - UpdateConsole(component); + UpdateConsole(console); } - private void OnSalvageConsoleParent(EntityUid uid, SalvageExpeditionConsoleComponent component, ref EntParentChangedMessage args) + private void OnSalvageConsoleParent(Entity console, ref EntParentChangedMessage args) { - UpdateConsole(component); + UpdateConsole(console); } private void UpdateConsoles(SalvageExpeditionDataComponent component) { var state = GetState(component); - foreach (var (console, xform, uiComp) in EntityQuery(true)) + var query = AllEntityQuery(); + while (query.MoveNext(out var uid, out _, out var uiComp, out var xform)) { - var station = _station.GetOwningStation(console.Owner, xform); + var station = _station.GetOwningStation(uid, xform); - if (station != component.Owner) + if (station != uid) continue; - _ui.TrySetUiState(console.Owner, SalvageConsoleUiKey.Expedition, state, ui: uiComp); + _ui.TrySetUiState(uid, SalvageConsoleUiKey.Expedition, state, ui: uiComp); } } - private void UpdateConsole(SalvageExpeditionConsoleComponent component) + private void UpdateConsole(Entity component) { - var station = _station.GetOwningStation(component.Owner); + var station = _station.GetOwningStation(component); SalvageExpeditionConsoleState state; if (TryComp(station, out var dataComponent)) @@ -63,6 +63,6 @@ public sealed partial class SalvageSystem state = new SalvageExpeditionConsoleState(TimeSpan.Zero, false, true, 0, new List()); } - _ui.TrySetUiState(component.Owner, SalvageConsoleUiKey.Expedition, state); + _ui.TrySetUiState(component, SalvageConsoleUiKey.Expedition, state); } } diff --git a/Content.Server/Shuttles/Components/ThrusterComponent.cs b/Content.Server/Shuttles/Components/ThrusterComponent.cs index c50feb959a..e7cfbf8f8e 100644 --- a/Content.Server/Shuttles/Components/ThrusterComponent.cs +++ b/Content.Server/Shuttles/Components/ThrusterComponent.cs @@ -15,31 +15,8 @@ namespace Content.Server.Shuttles.Components /// /// Whether the thruster has been force to be enabled / disabled (e.g. VV, interaction, etc.) /// - [ViewVariables(VVAccess.ReadWrite)] - public bool Enabled - { - get => _enabled; - [Obsolete("Use the system method")] - set - { - if (_enabled == value) return; - _enabled = value; - - var system = EntitySystem.Get(); - - if (!_enabled) - { - system.DisableThruster(Owner, this); - } - else if (system.CanEnable(Owner, this)) - { - system.EnableThruster(Owner, this); - } - } - } - - [DataField("enabled")] - private bool _enabled = true; + [DataField, ViewVariables(VVAccess.ReadWrite)] + public bool Enabled { get; set; } /// /// This determines whether the thruster is actually enabled for the purposes of thrust diff --git a/Content.Server/Shuttles/Systems/DockingSystem.AutoDock.cs b/Content.Server/Shuttles/Systems/DockingSystem.AutoDock.cs index 439367a080..a09fff5189 100644 --- a/Content.Server/Shuttles/Systems/DockingSystem.AutoDock.cs +++ b/Content.Server/Shuttles/Systems/DockingSystem.AutoDock.cs @@ -1,9 +1,6 @@ using Content.Server.Shuttles.Components; using Content.Shared.Shuttles.Components; using Content.Shared.Shuttles.Events; -using Robust.Shared.Physics.Components; -using Robust.Shared.Players; -using Robust.Shared.Utility; namespace Content.Server.Shuttles.Systems; @@ -35,7 +32,7 @@ public sealed partial class DockingSystem if (dockable == null) continue; - TryDock(dockUid, dock, dockable.Owner, dockable); + TryDock(dockUid, dock, dockable.Value); } // Work out recent docks that have gone past their designated threshold. @@ -114,7 +111,8 @@ public sealed partial class DockingSystem var player = args.Session.AttachedEntity; // TODO: Validation - if (player == null || !TryComp(dork, out var comp)) return; + if (player == null || !TryComp(dork, out var comp)) + return; comp.Requesters.Remove(player.Value); diff --git a/Content.Server/Shuttles/Systems/DockingSystem.Shuttle.cs b/Content.Server/Shuttles/Systems/DockingSystem.Shuttle.cs index 6ad113f3da..fd9cf67c5a 100644 --- a/Content.Server/Shuttles/Systems/DockingSystem.Shuttle.cs +++ b/Content.Server/Shuttles/Systems/DockingSystem.Shuttle.cs @@ -1,4 +1,3 @@ -using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Numerics; using Content.Server.Shuttles.Components; @@ -140,6 +139,7 @@ public sealed partial class DockingSystem var isMap = HasComp(targetGrid); var validDockConfigs = new List(); + var grids = new List>(); if (shuttleDocks.Count > 0) { // We'll try all combinations of shuttle docks and see which one is most suitable @@ -174,8 +174,9 @@ public sealed partial class DockingSystem var dockedBounds = new Box2Rotated(shuttleAABB.Translated(spawnPosition.Position), targetAngle, spawnPosition.Position); // Check if there's no intersecting grids (AKA oh god it's docking at cargo). - if (_mapManager.FindGridsIntersecting(targetGridXform.MapID, - dockedBounds).Any(o => o.Owner != targetGrid)) + grids.Clear(); + _mapManager.FindGridsIntersecting(targetGridXform.MapID, dockedBounds, ref grids); + if (grids.Any(o => o.Owner != targetGrid)) { continue; } diff --git a/Content.Server/Shuttles/Systems/DockingSystem.cs b/Content.Server/Shuttles/Systems/DockingSystem.cs index ba75ef3284..f765ed6976 100644 --- a/Content.Server/Shuttles/Systems/DockingSystem.cs +++ b/Content.Server/Shuttles/Systems/DockingSystem.cs @@ -7,6 +7,7 @@ using Content.Shared.Doors; using Content.Shared.Doors.Components; using Content.Shared.Shuttles.Events; using Robust.Shared.Map; +using Robust.Shared.Map.Components; using Robust.Shared.Physics; using Robust.Shared.Physics.Collision.Shapes; using Robust.Shared.Physics.Components; @@ -66,7 +67,7 @@ namespace Content.Server.Shuttles.Systems args.Cancel(); } - private DockingComponent? GetDockable(EntityUid uid, TransformComponent dockingXform) + private Entity? GetDockable(EntityUid uid, TransformComponent dockingXform) { // Did you know Saltern is the most dockable station? @@ -96,12 +97,14 @@ namespace Content.Server.Shuttles.Systems var enlargedAABB = aabb.Value.Enlarged(DockingRadius * 1.5f); // Get any docking ports in range on other grids. - foreach (var otherGrid in _mapManager.FindGridsIntersecting(dockingXform.MapID, enlargedAABB)) + var grids = new List>(); + _mapManager.FindGridsIntersecting(dockingXform.MapID, enlargedAABB, ref grids); + foreach (var otherGrid in grids) { if (otherGrid.Owner == dockingXform.GridUid) continue; - foreach (var ent in otherGrid.GetAnchoredEntities(enlargedAABB)) + foreach (var ent in otherGrid.Comp.GetAnchoredEntities(enlargedAABB)) { if (!TryComp(ent, out DockingComponent? otherDocking) || !otherDocking.Enabled || @@ -129,7 +132,7 @@ namespace Content.Server.Shuttles.Systems // TODO: Need CollisionManager's GJK for accurate bounds // Realistically I want 2 fixtures anyway but I'll deal with that later. - return otherDocking; + return (ent, otherDocking); } } } @@ -443,12 +446,12 @@ namespace Content.Server.Shuttles.Systems /// /// Attempts to dock 2 ports together and will return early if it's not possible. /// - private void TryDock(EntityUid dockAUid, DockingComponent dockA, EntityUid dockBUid, DockingComponent dockB) + private void TryDock(EntityUid dockAUid, DockingComponent dockA, Entity dockB) { - if (!CanDock(dockAUid, dockBUid, dockA, dockB)) + if (!CanDock(dockAUid, dockB, dockA, dockB)) return; - Dock(dockAUid, dockA, dockBUid, dockB); + Dock(dockAUid, dockA, dockB, dockB); } public void Undock(EntityUid dockUid, DockingComponent dock) diff --git a/Content.Server/Shuttles/Systems/EmergencyShuttleSystem.Console.cs b/Content.Server/Shuttles/Systems/EmergencyShuttleSystem.Console.cs index 0603ff7502..62478082d8 100644 --- a/Content.Server/Shuttles/Systems/EmergencyShuttleSystem.Console.cs +++ b/Content.Server/Shuttles/Systems/EmergencyShuttleSystem.Console.cs @@ -9,7 +9,6 @@ using Content.Shared.Popups; using Content.Shared.Shuttles.BUIStates; using Content.Shared.Shuttles.Events; using Content.Shared.Shuttles.Systems; -using Robust.Server.GameObjects; using Robust.Shared.Map; using Robust.Shared.Player; using Timer = Robust.Shared.Timing.Timer; @@ -258,16 +257,17 @@ public sealed partial class EmergencyShuttleSystem private void OnEmergencyRepeal(EntityUid uid, EmergencyShuttleConsoleComponent component, EmergencyShuttleRepealMessage args) { var player = args.Session.AttachedEntity; - if (player == null) return; + if (player == null) + return; - if (!_idSystem.TryFindIdCard(player.Value, out var idCard) || !_reader.IsAllowed(idCard.Owner, uid)) + if (!_idSystem.TryFindIdCard(player.Value, out var idCard) || !_reader.IsAllowed(idCard, uid)) { _popup.PopupCursor(Loc.GetString("emergency-shuttle-console-denied"), player.Value, PopupType.Medium); return; } // TODO: This is fucking bad - if (!component.AuthorizedEntities.Remove(MetaData(idCard.Owner).EntityName)) + if (!component.AuthorizedEntities.Remove(MetaData(idCard).EntityName)) return; _logger.Add(LogType.EmergencyShuttle, LogImpact.High, $"Emergency shuttle early launch REPEAL by {args.Session:user}"); @@ -283,14 +283,14 @@ public sealed partial class EmergencyShuttleSystem if (player == null) return; - if (!_idSystem.TryFindIdCard(player.Value, out var idCard) || !_reader.IsAllowed(idCard.Owner, uid)) + if (!_idSystem.TryFindIdCard(player.Value, out var idCard) || !_reader.IsAllowed(idCard, uid)) { _popup.PopupCursor(Loc.GetString("emergency-shuttle-console-denied"), args.Session, PopupType.Medium); return; } // TODO: This is fucking bad - if (!component.AuthorizedEntities.Add(MetaData(idCard.Owner).EntityName)) + if (!component.AuthorizedEntities.Add(MetaData(idCard).EntityName)) return; _logger.Add(LogType.EmergencyShuttle, LogImpact.High, $"Emergency shuttle early launch AUTH by {args.Session:user}"); diff --git a/Content.Server/Shuttles/Systems/ShuttleSystem.FasterThanLight.cs b/Content.Server/Shuttles/Systems/ShuttleSystem.FasterThanLight.cs index 49e1b1cb84..e19d88b1c2 100644 --- a/Content.Server/Shuttles/Systems/ShuttleSystem.FasterThanLight.cs +++ b/Content.Server/Shuttles/Systems/ShuttleSystem.FasterThanLight.cs @@ -1,29 +1,26 @@ +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Numerics; using Content.Server.Shuttles.Components; +using Content.Server.Shuttles.Events; using Content.Server.Station.Systems; using Content.Shared.Body.Components; +using Content.Shared.Buckle.Components; +using Content.Shared.Doors.Components; using Content.Shared.Maps; using Content.Shared.Parallax; +using Content.Shared.Shuttles.Components; using Content.Shared.Shuttles.Systems; using Content.Shared.StatusEffect; +using JetBrains.Annotations; using Robust.Shared.Audio; using Robust.Shared.Collections; using Robust.Shared.Map; -using Robust.Shared.Player; -using Robust.Shared.Utility; -using System.Diagnostics.CodeAnalysis; -using System.Numerics; -using System.Linq; -using Content.Server.Shuttles.Events; -using Content.Shared.Body.Components; -using Content.Shared.Buckle.Components; -using Content.Shared.Doors.Components; -using Content.Shared.Mobs.Components; -using Content.Shared.Shuttles.Components; -using Content.Shared.Throwing; -using JetBrains.Annotations; using Robust.Shared.Map.Components; using Robust.Shared.Physics; using Robust.Shared.Physics.Components; +using Robust.Shared.Player; +using Robust.Shared.Utility; namespace Content.Server.Shuttles.Systems; @@ -231,7 +228,7 @@ public sealed partial class ShuttleSystem component = AddComp(uid); component.State = FTLState.Starting; // TODO: Need BroadcastGrid to not be bad. - SoundSystem.Play(_startupSound.GetSound(), Filter.Empty().AddInRange(Transform(uid).MapPosition, GetSoundRange(component.Owner)), _startupSound.Params); + SoundSystem.Play(_startupSound.GetSound(), Filter.Empty().AddInRange(Transform(uid).MapPosition, GetSoundRange(uid)), _startupSound.Params); // Make sure the map is setup before we leave to avoid pop-in (e.g. parallax). SetupHyperspace(); return true; @@ -608,16 +605,20 @@ public sealed partial class ShuttleSystem var iteration = 0; var lastCount = nearbyGrids.Count; var mapId = targetXform.MapID; + var grids = new List>(); while (iteration < FTLProximityIterations) { - foreach (var grid in _mapManager.FindGridsIntersecting(mapId, targetAABB)) + grids.Clear(); + _mapManager.FindGridsIntersecting(mapId, targetAABB, ref grids); + + foreach (var grid in grids) { - if (!nearbyGrids.Add(grid.Owner)) + if (!nearbyGrids.Add(grid)) continue; - targetAABB = targetAABB.Union(_transform.GetWorldMatrix(grid.Owner, xformQuery) - .TransformBox(Comp(grid.Owner).LocalAABB)); + targetAABB = targetAABB.Union(_transform.GetWorldMatrix(grid, xformQuery) + .TransformBox(Comp(grid).LocalAABB)); } // Can do proximity @@ -634,14 +635,15 @@ public sealed partial class ShuttleSystem if (iteration != FTLProximityIterations) continue; - foreach (var grid in _mapManager.GetAllGrids()) + var query = AllEntityQuery(); + while (query.MoveNext(out var uid, out var grid)) { // Don't add anymore as it is irrelevant, but that doesn't mean we need to re-do existing work. - if (nearbyGrids.Contains(grid.Owner)) + if (nearbyGrids.Contains(uid)) continue; - targetAABB = targetAABB.Union(_transform.GetWorldMatrix(grid.Owner, xformQuery) - .TransformBox(Comp(grid.Owner).LocalAABB)); + targetAABB = targetAABB.Union(_transform.GetWorldMatrix(uid, xformQuery) + .TransformBox(Comp(uid).LocalAABB)); } break; diff --git a/Content.Server/Shuttles/Systems/ShuttleSystem.IFF.cs b/Content.Server/Shuttles/Systems/ShuttleSystem.IFF.cs index 15c89b2134..bf265da2e6 100644 --- a/Content.Server/Shuttles/Systems/ShuttleSystem.IFF.cs +++ b/Content.Server/Shuttles/Systems/ShuttleSystem.IFF.cs @@ -76,12 +76,14 @@ public sealed partial class ShuttleSystem protected override void UpdateIFFInterfaces(EntityUid gridUid, IFFComponent component) { base.UpdateIFFInterfaces(gridUid, component); - foreach (var (comp, xform) in EntityQuery(true)) + + var query = AllEntityQuery(); + while (query.MoveNext(out var uid, out var comp, out var xform)) { if (xform.GridUid != gridUid) continue; - _uiSystem.TrySetUiState(comp.Owner, IFFConsoleUiKey.Key, new IFFConsoleBoundUserInterfaceState() + _uiSystem.TrySetUiState(uid, IFFConsoleUiKey.Key, new IFFConsoleBoundUserInterfaceState() { AllowedFlags = comp.AllowedFlags, Flags = component.Flags, diff --git a/Content.Server/Shuttles/Systems/ThrusterSystem.cs b/Content.Server/Shuttles/Systems/ThrusterSystem.cs index 1fd9fabb80..ed7208ab47 100644 --- a/Content.Server/Shuttles/Systems/ThrusterSystem.cs +++ b/Content.Server/Shuttles/Systems/ThrusterSystem.cs @@ -130,6 +130,15 @@ public sealed class ThrusterSystem : EntitySystem private void OnActivateThruster(EntityUid uid, ThrusterComponent component, ActivateInWorldEvent args) { component.Enabled ^= true; + + if (!component.Enabled) + { + DisableThruster(uid, component); + } + else if (CanEnable(uid, component)) + { + EnableThruster(uid, component); + } } /// diff --git a/Content.Server/Singularity/EntitySystems/ContainmentFieldGeneratorSystem.cs b/Content.Server/Singularity/EntitySystems/ContainmentFieldGeneratorSystem.cs index 171f27752f..d58458527f 100644 --- a/Content.Server/Singularity/EntitySystems/ContainmentFieldGeneratorSystem.cs +++ b/Content.Server/Singularity/EntitySystems/ContainmentFieldGeneratorSystem.cs @@ -1,15 +1,15 @@ using Content.Server.Administration.Logs; -using Content.Server.Singularity.Events; -using Content.Shared.Singularity.Components; -using Content.Shared.Tag; -using Robust.Server.GameObjects; -using Robust.Shared.Physics; using Content.Server.Popups; +using Content.Server.Singularity.Events; using Content.Shared.Construction.Components; using Content.Shared.Database; using Content.Shared.Examine; using Content.Shared.Interaction; using Content.Shared.Popups; +using Content.Shared.Singularity.Components; +using Content.Shared.Tag; +using Robust.Server.GameObjects; +using Robust.Shared.Physics; using Robust.Shared.Physics.Components; using Robust.Shared.Physics.Events; @@ -52,7 +52,7 @@ public sealed class ContainmentFieldGeneratorSystem : EntitySystem if (generator.Accumulator >= generator.Threshold) { - LosePower(uid, generator.PowerLoss, generator); + LosePower((uid, generator), generator.PowerLoss); generator.Accumulator -= generator.Threshold; } } @@ -63,12 +63,12 @@ public sealed class ContainmentFieldGeneratorSystem : EntitySystem /// /// A generator receives power from a source colliding with it. /// - private void HandleGeneratorCollide(EntityUid uid, ContainmentFieldGeneratorComponent component, ref StartCollideEvent args) + private void HandleGeneratorCollide(Entity generator, ref StartCollideEvent args) { - if (_tags.HasTag(args.OtherEntity, component.IDTag)) + if (_tags.HasTag(args.OtherEntity, generator.Comp.IDTag)) { - ReceivePower(component.PowerReceived, component); - component.Accumulator = 0f; + ReceivePower(generator.Comp.PowerReceived, generator); + generator.Comp.Accumulator = 0f; } } @@ -81,35 +81,35 @@ public sealed class ContainmentFieldGeneratorSystem : EntitySystem args.PushMarkup(Loc.GetString("comp-containment-off")); } - private void OnInteract(EntityUid uid, ContainmentFieldGeneratorComponent component, InteractHandEvent args) + private void OnInteract(Entity generator, ref InteractHandEvent args) { if (args.Handled) return; - if (TryComp(component.Owner, out TransformComponent? transformComp) && transformComp.Anchored) + if (TryComp(generator, out TransformComponent? transformComp) && transformComp.Anchored) { - if (!component.Enabled) - TurnOn(component); - else if (component.Enabled && component.IsConnected) + if (!generator.Comp.Enabled) + TurnOn(generator); + else if (generator.Comp.Enabled && generator.Comp.IsConnected) { _popupSystem.PopupEntity(Loc.GetString("comp-containment-toggle-warning"), args.User, args.User, PopupType.LargeCaution); return; } else - TurnOff(component); + TurnOff(generator); } args.Handled = true; } - private void OnAnchorChanged(EntityUid uid, ContainmentFieldGeneratorComponent component, ref AnchorStateChangedEvent args) + private void OnAnchorChanged(Entity generator, ref AnchorStateChangedEvent args) { if (!args.Anchored) - RemoveConnections(uid, component); + RemoveConnections(generator); } - private void OnReanchorEvent(EntityUid uid, ContainmentFieldGeneratorComponent component, ref ReAnchorEvent args) + private void OnReanchorEvent(Entity generator, ref ReAnchorEvent args) { - GridCheck(uid, component); + GridCheck(generator); } private void OnUnanchorAttempt(EntityUid uid, ContainmentFieldGeneratorComponent component, @@ -122,41 +122,42 @@ public sealed class ContainmentFieldGeneratorSystem : EntitySystem } } - private void TurnOn(ContainmentFieldGeneratorComponent component) + private void TurnOn(Entity generator) { - component.Enabled = true; - ChangeFieldVisualizer(component); - _popupSystem.PopupEntity(Loc.GetString("comp-containment-turned-on"), component.Owner); + generator.Comp.Enabled = true; + ChangeFieldVisualizer(generator); + _popupSystem.PopupEntity(Loc.GetString("comp-containment-turned-on"), generator); } - private void TurnOff(ContainmentFieldGeneratorComponent component) + private void TurnOff(Entity generator) { - component.Enabled = false; - ChangeFieldVisualizer(component); - _popupSystem.PopupEntity(Loc.GetString("comp-containment-turned-off"), component.Owner); + generator.Comp.Enabled = false; + ChangeFieldVisualizer(generator); + _popupSystem.PopupEntity(Loc.GetString("comp-containment-turned-off"), generator); } - private void OnComponentRemoved(EntityUid uid, ContainmentFieldGeneratorComponent component, ComponentRemove args) + private void OnComponentRemoved(Entity generator, ref ComponentRemove args) { - RemoveConnections(uid, component); + RemoveConnections(generator); } /// /// Deletes the fields and removes the respective connections for the generators. /// - private void RemoveConnections(EntityUid uid, ContainmentFieldGeneratorComponent component) + private void RemoveConnections(Entity generator) { + var (uid, component) = generator; foreach (var (direction, value) in component.Connections) { foreach (var field in value.Item2) { QueueDel(field); } - value.Item1.Connections.Remove(direction.GetOpposite()); + value.Item1.Comp.Connections.Remove(direction.GetOpposite()); - if (value.Item1.Connections.Count == 0) //Change isconnected only if there's no more connections + if (value.Item1.Comp.Connections.Count == 0) //Change isconnected only if there's no more connections { - value.Item1.IsConnected = false; + value.Item1.Comp.IsConnected = false; ChangeOnLightVisualizer(value.Item1); } @@ -164,10 +165,10 @@ public sealed class ContainmentFieldGeneratorSystem : EntitySystem } component.Connections.Clear(); component.IsConnected = false; - ChangeOnLightVisualizer(component); - ChangeFieldVisualizer(component); + ChangeOnLightVisualizer(generator); + ChangeFieldVisualizer(generator); _adminLogger.Add(LogType.FieldGeneration, LogImpact.Medium, $"{ToPrettyString(uid)} lost field connections"); // Ideally LogImpact would depend on if there is a singulo nearby - _popupSystem.PopupEntity(Loc.GetString("comp-containment-disconnected"), component.Owner, PopupType.LargeCaution); + _popupSystem.PopupEntity(Loc.GetString("comp-containment-disconnected"), uid, PopupType.LargeCaution); } #endregion @@ -178,11 +179,12 @@ public sealed class ContainmentFieldGeneratorSystem : EntitySystem /// Stores power in the generator. If it hits the threshold, it tries to establish a connection. /// /// The power that this generator received from the collision in - public void ReceivePower(int power, ContainmentFieldGeneratorComponent component) + public void ReceivePower(int power, Entity generator) { + var component = generator.Comp; component.PowerBuffer += power; - var genXForm = Transform(component.Owner); + var genXForm = Transform(generator); if (component.PowerBuffer >= component.PowerMinimum) { @@ -194,23 +196,24 @@ public sealed class ContainmentFieldGeneratorSystem : EntitySystem if (component.Connections.ContainsKey(dir)) continue; // This direction already has an active connection - TryGenerateFieldConnection(dir, component, genXForm); + TryGenerateFieldConnection(dir, generator, genXForm); } } - ChangePowerVisualizer(power, component); + ChangePowerVisualizer(power, generator); } - public void LosePower(EntityUid uid, int power, ContainmentFieldGeneratorComponent component) + public void LosePower(Entity generator, int power) { + var component = generator.Comp; component.PowerBuffer -= power; if (component.PowerBuffer < component.PowerMinimum && component.Connections.Count != 0) { - RemoveConnections(uid, component); + RemoveConnections(generator); } - ChangePowerVisualizer(power, component); + ChangePowerVisualizer(power, generator); } /// @@ -218,11 +221,12 @@ public sealed class ContainmentFieldGeneratorSystem : EntitySystem /// If all the checks pass and fields spawn, it will store this connection on each respective generator. /// /// The field generator establishes a connection in this direction. - /// The field generator component + /// The field generator component /// The transform component for the first generator /// - private bool TryGenerateFieldConnection(Direction dir, ContainmentFieldGeneratorComponent component, TransformComponent gen1XForm) + private bool TryGenerateFieldConnection(Direction dir, Entity generator, TransformComponent gen1XForm) { + var component = generator.Comp; if (!component.Enabled) return false; @@ -233,7 +237,7 @@ public sealed class ContainmentFieldGeneratorSystem : EntitySystem var dirRad = dir.ToAngle() + genWorldPosRot.WorldRotation; //needs to be like this for the raycast to work properly var ray = new CollisionRay(genWorldPosRot.WorldPosition, dirRad.ToVec(), component.CollisionMask); - var rayCastResults = _physics.IntersectRay(gen1XForm.MapID, ray, component.MaxLength, component.Owner, false); + var rayCastResults = _physics.IntersectRay(gen1XForm.MapID, ray, component.MaxLength, generator, false); var genQuery = GetEntityQuery(); RayCastResults? closestResult = null; @@ -254,46 +258,47 @@ public sealed class ContainmentFieldGeneratorSystem : EntitySystem otherFieldGeneratorComponent == component || !TryComp(ent, out var collidableComponent) || collidableComponent.BodyType != BodyType.Static || - gen1XForm.ParentUid != Transform(otherFieldGeneratorComponent.Owner).ParentUid) + gen1XForm.ParentUid != Transform(ent).ParentUid) { return false; } - var fields = GenerateFieldConnection(component, otherFieldGeneratorComponent); + var otherFieldGenerator = (ent, otherFieldGeneratorComponent); + var fields = GenerateFieldConnection(generator, otherFieldGenerator); - component.Connections[dir] = (otherFieldGeneratorComponent, fields); - otherFieldGeneratorComponent.Connections[dir.GetOpposite()] = (component, fields); - ChangeFieldVisualizer(otherFieldGeneratorComponent); + component.Connections[dir] = (otherFieldGenerator, fields); + otherFieldGeneratorComponent.Connections[dir.GetOpposite()] = (generator, fields); + ChangeFieldVisualizer(otherFieldGenerator); if (!component.IsConnected) { component.IsConnected = true; - ChangeOnLightVisualizer(component); + ChangeOnLightVisualizer(generator); } if (!otherFieldGeneratorComponent.IsConnected) { otherFieldGeneratorComponent.IsConnected = true; - ChangeOnLightVisualizer(otherFieldGeneratorComponent); + ChangeOnLightVisualizer(otherFieldGenerator); } - ChangeFieldVisualizer(component); - UpdateConnectionLights(component); - _popupSystem.PopupEntity(Loc.GetString("comp-containment-connected"), component.Owner); + ChangeFieldVisualizer(generator); + UpdateConnectionLights(generator); + _popupSystem.PopupEntity(Loc.GetString("comp-containment-connected"), generator); return true; } /// /// Spawns fields between two generators if the finds two generators to connect. /// - /// The source field generator - /// The second generator that the source is connected to + /// The source field generator + /// The second generator that the source is connected to /// - private List GenerateFieldConnection(ContainmentFieldGeneratorComponent firstGenComp, ContainmentFieldGeneratorComponent secondGenComp) + private List GenerateFieldConnection(Entity firstGen, Entity secondGen) { var fieldList = new List(); - var gen1Coords = Transform(firstGenComp.Owner).Coordinates; - var gen2Coords = Transform(secondGenComp.Owner).Coordinates; + var gen1Coords = Transform(firstGen).Coordinates; + var gen2Coords = Transform(secondGen).Coordinates; var delta = (gen2Coords - gen1Coords).Position; var dirVec = delta.Normalized(); @@ -302,10 +307,10 @@ public sealed class ContainmentFieldGeneratorSystem : EntitySystem while (currentOffset.Length() < stopDist) { var currentCoords = gen1Coords.Offset(currentOffset); - var newField = Spawn(firstGenComp.CreatedField, currentCoords); + var newField = Spawn(firstGen.Comp.CreatedField, currentCoords); var fieldXForm = Transform(newField); - fieldXForm.AttachParent(firstGenComp.Owner); + fieldXForm.AttachParent(firstGen); if (dirVec.GetDir() == Direction.East || dirVec.GetDir() == Direction.West) { var angle = fieldXForm.LocalPosition.ToAngle(); @@ -324,28 +329,28 @@ public sealed class ContainmentFieldGeneratorSystem : EntitySystem /// /// Creates a light component for the spawned fields. /// - public void UpdateConnectionLights(ContainmentFieldGeneratorComponent component) + public void UpdateConnectionLights(Entity generator) { - if (_light.TryGetLight(component.Owner, out var pointLightComponent)) + if (_light.TryGetLight(generator, out var pointLightComponent)) { - _light.SetEnabled(component.Owner, component.Connections.Count > 0, pointLightComponent); + _light.SetEnabled(generator, generator.Comp.Connections.Count > 0, pointLightComponent); } } /// /// Checks to see if this or the other gens connected to a new grid. If they did, remove connection. /// - public void GridCheck(EntityUid uid, ContainmentFieldGeneratorComponent component) + public void GridCheck(Entity generator) { var xFormQuery = GetEntityQuery(); - foreach (var (_, generators) in component.Connections) + foreach (var (_, generators) in generator.Comp.Connections) { - var gen1ParentGrid = xFormQuery.GetComponent(component.Owner).ParentUid; - var gent2ParentGrid = xFormQuery.GetComponent(generators.Item1.Owner).ParentUid; + var gen1ParentGrid = xFormQuery.GetComponent(generator).ParentUid; + var gent2ParentGrid = xFormQuery.GetComponent(generators.Item1).ParentUid; if (gen1ParentGrid != gent2ParentGrid) - RemoveConnections(uid, component); + RemoveConnections(generator); } } @@ -356,32 +361,37 @@ public sealed class ContainmentFieldGeneratorSystem : EntitySystem /// Check if a fields power falls between certain ranges to update the field gen visual for power. /// /// - /// - private void ChangePowerVisualizer(int power, ContainmentFieldGeneratorComponent component) + /// + private void ChangePowerVisualizer(int power, Entity generator) { - _visualizer.SetData(component.Owner, ContainmentFieldGeneratorVisuals.PowerLight, component.PowerBuffer switch { - <=0 => PowerLevelVisuals.NoPower, - >=25 => PowerLevelVisuals.HighPower, - _ => (component.PowerBuffer < component.PowerMinimum) ? PowerLevelVisuals.LowPower : PowerLevelVisuals.MediumPower + var component = generator.Comp; + _visualizer.SetData(generator, ContainmentFieldGeneratorVisuals.PowerLight, component.PowerBuffer switch + { + <= 0 => PowerLevelVisuals.NoPower, + >= 25 => PowerLevelVisuals.HighPower, + _ => (component.PowerBuffer < component.PowerMinimum) + ? PowerLevelVisuals.LowPower + : PowerLevelVisuals.MediumPower }); } /// /// Check if a field has any or no connections and if it's enabled to toggle the field level light /// - /// - private void ChangeFieldVisualizer(ContainmentFieldGeneratorComponent component) + /// + private void ChangeFieldVisualizer(Entity generator) { - _visualizer.SetData(component.Owner, ContainmentFieldGeneratorVisuals.FieldLight, component.Connections.Count switch { + _visualizer.SetData(generator, ContainmentFieldGeneratorVisuals.FieldLight, generator.Comp.Connections.Count switch + { >1 => FieldLevelVisuals.MultipleFields, 1 => FieldLevelVisuals.OneField, - _ => component.Enabled ? FieldLevelVisuals.On : FieldLevelVisuals.NoLevel + _ => generator.Comp.Enabled ? FieldLevelVisuals.On : FieldLevelVisuals.NoLevel }); } - private void ChangeOnLightVisualizer(ContainmentFieldGeneratorComponent component) + private void ChangeOnLightVisualizer(Entity generator) { - _visualizer.SetData(component.Owner, ContainmentFieldGeneratorVisuals.OnLight, component.IsConnected); + _visualizer.SetData(generator, ContainmentFieldGeneratorVisuals.OnLight, generator.Comp.IsConnected); } #endregion diff --git a/Content.Server/Singularity/EntitySystems/ContainmentFieldSystem.cs b/Content.Server/Singularity/EntitySystems/ContainmentFieldSystem.cs index 70cc992dc3..561db76a47 100644 --- a/Content.Server/Singularity/EntitySystems/ContainmentFieldSystem.cs +++ b/Content.Server/Singularity/EntitySystems/ContainmentFieldSystem.cs @@ -26,15 +26,15 @@ public sealed class ContainmentFieldSystem : EntitySystem { var otherBody = args.OtherEntity; - if (TryComp(otherBody, out var garbage)) + if (HasComp(otherBody)) { - _popupSystem.PopupEntity(Loc.GetString("comp-field-vaporized", ("entity", otherBody)), component.Owner, PopupType.LargeCaution); - QueueDel(garbage.Owner); + _popupSystem.PopupEntity(Loc.GetString("comp-field-vaporized", ("entity", otherBody)), uid, PopupType.LargeCaution); + QueueDel(otherBody); } if (TryComp(otherBody, out var physics) && physics.Mass <= component.MaxMass && physics.Hard) { - var fieldDir = Transform(component.Owner).WorldPosition; + var fieldDir = Transform(uid).WorldPosition; var playerDir = Transform(otherBody).WorldPosition; _throwing.TryThrow(otherBody, playerDir-fieldDir, strength: component.ThrowForce); diff --git a/Content.Server/Singularity/EntitySystems/EventHorizonSystem.cs b/Content.Server/Singularity/EntitySystems/EventHorizonSystem.cs index fd9eb3e8c6..a15dad8507 100644 --- a/Content.Server/Singularity/EntitySystems/EventHorizonSystem.cs +++ b/Content.Server/Singularity/EntitySystems/EventHorizonSystem.cs @@ -304,9 +304,13 @@ public sealed class EventHorizonSystem : SharedEventHorizonSystem var mapPos = xform.MapPosition; var box = Box2.CenteredAround(mapPos.Position, new Vector2(range, range)); var circle = new Circle(mapPos.Position, range); - foreach (var grid in _mapMan.FindGridsIntersecting(mapPos.MapId, box)) - { // TODO: Remover grid.Owner when this iterator returns entityuids as well. - AttemptConsumeTiles(uid, grid.GetTilesIntersecting(circle), grid.Owner, grid, eventHorizon); + var grids = new List>(); + _mapMan.FindGridsIntersecting(mapPos.MapId, box, ref grids); + + foreach (var grid in grids) + { + // TODO: Remover grid.Owner when this iterator returns entityuids as well. + AttemptConsumeTiles(uid, grid.Comp.GetTilesIntersecting(circle), grid, grid, eventHorizon); } } diff --git a/Content.Server/Singularity/EntitySystems/GravityWellSystem.cs b/Content.Server/Singularity/EntitySystems/GravityWellSystem.cs index b10685ed27..2ba4dbd41c 100644 --- a/Content.Server/Singularity/EntitySystems/GravityWellSystem.cs +++ b/Content.Server/Singularity/EntitySystems/GravityWellSystem.cs @@ -1,3 +1,6 @@ +using Content.Server.Singularity.Components; +using Content.Shared.Ghost; +using Content.Shared.Singularity.EntitySystems; using Robust.Shared.Map; using Robust.Shared.Map.Components; using Robust.Shared.Physics; @@ -5,10 +8,6 @@ using Robust.Shared.Physics.Components; using Robust.Shared.Physics.Systems; using Robust.Shared.Timing; -using Content.Shared.Singularity.EntitySystems; -using Content.Server.Singularity.Components; -using Content.Shared.Ghost; - namespace Content.Server.Singularity.EntitySystems; /// @@ -58,11 +57,12 @@ public sealed class GravityWellSystem : SharedGravityWellSystem if(!_timing.IsFirstTimePredicted) return; - foreach(var (gravWell, xform) in EntityManager.EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var gravWell, out var xform)) { var curTime = _timing.CurTime; if (gravWell.NextPulseTime <= curTime) - Update(gravWell.Owner, curTime - gravWell.LastPulseTime, gravWell, xform); + Update(uid, curTime - gravWell.LastPulseTime, gravWell, xform); } } diff --git a/Content.Server/Singularity/EntitySystems/SingularitySystem.cs b/Content.Server/Singularity/EntitySystems/SingularitySystem.cs index 37e26b9cc0..ddc63156bf 100644 --- a/Content.Server/Singularity/EntitySystems/SingularitySystem.cs +++ b/Content.Server/Singularity/EntitySystems/SingularitySystem.cs @@ -1,15 +1,13 @@ -using Robust.Shared.GameStates; -using Robust.Shared.Player; -using Robust.Shared.Timing; -using Robust.Server.GameStates; - -using Content.Shared.Singularity.Components; -using Content.Shared.Singularity.EntitySystems; -using Content.Shared.Singularity.Events; - using Content.Server.Physics.Components; using Content.Server.Singularity.Components; using Content.Server.Singularity.Events; +using Content.Shared.Singularity.Components; +using Content.Shared.Singularity.EntitySystems; +using Content.Shared.Singularity.Events; +using Robust.Server.GameStates; +using Robust.Shared.GameStates; +using Robust.Shared.Player; +using Robust.Shared.Timing; namespace Content.Server.Singularity.EntitySystems; @@ -75,11 +73,12 @@ public sealed class SingularitySystem : SharedSingularitySystem if(!_timing.IsFirstTimePredicted) return; - foreach(var singularity in EntityManager.EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var singularity)) { var curTime = _timing.CurTime; if (singularity.NextUpdateTime <= curTime) - Update(singularity.Owner, curTime - singularity.LastUpdateTime, singularity); + Update(uid, curTime - singularity.LastUpdateTime, singularity); } } @@ -129,14 +128,15 @@ public sealed class SingularitySystem : SharedSingularitySystem return; singularity.Energy = value; - SetLevel(uid, value switch { - >= 2400 => 6, - >= 1600 => 5, - >= 900 => 4, - >= 300 => 3, - >= 200 => 2, - > 0 => 1, - _ => 0 + SetLevel(uid, value switch + { + >= 2400 => 6, + >= 1600 => 5, + >= 900 => 4, + >= 300 => 3, + >= 200 => 2, + > 0 => 1, + _ => 0 }, singularity); } @@ -204,9 +204,9 @@ public sealed class SingularitySystem : SharedSingularitySystem MetaDataComponent? metaData = null; if (Resolve(uid, ref metaData) && metaData.EntityLifeStage <= EntityLifeStage.Initializing) - _audio.Play(comp.FormationSound, Filter.Pvs(comp.Owner), comp.Owner, true); + _audio.Play(comp.FormationSound, Filter.Pvs(uid), uid, true); - comp.AmbientSoundStream = _audio.Play(comp.AmbientSound, Filter.Pvs(comp.Owner), comp.Owner, true); + comp.AmbientSoundStream = _audio.Play(comp.AmbientSound, Filter.Pvs(uid), uid, true); UpdateSingularityLevel(uid, comp); } @@ -236,7 +236,7 @@ public sealed class SingularitySystem : SharedSingularitySystem MetaDataComponent? metaData = null; if (Resolve(uid, ref metaData) && metaData.EntityLifeStage >= EntityLifeStage.Terminating) - _audio.Play(comp.DissipationSound, Filter.Pvs(comp.Owner), comp.Owner, true); + _audio.Play(comp.DissipationSound, Filter.Pvs(uid), uid, true); } /// @@ -283,7 +283,7 @@ public sealed class SingularitySystem : SharedSingularitySystem // Should be slightly more efficient than checking literally everything we consume for a singularity component and doing the reverse. if (EntityManager.TryGetComponent(args.EventHorizonUid, out var singulo)) { - AdjustEnergy(singulo.Owner, comp.Energy, singularity: singulo); + AdjustEnergy(uid, comp.Energy, singularity: singulo); SetEnergy(uid, 0.0f, comp); } } diff --git a/Content.Server/Solar/EntitySystems/PowerSolarSystem.cs b/Content.Server/Solar/EntitySystems/PowerSolarSystem.cs index cead16b76d..6a8fc68d97 100644 --- a/Content.Server/Solar/EntitySystems/PowerSolarSystem.cs +++ b/Content.Server/Solar/EntitySystems/PowerSolarSystem.cs @@ -61,8 +61,7 @@ namespace Content.Server.Solar.EntitySystems /// /// Queue of panels to update each cycle. /// - private readonly Queue _updateQueue = new(); - + private readonly Queue> _updateQueue = new(); public override void Initialize() { @@ -102,24 +101,26 @@ namespace Content.Server.Solar.EntitySystems if (_updateQueue.Count > 0) { var panel = _updateQueue.Dequeue(); - if (panel.Running) + if (panel.Comp.Running) UpdatePanelCoverage(panel); } else { TotalPanelPower = 0; - foreach (var (panel, xform) in EntityManager.EntityQuery()) + + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var panel, out var xform)) { TotalPanelPower += panel.MaxSupply * panel.Coverage; xform.WorldRotation = TargetPanelRotation; - _updateQueue.Enqueue(panel); + _updateQueue.Enqueue((uid, panel)); } } } - private void UpdatePanelCoverage(SolarPanelComponent panel) + private void UpdatePanelCoverage(Entity panel) { - EntityUid entity = panel.Owner; + var entity = panel.Owner; var xform = EntityManager.GetComponent(entity); // So apparently, and yes, I *did* only find this out later, @@ -163,8 +164,8 @@ namespace Content.Server.Solar.EntitySystems } // Total coverage calculated; apply it to the panel. - panel.Coverage = coverage; - UpdateSupply((panel).Owner, panel); + panel.Comp.Coverage = coverage; + UpdateSupply(panel, panel); } public void UpdateSupply( diff --git a/Content.Server/Speech/EntitySystems/AddAccentClothingSystem.cs b/Content.Server/Speech/EntitySystems/AddAccentClothingSystem.cs index 23dfaef923..1f707c2249 100644 --- a/Content.Server/Speech/EntitySystems/AddAccentClothingSystem.cs +++ b/Content.Server/Speech/EntitySystems/AddAccentClothingSystem.cs @@ -23,16 +23,17 @@ public sealed class AddAccentClothingSystem : EntitySystem // check if entity was actually used as clothing // not just taken in pockets or something var isCorrectSlot = clothing.Slots.HasFlag(args.SlotFlags); - if (!isCorrectSlot) return; + if (!isCorrectSlot) + return; // does the user already has this accent? var componentType = _componentFactory.GetRegistration(component.Accent).Type; - if (EntityManager.HasComponent(args.Equipee, componentType)) return; + if (HasComp(args.Equipee, componentType)) + return; // add accent to the user var accentComponent = (Component) _componentFactory.GetComponent(componentType); - accentComponent.Owner = args.Equipee; - EntityManager.AddComponent(args.Equipee, accentComponent); + AddComp(args.Equipee, accentComponent); // snowflake case for replacement accent if (accentComponent is ReplacementAccentComponent rep) diff --git a/Content.Server/Station/Systems/StationSystem.cs b/Content.Server/Station/Systems/StationSystem.cs index 8fdf103cd7..65eabd8190 100644 --- a/Content.Server/Station/Systems/StationSystem.cs +++ b/Content.Server/Station/Systems/StationSystem.cs @@ -239,7 +239,7 @@ public sealed class StationSystem : EntitySystem foreach (var gridUid in dataComponent.Grids) { - if (!_mapManager.TryGetGrid(gridUid, out var grid) || + if (!TryComp(gridUid, out MapGridComponent? grid) || !xformQuery.TryGetComponent(gridUid, out var xform)) continue; @@ -429,7 +429,7 @@ public sealed class StationSystem : EntitySystem if (xform.GridUid == EntityUid.Invalid) { - Logger.Debug("A"); + Log.Debug("A"); return null; } @@ -438,12 +438,26 @@ public sealed class StationSystem : EntitySystem public List GetStations() { - return EntityQuery().Select(x => x.Owner).ToList(); + var stations = new List(); + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out _)) + { + stations.Add(uid); + } + + return stations; } public HashSet GetStationsSet() { - return EntityQuery().Select(x => x.Owner).ToHashSet(); + var stations = new HashSet(); + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out _)) + { + stations.Add(uid); + } + + return stations; } /// diff --git a/Content.Server/StationEvents/Events/BluespaceLockerRule.cs b/Content.Server/StationEvents/Events/BluespaceLockerRule.cs index ddf1ba784c..709b750334 100644 --- a/Content.Server/StationEvents/Events/BluespaceLockerRule.cs +++ b/Content.Server/StationEvents/Events/BluespaceLockerRule.cs @@ -1,5 +1,4 @@ -using System.Linq; -using Content.Server.GameTicking.Rules.Components; +using Content.Server.GameTicking.Rules.Components; using Content.Server.Resist; using Content.Server.Station.Components; using Content.Server.StationEvents.Components; @@ -18,13 +17,17 @@ public sealed class BluespaceLockerRule : StationEventSystem().ToList(); + var targets = new List(); + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var storageUid, out _, out _)) + { + targets.Add(storageUid); + } + RobustRandom.Shuffle(targets); - foreach (var target in targets) + foreach (var potentialLink in targets) { - var potentialLink = target.Item1.Owner; - if (HasComp(potentialLink) || HasComp(potentialLink) || !HasComp(potentialLink.ToCoordinates().GetGridUid(EntityManager))) diff --git a/Content.Server/StationEvents/Events/BreakerFlipRule.cs b/Content.Server/StationEvents/Events/BreakerFlipRule.cs index c53f3c5750..494779fe35 100644 --- a/Content.Server/StationEvents/Events/BreakerFlipRule.cs +++ b/Content.Server/StationEvents/Events/BreakerFlipRule.cs @@ -1,11 +1,9 @@ -using System.Linq; -using Content.Server.GameTicking.Rules.Components; +using Content.Server.GameTicking.Rules.Components; using Content.Server.Power.Components; using Content.Server.Power.EntitySystems; using Content.Server.Station.Components; using Content.Server.StationEvents.Components; using JetBrains.Annotations; -using Robust.Shared.Random; namespace Content.Server.StationEvents.Events; @@ -29,12 +27,13 @@ public sealed class BreakerFlipRule : StationEventSystem(); - foreach (var (apc, transform) in EntityQuery()) + var stationApcs = new List>(); + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var apcUid, out var apc, out var xform)) { - if (apc.MainBreakerEnabled && CompOrNull(transform.GridUid)?.Station == chosenStation) + if (apc.MainBreakerEnabled && CompOrNull(xform.GridUid)?.Station == chosenStation) { - stationApcs.Add(apc); + stationApcs.Add((apcUid, apc)); } } @@ -46,7 +45,7 @@ public sealed class BreakerFlipRule : StationEventSystem(); + while (query.MoveNext(out var gridId, out _, out var xform)) { - var aabb = _physics.GetWorldAABB(grid.Owner); + if (xform.MapID != mapId) + continue; + + var aabb = _physics.GetWorldAABB(gridId); playableArea = playableArea?.Union(aabb) ?? aabb; } diff --git a/Content.Server/StationEvents/Events/PowerGridCheckRule.cs b/Content.Server/StationEvents/Events/PowerGridCheckRule.cs index d24f04d800..fdd3e30d43 100644 --- a/Content.Server/StationEvents/Events/PowerGridCheckRule.cs +++ b/Content.Server/StationEvents/Events/PowerGridCheckRule.cs @@ -1,16 +1,14 @@ +using System.Threading; +using Content.Server.GameTicking.Rules.Components; using Content.Server.Power.Components; +using Content.Server.Power.EntitySystems; +using Content.Server.Station.Components; +using Content.Server.StationEvents.Components; using JetBrains.Annotations; using Robust.Shared.Audio; using Robust.Shared.Player; using Robust.Shared.Utility; -using System.Threading; -using Content.Server.Power.EntitySystems; using Timer = Robust.Shared.Timing.Timer; -using System.Linq; -using Content.Server.GameTicking.Rules.Components; -using Robust.Shared.Random; -using Content.Server.Station.Components; -using Content.Server.StationEvents.Components; namespace Content.Server.StationEvents.Events { @@ -26,10 +24,11 @@ namespace Content.Server.StationEvents.Events if (!TryGetRandomStation(out var chosenStation)) return; - foreach (var (apc, transform) in EntityQuery(true)) + var query = AllEntityQuery(); + while (query.MoveNext(out var apcUid ,out var apc, out var transform)) { if (apc.MainBreakerEnabled && CompOrNull(transform.GridUid)?.Station == chosenStation) - component.Powered.Add(apc.Owner); + component.Powered.Add(apcUid); } RobustRandom.Shuffle(component.Powered); diff --git a/Content.Server/StationEvents/Events/RandomSentienceRule.cs b/Content.Server/StationEvents/Events/RandomSentienceRule.cs index 8b2128178a..d90361fe96 100644 --- a/Content.Server/StationEvents/Events/RandomSentienceRule.cs +++ b/Content.Server/StationEvents/Events/RandomSentienceRule.cs @@ -1,8 +1,6 @@ using System.Linq; -using Content.Server.Chat.Systems; using Content.Server.GameTicking.Rules.Components; using Content.Server.Ghost.Roles.Components; -using Content.Server.Station.Systems; using Content.Server.StationEvents.Components; namespace Content.Server.StationEvents.Events; @@ -14,7 +12,13 @@ public sealed class RandomSentienceRule : StationEventSystem stationsToNotify = new(); var mod = GetSeverityModifier(); - var targetList = EntityQuery().ToList(); + var targetList = new List>(); + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var targetUid, out var target)) + { + targetList.Add((targetUid, target)); + } + RobustRandom.Shuffle(targetList); var toMakeSentient = (int) (RobustRandom.Next(2, 5) * Math.Sqrt(mod)); @@ -25,12 +29,12 @@ public sealed class RandomSentienceRule : StationEventSystem(target.Owner); - var ghostRole = EnsureComp(target.Owner); - EnsureComp(target.Owner); - ghostRole.RoleName = MetaData(target.Owner).EntityName; + RemComp(target); + var ghostRole = EnsureComp(target); + EnsureComp(target); + ghostRole.RoleName = MetaData(target).EntityName; ghostRole.RoleDescription = Loc.GetString("station-event-random-sentience-role-description", ("name", ghostRole.RoleName)); - groups.Add(Loc.GetString(target.FlavorKind)); + groups.Add(Loc.GetString(target.Comp.FlavorKind)); } if (groups.Count == 0) @@ -43,8 +47,9 @@ public sealed class RandomSentienceRule : StationEventSystem().ToArray(); + var storages = new List>(); + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var storage)) + { + storages.Add((uid, storage)); + } + _robustRandom.Shuffle(storages); // Add valid candidates till MinBluespaceLinks is met diff --git a/Content.Server/Storage/EntitySystems/CursedEntityStorageSystem.cs b/Content.Server/Storage/EntitySystems/CursedEntityStorageSystem.cs index 1492a3f481..f51c215c6e 100644 --- a/Content.Server/Storage/EntitySystems/CursedEntityStorageSystem.cs +++ b/Content.Server/Storage/EntitySystems/CursedEntityStorageSystem.cs @@ -1,10 +1,10 @@ +using System.Linq; using Content.Server.Storage.Components; using Content.Shared.Audio; +using Content.Shared.Storage.Components; using Robust.Shared.Audio; using Robust.Shared.Player; using Robust.Shared.Random; -using System.Linq; -using Content.Shared.Storage.Components; namespace Content.Server.Storage.EntitySystems; @@ -28,13 +28,19 @@ public sealed class CursedEntityStorageSystem : EntitySystem if (storage.Open || storage.Contents.ContainedEntities.Count <= 0) return; - var lockerQuery = EntityQuery().ToList(); - lockerQuery.Remove(storage); + var lockers = new List>(); + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var storageUid, out var storageComp)) + { + lockers.Add((storageUid, storageComp)); + } + + lockers.RemoveAll(e => e.Owner == uid); - if (lockerQuery.Count == 0) + if (lockers.Count == 0) return; - var lockerEnt = _random.Pick(lockerQuery).Owner; + var lockerEnt = _random.Pick(lockers).Owner; foreach (var entity in storage.Contents.ContainedEntities.ToArray()) { diff --git a/Content.Server/Storage/EntitySystems/EntityStorageSystem.cs b/Content.Server/Storage/EntitySystems/EntityStorageSystem.cs index cbd4883b4c..4bcad622c7 100644 --- a/Content.Server/Storage/EntitySystems/EntityStorageSystem.cs +++ b/Content.Server/Storage/EntitySystems/EntityStorageSystem.cs @@ -12,6 +12,7 @@ using Content.Shared.Storage.Components; using Content.Shared.Storage.EntitySystems; using Content.Shared.Tools.Systems; using Content.Shared.Verbs; +using Robust.Server.GameObjects; using Robust.Shared.Containers; using Robust.Shared.GameStates; using Robust.Shared.Map; @@ -23,6 +24,7 @@ public sealed class EntityStorageSystem : SharedEntityStorageSystem [Dependency] private readonly ConstructionSystem _construction = default!; [Dependency] private readonly AtmosphereSystem _atmos = default!; [Dependency] private readonly IMapManager _map = default!; + [Dependency] private readonly MapSystem _mapSystem = default!; public override void Initialize() { @@ -130,9 +132,9 @@ public sealed class EntityStorageSystem : SharedEntityStorageSystem { var targetCoordinates = new EntityCoordinates(uid, component.EnteringOffset).ToMap(EntityManager, TransformSystem); - if (_map.TryFindGridAt(targetCoordinates, out _, out var grid)) + if (_map.TryFindGridAt(targetCoordinates, out var gridId, out var grid)) { - return grid.GetTileRef(targetCoordinates); + return _mapSystem.GetTileRef(gridId, grid, targetCoordinates); } return null; diff --git a/Content.Server/Storage/EntitySystems/PickRandomSystem.cs b/Content.Server/Storage/EntitySystems/PickRandomSystem.cs index 50f6db459c..dbbe1dd778 100644 --- a/Content.Server/Storage/EntitySystems/PickRandomSystem.cs +++ b/Content.Server/Storage/EntitySystems/PickRandomSystem.cs @@ -1,11 +1,11 @@ +using System.Linq; using Content.Server.Storage.Components; using Content.Shared.Database; using Content.Shared.Hands.EntitySystems; +using Content.Shared.Storage; using Content.Shared.Verbs; using Robust.Shared.Containers; using Robust.Shared.Random; -using System.Linq; -using Content.Shared.Storage; namespace Content.Server.Storage.EntitySystems; @@ -55,7 +55,7 @@ public sealed class PickRandomSystem : EntitySystem var picked = _random.Pick(entities); // if it fails to go into a hand of the user, will be on the storage - _container.AttachParentToContainerOrGrid(Transform(picked)); + _container.AttachParentToContainerOrGrid((picked, Transform(picked))); // TODO: try to put in hands, failing that put it on the storage _hands.TryPickupAnyHand(user, picked); diff --git a/Content.Server/Storage/EntitySystems/SpawnItemsOnUseSystem.cs b/Content.Server/Storage/EntitySystems/SpawnItemsOnUseSystem.cs index 061ddee824..25c31e48ca 100644 --- a/Content.Server/Storage/EntitySystems/SpawnItemsOnUseSystem.cs +++ b/Content.Server/Storage/EntitySystems/SpawnItemsOnUseSystem.cs @@ -4,7 +4,6 @@ using Content.Server.Storage.Components; using Content.Shared.Database; using Content.Shared.Hands.EntitySystems; using Content.Shared.Interaction.Events; -using Content.Shared.Storage; using Robust.Shared.Audio; using Robust.Shared.Map; using Robust.Shared.Player; @@ -76,7 +75,7 @@ namespace Content.Server.Storage.EntitySystems foreach (var proto in spawnEntities) { entityToPlaceInHands = Spawn(proto, coords); - _adminLogger.Add(LogType.EntitySpawn, LogImpact.Low, $"{ToPrettyString(args.User)} used {ToPrettyString(component.Owner)} which spawned {ToPrettyString(entityToPlaceInHands.Value)}"); + _adminLogger.Add(LogType.EntitySpawn, LogImpact.Low, $"{ToPrettyString(args.User)} used {ToPrettyString(uid)} which spawned {ToPrettyString(entityToPlaceInHands.Value)}"); } if (component.Sound != null) diff --git a/Content.Server/Strip/StrippableSystem.cs b/Content.Server/Strip/StrippableSystem.cs index 8f723ab97d..a8ddf1a986 100644 --- a/Content.Server/Strip/StrippableSystem.cs +++ b/Content.Server/Strip/StrippableSystem.cs @@ -63,7 +63,7 @@ namespace Content.Server.Strip } } - private void OnStripButtonPressed(EntityUid target, StrippableComponent component, StrippingSlotButtonPressed args) + private void OnStripButtonPressed(Entity strippable, ref StrippingSlotButtonPressed args) { if (args.Session.AttachedEntity is not {Valid: true} user || !TryComp(user, out var userHands)) @@ -71,22 +71,22 @@ namespace Content.Server.Strip if (args.IsHand) { - StripHand(target, user, args.Slot, component, userHands); + StripHand(user, args.Slot, strippable, userHands); return; } - if (!TryComp(target, out var inventory)) + if (!TryComp(strippable, out var inventory)) return; - var hasEnt = _inventorySystem.TryGetSlotEntity(target, args.Slot, out var held, inventory); + var hasEnt = _inventorySystem.TryGetSlotEntity(strippable, args.Slot, out var held, inventory); if (userHands.ActiveHandEntity != null && !hasEnt) - PlaceActiveHandItemInInventory(user, target, userHands.ActiveHandEntity.Value, args.Slot, component); + PlaceActiveHandItemInInventory(user, strippable, userHands.ActiveHandEntity.Value, args.Slot, strippable); else if (userHands.ActiveHandEntity == null && hasEnt) - TakeItemFromInventory(user, target, held!.Value, args.Slot, component); + TakeItemFromInventory(user, strippable, held!.Value, args.Slot, strippable); } - private void StripHand(EntityUid target, EntityUid user, string handId, StrippableComponent component, HandsComponent userHands) + private void StripHand(EntityUid user, string handId, Entity target, HandsComponent userHands) { if (!_handsSystem.TryGetHand(target, handId, out var hand)) return; @@ -101,23 +101,23 @@ namespace Content.Server.Strip } if (userHands.ActiveHandEntity != null && hand.HeldEntity == null) - PlaceActiveHandItemInHands(user, target, userHands.ActiveHandEntity.Value, handId, component); + PlaceActiveHandItemInHands(user, target, userHands.ActiveHandEntity.Value, handId, target); else if (userHands.ActiveHandEntity == null && hand.HeldEntity != null) - TakeItemFromHands(user,target, hand.HeldEntity.Value, handId, component); + TakeItemFromHands(user, target, hand.HeldEntity.Value, handId, target); } - public override void StartOpeningStripper(EntityUid user, StrippableComponent component, bool openInCombat = false) + public override void StartOpeningStripper(EntityUid user, Entity strippable, bool openInCombat = false) { - base.StartOpeningStripper(user, component, openInCombat); + base.StartOpeningStripper(user, strippable, openInCombat); if (TryComp(user, out var mode) && mode.IsInCombatMode && !openInCombat) return; if (TryComp(user, out var actor)) { - if (_userInterfaceSystem.SessionHasOpenUi(component.Owner, StrippingUiKey.Key, actor.PlayerSession)) + if (_userInterfaceSystem.SessionHasOpenUi(strippable, StrippingUiKey.Key, actor.PlayerSession)) return; - _userInterfaceSystem.TryOpen(component.Owner, StrippingUiKey.Key, actor.PlayerSession); + _userInterfaceSystem.TryOpen(strippable, StrippingUiKey.Key, actor.PlayerSession); } } @@ -126,14 +126,14 @@ namespace Content.Server.Strip if (args.Hands == null || !args.CanAccess || !args.CanInteract || args.Target == args.User) return; - if (!EntityManager.TryGetComponent(args.User, out ActorComponent? actor)) + if (!HasComp(args.User)) return; Verb verb = new() { Text = Loc.GetString("strip-verb-get-data-text"), Icon = new SpriteSpecifier.Texture(new ("/Textures/Interface/VerbIcons/outfit.svg.192dpi.png")), - Act = () => StartOpeningStripper(args.User, component, true), + Act = () => StartOpeningStripper(args.User, (uid, component), true), }; args.Verbs.Add(verb); } @@ -150,7 +150,7 @@ namespace Content.Server.Strip { Text = Loc.GetString("strip-verb-get-data-text"), Icon = new SpriteSpecifier.Texture(new ("/Textures/Interface/VerbIcons/outfit.svg.192dpi.png")), - Act = () => StartOpeningStripper(args.User, component, true), + Act = () => StartOpeningStripper(args.User, (uid, component), true), Category = VerbCategory.Examine, }; @@ -162,10 +162,10 @@ namespace Content.Server.Strip if (args.Target == args.User) return; - if (!TryComp(args.User, out var actor)) + if (!HasComp(args.User)) return; - StartOpeningStripper(args.User, component); + StartOpeningStripper(args.User, (uid, component)); } /// @@ -238,7 +238,8 @@ namespace Content.Server.Strip _adminLogger.Add(LogType.Stripping, LogImpact.Low, $"{ToPrettyString(user):user} is trying to place the item {ToPrettyString(held):item} in {ToPrettyString(target):target}'s {slot} slot"); var result = await _doAfter.WaitDoAfter(doAfterArgs); - if (result != DoAfterStatus.Finished) return; + if (result != DoAfterStatus.Finished) + return; DebugTools.Assert(userHands.ActiveHand?.HeldEntity == held); @@ -319,7 +320,7 @@ namespace Content.Server.Strip EntityUid target, EntityUid item, string slot, - StrippableComponent component) + Entity strippable) { bool Check() { @@ -368,7 +369,7 @@ namespace Content.Server.Strip _popup.PopupEntity(Loc.GetString("strippable-component-alert-owner-hidden", ("slot", slot)), target, target, PopupType.Large); } - else if (_inventorySystem.TryGetSlotEntity(component.Owner, slot, out var slotItem)) + else if (_inventorySystem.TryGetSlotEntity(strippable, slot, out var slotItem)) { _popup.PopupEntity(Loc.GetString("strippable-component-alert-owner", ("user", Identity.Entity(user, EntityManager)), ("item", slotItem)), target, target, PopupType.Large); @@ -378,9 +379,10 @@ namespace Content.Server.Strip _adminLogger.Add(LogType.Stripping, LogImpact.Low, $"{ToPrettyString(user):user} is trying to strip the item {ToPrettyString(item):item} from {ToPrettyString(target):target}"); var result = await _doAfter.WaitDoAfter(doAfterArgs); - if (result != DoAfterStatus.Finished) return; + if (result != DoAfterStatus.Finished) + return; - if (!_inventorySystem.TryUnequip(user, component.Owner, slot)) + if (!_inventorySystem.TryUnequip(user, strippable, slot)) return; // Raise a dropped event, so that things like gas tank internals properly deactivate when stripping @@ -394,7 +396,7 @@ namespace Content.Server.Strip /// /// Takes an item from a hand and places it in the user's active hand. /// - private async void TakeItemFromHands(EntityUid user, EntityUid target, EntityUid item, string handName, StrippableComponent component) + private async void TakeItemFromHands(EntityUid user, EntityUid target, EntityUid item, string handName, Entity strippable) { var hands = Comp(target); var userHands = Comp(user); @@ -419,7 +421,7 @@ namespace Content.Server.Strip return true; } - var userEv = new BeforeStripEvent(component.HandStripDelay); + var userEv = new BeforeStripEvent(strippable.Comp.HandStripDelay); RaiseLocalEvent(user, userEv); var ev = new BeforeGettingStrippedEvent(userEv.Time, userEv.Stealth); RaiseLocalEvent(target, ev); @@ -441,15 +443,16 @@ namespace Content.Server.Strip _popup.PopupEntity( Loc.GetString("strippable-component-alert-owner", ("user", Identity.Entity(user, EntityManager)), ("item", item)), - component.Owner, - component.Owner); + strippable.Owner, + strippable.Owner); } _adminLogger.Add(LogType.Stripping, LogImpact.Low, $"{ToPrettyString(user):user} is trying to strip the item {ToPrettyString(item):item} from {ToPrettyString(target):target}"); var result = await _doAfter.WaitDoAfter(doAfterArgs); - if (result != DoAfterStatus.Finished) return; + if (result != DoAfterStatus.Finished) + return; _handsSystem.TryDrop(target, item, checkActionBlocker: false, handsComp: hands); _handsSystem.PickupOrDrop(user, item, handsComp: userHands); diff --git a/Content.Server/SurveillanceCamera/Systems/SurveillanceCameraMonitorSystem.cs b/Content.Server/SurveillanceCamera/Systems/SurveillanceCameraMonitorSystem.cs index 2d691602f7..17eee198b8 100644 --- a/Content.Server/SurveillanceCamera/Systems/SurveillanceCameraMonitorSystem.cs +++ b/Content.Server/SurveillanceCamera/Systems/SurveillanceCameraMonitorSystem.cs @@ -1,18 +1,10 @@ using System.Linq; -using Content.Server.Chat.Systems; using Content.Server.DeviceNetwork; using Content.Server.DeviceNetwork.Systems; using Content.Server.Power.Components; using Content.Server.UserInterface; -using Content.Server.Wires; -using Content.Shared.Interaction; -using Content.Shared.Speech; using Content.Shared.SurveillanceCamera; using Robust.Server.GameObjects; -using Robust.Server.Player; -using Robust.Shared.Prototypes; -using Robust.Shared.Random; -using Robust.Shared.Timing; namespace Content.Server.SurveillanceCamera; @@ -42,21 +34,22 @@ public sealed class SurveillanceCameraMonitorSystem : EntitySystem public override void Update(float frameTime) { - foreach (var (_, monitor) in EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out _, out var monitor)) { - if (Paused(monitor.Owner)) + if (Paused(uid)) { continue; } monitor.LastHeartbeatSent += frameTime; - SendHeartbeat(monitor.Owner, monitor); + SendHeartbeat(uid, monitor); monitor.LastHeartbeat += frameTime; if (monitor.LastHeartbeat > _maxHeartbeatTime) { - DisconnectCamera(monitor.Owner, true, monitor); - EntityManager.RemoveComponent(monitor.Owner); + DisconnectCamera(uid, true, monitor); + EntityManager.RemoveComponent(uid); } } } diff --git a/Content.Server/Tabletop/TabletopSystem.cs b/Content.Server/Tabletop/TabletopSystem.cs index 3b817c2c61..2e271080d0 100644 --- a/Content.Server/Tabletop/TabletopSystem.cs +++ b/Content.Server/Tabletop/TabletopSystem.cs @@ -1,6 +1,5 @@ using Content.Server.Popups; using Content.Server.Tabletop.Components; -using Content.Shared.Examine; using Content.Shared.Hands.Components; using Content.Shared.Interaction; using Content.Shared.Item; @@ -178,20 +177,19 @@ namespace Content.Server.Tabletop { base.Update(frameTime); - foreach (var gamer in EntityManager.EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var gamer)) { - if (!EntityManager.EntityExists(gamer.Tabletop)) + if (!Exists(gamer.Tabletop)) continue; - if (!EntityManager.TryGetComponent(gamer.Owner, out ActorComponent? actor)) + if (!TryComp(uid, out ActorComponent? actor)) { - EntityManager.RemoveComponent(gamer.Owner); + EntityManager.RemoveComponent(uid); return; } - var gamerUid = (gamer).Owner; - - if (actor.PlayerSession.Status != SessionStatus.InGame || !CanSeeTable(gamerUid, gamer.Tabletop)) + if (actor.PlayerSession.Status != SessionStatus.InGame || !CanSeeTable(uid, gamer.Tabletop)) CloseSessionFor(actor.PlayerSession, gamer.Tabletop); } } diff --git a/Content.Server/Temperature/Systems/TemperatureSystem.cs b/Content.Server/Temperature/Systems/TemperatureSystem.cs index 0dc5e9391a..27521cadf6 100644 --- a/Content.Server/Temperature/Systems/TemperatureSystem.cs +++ b/Content.Server/Temperature/Systems/TemperatureSystem.cs @@ -1,3 +1,4 @@ +using System.Linq; using Content.Server.Administration.Logs; using Content.Server.Atmos.Components; using Content.Server.Atmos.EntitySystems; @@ -11,7 +12,6 @@ using Content.Shared.Inventory; using Content.Shared.Rejuvenate; using Content.Shared.Temperature; using Robust.Server.GameObjects; -using System.Linq; namespace Content.Server.Temperature.Systems; @@ -28,7 +28,7 @@ public sealed class TemperatureSystem : EntitySystem /// This is done because both AtmosExposed and Flammable call ChangeHeat in the same tick, meaning /// that we need some mechanism to ensure it doesn't double dip on damage for both calls. /// - public HashSet ShouldUpdateDamage = new(); + public HashSet> ShouldUpdateDamage = new(); public float UpdateInterval = 1.0f; @@ -99,7 +99,7 @@ public sealed class TemperatureSystem : EntitySystem if (!ignoreHeatResistance) { var ev = new ModifyChangedTemperatureEvent(heatAmount); - RaiseLocalEvent(uid, ev, false); + RaiseLocalEvent(uid, ev); heatAmount = ev.TemperatureDelta; } @@ -189,9 +189,9 @@ public sealed class TemperatureSystem : EntitySystem } } - private void EnqueueDamage(EntityUid uid, TemperatureComponent component, OnTemperatureChangeEvent args) + private void EnqueueDamage(Entity temperature, ref OnTemperatureChangeEvent args) { - ShouldUpdateDamage.Add(component); + ShouldUpdateDamage.Add(temperature); } private void ChangeDamage(EntityUid uid, TemperatureComponent temperature) diff --git a/Content.Server/Tools/ToolSystem.Welder.cs b/Content.Server/Tools/ToolSystem.Welder.cs index 8a4b881f9f..e0dc341a16 100644 --- a/Content.Server/Tools/ToolSystem.Welder.cs +++ b/Content.Server/Tools/ToolSystem.Welder.cs @@ -15,7 +15,6 @@ using Content.Shared.Tools.Components; using Content.Shared.Weapons.Melee.Events; using Robust.Shared.Audio; using Robust.Shared.GameStates; -using Robust.Shared.Utility; namespace Content.Server.Tools { @@ -24,7 +23,7 @@ namespace Content.Server.Tools private readonly HashSet _activeWelders = new(); private const float WelderUpdateTimer = 1f; - private float _welderTimer = 0f; + private float _welderTimer; public void InitializeWelders() { @@ -112,7 +111,7 @@ namespace Content.Server.Tools _adminLogger.Add(LogType.Action, LogImpact.Low, $"{ToPrettyString(uid):welder} toggled on"); var ev = new WelderToggledEvent(true); - RaiseLocalEvent(welder.Owner, ev, false); + RaiseLocalEvent(uid, ev); var hotEvent = new IsHotEvent() {IsHot = true}; RaiseLocalEvent(uid, hotEvent); @@ -162,7 +161,7 @@ namespace Content.Server.Tools _adminLogger.Add(LogType.Action, LogImpact.Low, $"{ToPrettyString(uid):welder} toggled off"); var ev = new WelderToggledEvent(false); - RaiseLocalEvent(uid, ev, false); + RaiseLocalEvent(uid, ev); var hotEvent = new IsHotEvent() {IsHot = false}; RaiseLocalEvent(uid, hotEvent); @@ -187,7 +186,7 @@ namespace Content.Server.Tools private void OnWelderStartup(EntityUid uid, WelderComponent welder, ComponentStartup args) { // TODO: Delete this shit what - Dirty(welder); + Dirty(uid, welder); } private void OnWelderIsHotEvent(EntityUid uid, WelderComponent welder, IsHotEvent args) @@ -222,7 +221,7 @@ namespace Content.Server.Tools { // TODO what // ???? - Dirty(welder); + Dirty(uid, welder); } private void OnWelderActivate(EntityUid uid, WelderComponent welder, ActivateInWorldEvent args) @@ -315,7 +314,7 @@ namespace Content.Server.Tools if (solution.GetTotalPrototypeQuantity(welder.FuelReagent) <= FixedPoint2.Zero) TryTurnWelderOff(tool, null, welder); - Dirty(welder); + Dirty(tool, welder); } _welderTimer -= WelderUpdateTimer; diff --git a/Content.Server/Traitor/Uplink/SurplusBundle/SurplusBundleSystem.cs b/Content.Server/Traitor/Uplink/SurplusBundle/SurplusBundleSystem.cs index 11187e969f..5c0a56d346 100644 --- a/Content.Server/Traitor/Uplink/SurplusBundle/SurplusBundleSystem.cs +++ b/Content.Server/Traitor/Uplink/SurplusBundle/SurplusBundleSystem.cs @@ -1,8 +1,8 @@ using System.Linq; -using Content.Server.Store.Systems; using Content.Server.Storage.EntitySystems; -using Content.Shared.Store; +using Content.Server.Store.Systems; using Content.Shared.FixedPoint; +using Content.Shared.Store; using Robust.Shared.Prototypes; using Robust.Shared.Random; @@ -50,7 +50,7 @@ public sealed class SurplusBundleSystem : EntitySystem foreach (var item in content) { var ent = EntityManager.SpawnEntity(item.ProductEntity, cords); - _entityStorage.Insert(ent, component.Owner); + _entityStorage.Insert(ent, uid); } } diff --git a/Content.Server/Traits/Assorted/NarcolepsySystem.cs b/Content.Server/Traits/Assorted/NarcolepsySystem.cs index c1fdde4ed3..e4fa1ccbc7 100644 --- a/Content.Server/Traits/Assorted/NarcolepsySystem.cs +++ b/Content.Server/Traits/Assorted/NarcolepsySystem.cs @@ -39,7 +39,8 @@ public sealed class NarcolepsySystem : EntitySystem { base.Update(frameTime); - foreach (var narcolepsy in EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var narcolepsy)) { narcolepsy.NextIncidentTime -= frameTime; @@ -55,7 +56,7 @@ public sealed class NarcolepsySystem : EntitySystem // Make sure the sleep time doesn't cut into the time to next incident. narcolepsy.NextIncidentTime += duration; - _statusEffects.TryAddStatusEffect(narcolepsy.Owner, StatusEffectKey, + _statusEffects.TryAddStatusEffect(uid, StatusEffectKey, TimeSpan.FromSeconds(duration), false); } } diff --git a/Content.Server/Xenoarchaeology/XenoArtifacts/Effects/Systems/PolyArtifactSystem.cs b/Content.Server/Xenoarchaeology/XenoArtifacts/Effects/Systems/PolyArtifactSystem.cs index d192e928d8..ba2786f32d 100644 --- a/Content.Server/Xenoarchaeology/XenoArtifacts/Effects/Systems/PolyArtifactSystem.cs +++ b/Content.Server/Xenoarchaeology/XenoArtifacts/Effects/Systems/PolyArtifactSystem.cs @@ -1,9 +1,8 @@ +using Content.Server.Polymorph.Systems; using Content.Server.Xenoarchaeology.XenoArtifacts.Effects.Components; using Content.Server.Xenoarchaeology.XenoArtifacts.Events; using Content.Shared.Humanoid; -using Content.Server.Polymorph.Systems; using Content.Shared.Mobs.Systems; -using Content.Shared.Polymorph; namespace Content.Server.Xenoarchaeology.XenoArtifacts.Effects.Systems; @@ -28,7 +27,10 @@ public sealed class PolyArtifactSystem : EntitySystem private void OnActivate(EntityUid uid, PolyArtifactComponent component, ArtifactActivatedEvent args) { var xform = Transform(uid); - foreach (var comp in _lookup.GetComponentsInRange(xform.Coordinates, component.Range)) + var humanoids = new HashSet>(); + _lookup.GetEntitiesInRange(xform.Coordinates, component.Range, humanoids); + + foreach (var comp in humanoids) { var target = comp.Owner; if (_mob.IsAlive(target)) diff --git a/Content.Server/Xenoarchaeology/XenoArtifacts/Effects/Systems/ShuffleArtifactSystem.cs b/Content.Server/Xenoarchaeology/XenoArtifacts/Effects/Systems/ShuffleArtifactSystem.cs index 675d3e9387..b977cb038c 100644 --- a/Content.Server/Xenoarchaeology/XenoArtifacts/Effects/Systems/ShuffleArtifactSystem.cs +++ b/Content.Server/Xenoarchaeology/XenoArtifacts/Effects/Systems/ShuffleArtifactSystem.cs @@ -23,7 +23,7 @@ public sealed class ShuffleArtifactSystem : EntitySystem var mobState = GetEntityQuery(); List allCoords = new(); - List toShuffle = new(); + List> toShuffle = new(); foreach (var ent in _lookup.GetEntitiesInRange(uid, component.Radius, LookupFlags.Dynamic | LookupFlags.Sundries)) { @@ -32,7 +32,7 @@ public sealed class ShuffleArtifactSystem : EntitySystem var xform = Transform(ent); - toShuffle.Add(xform); + toShuffle.Add((ent, xform)); allCoords.Add(xform.Coordinates); } diff --git a/Content.Server/Xenoarchaeology/XenoArtifacts/RandomArtifactSpriteSystem.cs b/Content.Server/Xenoarchaeology/XenoArtifacts/RandomArtifactSpriteSystem.cs index c3af6a11e2..091441df21 100644 --- a/Content.Server/Xenoarchaeology/XenoArtifacts/RandomArtifactSpriteSystem.cs +++ b/Content.Server/Xenoarchaeology/XenoArtifacts/RandomArtifactSpriteSystem.cs @@ -24,8 +24,9 @@ public sealed class RandomArtifactSpriteSystem : EntitySystem public override void Update(float frameTime) { base.Update(frameTime); - var query = EntityManager.EntityQuery(); - foreach (var (component, appearance) in query) + + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var component, out var appearance)) { if (component.ActivationStart == null) continue; @@ -33,7 +34,7 @@ public sealed class RandomArtifactSpriteSystem : EntitySystem var timeDif = _time.CurTime - component.ActivationStart.Value; if (timeDif.Seconds >= component.ActivationTime) { - _appearance.SetData(appearance.Owner, SharedArtifactsVisuals.IsActivated, false, appearance); + _appearance.SetData(uid, SharedArtifactsVisuals.IsActivated, false, appearance); component.ActivationStart = null; } } diff --git a/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactDeathTriggerSystem.cs b/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactDeathTriggerSystem.cs index 4fa21535a4..a924120734 100644 --- a/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactDeathTriggerSystem.cs +++ b/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactDeathTriggerSystem.cs @@ -20,8 +20,9 @@ public sealed class ArtifactDeathTriggerSystem : EntitySystem var deathXform = Transform(ev.Target); - var toActivate = new List(); - foreach (var (trigger, xform) in EntityQuery()) + var toActivate = new List>(); + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var trigger, out var xform)) { if (!deathXform.Coordinates.TryDistance(EntityManager, xform.Coordinates, out var distance)) continue; @@ -29,12 +30,12 @@ public sealed class ArtifactDeathTriggerSystem : EntitySystem if (distance > trigger.Range) continue; - toActivate.Add(trigger); + toActivate.Add((uid, trigger)); } foreach (var a in toActivate) { - _artifact.TryActivateArtifact(a.Owner); + _artifact.TryActivateArtifact(a); } } } diff --git a/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactElectricityTriggerSystem.cs b/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactElectricityTriggerSystem.cs index 5988997101..aa2a16aa1b 100644 --- a/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactElectricityTriggerSystem.cs +++ b/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactElectricityTriggerSystem.cs @@ -20,18 +20,20 @@ public sealed class ArtifactElectricityTriggerSystem : EntitySystem public override void Update(float frameTime) { base.Update(frameTime); - List toUpdate = new(); - foreach (var (trigger, power, artifact) in EntityQuery()) + + List> toUpdate = new(); + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var trigger, out var power, out var artifact)) { if (power.ReceivedPower <= trigger.MinPower) continue; - toUpdate.Add(artifact); + toUpdate.Add((uid, artifact)); } foreach (var a in toUpdate) { - _artifactSystem.TryActivateArtifact(a.Owner, null, a); + _artifactSystem.TryActivateArtifact(a, null, a); } } diff --git a/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactGasTriggerSystem.cs b/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactGasTriggerSystem.cs index 9a88968923..a0c4971d8e 100644 --- a/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactGasTriggerSystem.cs +++ b/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactGasTriggerSystem.cs @@ -30,11 +30,10 @@ public sealed class ArtifactGasTriggerSystem : EntitySystem { base.Update(frameTime); - List toUpdate = new(); - foreach (var (trigger, artifact, transform) in EntityQuery()) + List> toUpdate = new(); + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var trigger, out var artifact, out var transform)) { - var uid = trigger.Owner; - if (trigger.ActivationGas == null) continue; @@ -49,12 +48,12 @@ public sealed class ArtifactGasTriggerSystem : EntitySystem if (moles < trigger.ActivationMoles) continue; - toUpdate.Add(artifact); + toUpdate.Add((uid, artifact)); } foreach (var a in toUpdate) { - _artifactSystem.TryActivateArtifact(a.Owner, null, a); + _artifactSystem.TryActivateArtifact(a, null, a); } } } diff --git a/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactHeatTriggerSystem.cs b/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactHeatTriggerSystem.cs index e54dc9a353..6c62f5d342 100644 --- a/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactHeatTriggerSystem.cs +++ b/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactHeatTriggerSystem.cs @@ -24,10 +24,10 @@ public sealed class ArtifactHeatTriggerSystem : EntitySystem { base.Update(frameTime); - List toUpdate = new(); - foreach (var (trigger, transform, artifact) in EntityQuery()) + List> toUpdate = new(); + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var trigger, out var transform, out var artifact)) { - var uid = trigger.Owner; var environment = _atmosphereSystem.GetTileMixture(transform.GridUid, transform.MapUid, _transformSystem.GetGridOrMapTilePosition(uid, transform)); if (environment == null) @@ -36,12 +36,12 @@ public sealed class ArtifactHeatTriggerSystem : EntitySystem if (environment.Temperature < trigger.ActivationTemperature) continue; - toUpdate.Add(artifact); + toUpdate.Add((uid, artifact)); } foreach (var a in toUpdate) { - _artifactSystem.TryActivateArtifact(a.Owner, null, a); + _artifactSystem.TryActivateArtifact(a, null, a); } } diff --git a/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactMagnetTriggerSystem.cs b/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactMagnetTriggerSystem.cs index 1960982841..0220c2ce1a 100644 --- a/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactMagnetTriggerSystem.cs +++ b/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactMagnetTriggerSystem.cs @@ -29,13 +29,12 @@ public sealed class ArtifactMagnetTriggerSystem : EntitySystem List toActivate = new(); //assume that there's more instruments than artifacts - foreach (var magboot in EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var magboot, out var magXform)) { if (!magboot.On) continue; - var magXform = Transform(magboot.Owner); - foreach (var (trigger, xform) in artifactQuery) { if (!magXform.Coordinates.TryDistance(EntityManager, xform.Coordinates, out var distance)) @@ -44,7 +43,7 @@ public sealed class ArtifactMagnetTriggerSystem : EntitySystem if (distance > trigger.Range) continue; - toActivate.Add(trigger.Owner); + toActivate.Add(uid); } } @@ -59,7 +58,8 @@ public sealed class ArtifactMagnetTriggerSystem : EntitySystem var magXform = Transform(ev.Magnet); var toActivate = new List(); - foreach (var (artifact, xform) in EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var artifact, out var xform)) { if (!magXform.Coordinates.TryDistance(EntityManager, xform.Coordinates, out var distance)) continue; @@ -67,7 +67,7 @@ public sealed class ArtifactMagnetTriggerSystem : EntitySystem if (distance > artifact.Range) continue; - toActivate.Add(artifact.Owner); + toActivate.Add(uid); } foreach (var a in toActivate) diff --git a/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactMusicTriggerSystem.cs b/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactMusicTriggerSystem.cs index 1f2718da2b..c62ed58752 100644 --- a/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactMusicTriggerSystem.cs +++ b/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactMusicTriggerSystem.cs @@ -11,22 +11,29 @@ public sealed class ArtifactMusicTriggerSystem : EntitySystem { [Dependency] private readonly ArtifactSystem _artifact = default!; + private readonly List> _artifacts = new(); + public override void Update(float frameTime) { base.Update(frameTime); - var artifactQuery = EntityQuery().ToArray(); - if (!artifactQuery.Any()) + _artifacts.Clear(); + var artifactQuery = EntityQueryEnumerator(); + while (artifactQuery.MoveNext(out var uid, out var trigger, out var xform)) + { + _artifacts.Add((uid, trigger, xform)); + } + + if (!_artifacts.Any()) return; List toActivate = new(); + var query = EntityQueryEnumerator(); //assume that there's more instruments than artifacts - foreach (var activeinstrument in EntityQuery()) + while (query.MoveNext(out _, out var instXform)) { - var instXform = Transform(activeinstrument.Owner); - - foreach (var (trigger, xform) in artifactQuery) + foreach (var (uid, trigger, xform) in _artifacts) { if (!instXform.Coordinates.TryDistance(EntityManager, xform.Coordinates, out var distance)) continue; @@ -34,7 +41,7 @@ public sealed class ArtifactMusicTriggerSystem : EntitySystem if (distance > trigger.Range) continue; - toActivate.Add(trigger.Owner); + toActivate.Add(uid); } } diff --git a/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactPressureTriggerSystem.cs b/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactPressureTriggerSystem.cs index aa1d40c5fb..cf730d8b49 100644 --- a/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactPressureTriggerSystem.cs +++ b/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactPressureTriggerSystem.cs @@ -17,10 +17,10 @@ public sealed class ArtifactPressureTriggerSystem : EntitySystem { base.Update(frameTime); - List toUpdate = new(); - foreach (var (trigger, artifact, transform) in EntityQuery()) + List> toUpdate = new(); + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var trigger, out var artifact, out var transform)) { - var uid = trigger.Owner; var environment = _atmosphereSystem.GetTileMixture(transform.GridUid, transform.MapUid, _transformSystem.GetGridOrMapTilePosition(uid, transform)); @@ -29,12 +29,12 @@ public sealed class ArtifactPressureTriggerSystem : EntitySystem var pressure = environment.Pressure; if (pressure >= trigger.MaxPressureThreshold || pressure <= trigger.MinPressureThreshold) - toUpdate.Add(artifact); + toUpdate.Add((uid, artifact)); } foreach (var a in toUpdate) { - _artifactSystem.TryActivateArtifact(a.Owner, null, a); + _artifactSystem.TryActivateArtifact(a, null, a); } } } diff --git a/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactTimerTriggerSystem.cs b/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactTimerTriggerSystem.cs index d8c500c3b1..c6ea745e1c 100644 --- a/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactTimerTriggerSystem.cs +++ b/Content.Server/Xenoarchaeology/XenoArtifacts/Triggers/Systems/ArtifactTimerTriggerSystem.cs @@ -24,20 +24,21 @@ public sealed class ArtifactTimerTriggerSystem : EntitySystem { base.Update(frameTime); - List toUpdate = new(); - foreach (var (trigger, artifact) in EntityQuery()) + List> toUpdate = new(); + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var trigger, out var artifact)) { var timeDif = _time.CurTime - trigger.LastActivation; if (timeDif <= trigger.ActivationRate) continue; - toUpdate.Add(artifact); + toUpdate.Add((uid, artifact)); trigger.LastActivation = _time.CurTime; } foreach (var a in toUpdate) { - _artifactSystem.TryActivateArtifact(a.Owner, null, a); + _artifactSystem.TryActivateArtifact(a, null, a); } } } diff --git a/Content.Shared/Access/Systems/SharedIdCardSystem.cs b/Content.Shared/Access/Systems/SharedIdCardSystem.cs index 3ef57827e5..842e7e7e6a 100644 --- a/Content.Shared/Access/Systems/SharedIdCardSystem.cs +++ b/Content.Shared/Access/Systems/SharedIdCardSystem.cs @@ -1,4 +1,3 @@ -using System.Diagnostics.CodeAnalysis; using Content.Shared.Access.Components; using Content.Shared.Hands.Components; using Content.Shared.Inventory; @@ -14,7 +13,7 @@ public abstract class SharedIdCardSystem : EntitySystem /// Attempt to find an ID card on an entity. This will look in the entity itself, in the entity's hands, and /// in the entity's inventory. /// - public bool TryFindIdCard(EntityUid uid, [NotNullWhen(true)] out IdCardComponent? idCard) + public bool TryFindIdCard(EntityUid uid, out Entity idCard) { // check held item? if (TryComp(uid, out HandsComponent? hands) && @@ -39,17 +38,22 @@ public abstract class SharedIdCardSystem : EntitySystem /// Attempt to get an id card component from an entity, either by getting it directly from the entity, or by /// getting the contained id from a . /// - public bool TryGetIdCard(EntityUid uid, [NotNullWhen(true)] out IdCardComponent? idCard) + public bool TryGetIdCard(EntityUid uid, out Entity idCard) { - if (TryComp(uid, out idCard)) + if (TryComp(uid, out IdCardComponent? idCardComp)) + { + idCard = (uid, idCardComp); return true; + } if (TryComp(uid, out PdaComponent? pda) - && TryComp(pda.ContainedId, out idCard)) + && TryComp(pda.ContainedId, out idCardComp)) { + idCard = (pda.ContainedId.Value, idCardComp); return true; } + idCard = default; return false; } } diff --git a/Content.Shared/Actions/ActionContainerSystem.cs b/Content.Shared/Actions/ActionContainerSystem.cs index bce0836efb..86d50e3989 100644 --- a/Content.Shared/Actions/ActionContainerSystem.cs +++ b/Content.Shared/Actions/ActionContainerSystem.cs @@ -60,7 +60,7 @@ public sealed class ActionContainerSystem : EntitySystem { action = null; - DebugTools.Assert(comp == null || comp.Owner == uid); + DebugTools.AssertOwner(uid, comp); comp ??= EnsureComp(uid); if (Exists(actionId)) @@ -162,7 +162,7 @@ public sealed class ActionContainerSystem : EntitySystem if (action.Container != null) RemoveAction(actionId, action); - DebugTools.Assert(comp == null || comp.Owner == uid); + DebugTools.AssertOwner(uid, comp); comp ??= EnsureComp(uid); if (!comp.Container.Insert(actionId)) { diff --git a/Content.Shared/Actions/SharedActionsSystem.cs b/Content.Shared/Actions/SharedActionsSystem.cs index 8d2c8c28e3..9ad155081a 100644 --- a/Content.Shared/Actions/SharedActionsSystem.cs +++ b/Content.Shared/Actions/SharedActionsSystem.cs @@ -96,7 +96,7 @@ public abstract class SharedActionsSystem : EntitySystem { if (result != null) { - DebugTools.Assert(result.Owner == uid); + DebugTools.AssertOwner(uid, result); return true; } @@ -494,7 +494,7 @@ public abstract class SharedActionsSystem : EntitySystem (TryComp(action.Container, out ActionsContainerComponent? containerComp) && containerComp.Container.Contains(actionId))); - DebugTools.Assert(comp == null || comp.Owner == performer); + DebugTools.AssertOwner(performer, comp); comp ??= EnsureComp(performer); action.AttachedEntity = performer; comp.Actions.Add(actionId); @@ -523,7 +523,7 @@ public abstract class SharedActionsSystem : EntitySystem if (!Resolve(container, ref containerComp)) return; - DebugTools.Assert(comp == null || comp.Owner == performer); + DebugTools.AssertOwner(performer, comp); comp ??= EnsureComp(performer); foreach (var actionId in actions) diff --git a/Content.Shared/Alert/AlertsSystem.cs b/Content.Shared/Alert/AlertsSystem.cs index db6911f12b..1a2d8a05bf 100644 --- a/Content.Shared/Alert/AlertsSystem.cs +++ b/Content.Shared/Alert/AlertsSystem.cs @@ -73,7 +73,7 @@ public abstract class AlertsSystem : EntitySystem /// be erased if there is currently a cooldown for the alert) public void ShowAlert(EntityUid euid, AlertType alertType, short? severity = null, (TimeSpan, TimeSpan)? cooldown = null) { - if (!EntityManager.TryGetComponent(euid, out AlertsComponent? alertsComponent)) + if (!TryComp(euid, out AlertsComponent? alertsComponent)) return; if (TryGet(alertType, out var alert)) @@ -94,9 +94,9 @@ public abstract class AlertsSystem : EntitySystem alertsComponent.Alerts[alert.AlertKey] = new AlertState { Cooldown = cooldown, Severity = severity, Type = alertType }; - AfterShowAlert(alertsComponent); + AfterShowAlert((euid, alertsComponent)); - Dirty(alertsComponent); + Dirty(euid, alertsComponent); } else { @@ -111,7 +111,7 @@ public abstract class AlertsSystem : EntitySystem /// public void ClearAlertCategory(EntityUid euid, AlertCategory category) { - if(!EntityManager.TryGetComponent(euid, out AlertsComponent? alertsComponent)) + if(!TryComp(euid, out AlertsComponent? alertsComponent)) return; var key = AlertKey.ForCategory(category); @@ -120,9 +120,9 @@ public abstract class AlertsSystem : EntitySystem return; } - AfterClearAlert(alertsComponent); + AfterClearAlert((euid, alertsComponent)); - Dirty(alertsComponent); + Dirty(euid, alertsComponent); } /// @@ -140,9 +140,9 @@ public abstract class AlertsSystem : EntitySystem return; } - AfterClearAlert(alertsComponent); + AfterClearAlert((euid, alertsComponent)); - Dirty(alertsComponent); + Dirty(euid, alertsComponent); } else { @@ -153,14 +153,12 @@ public abstract class AlertsSystem : EntitySystem /// /// Invoked after showing an alert prior to dirtying the component /// - /// - protected virtual void AfterShowAlert(AlertsComponent alertsComponent) { } + protected virtual void AfterShowAlert(Entity alerts) { } /// /// Invoked after clearing an alert prior to dirtying the component /// - /// - protected virtual void AfterClearAlert(AlertsComponent alertsComponent) { } + protected virtual void AfterClearAlert(Entity alerts) { } public override void Initialize() { diff --git a/Content.Shared/Buckle/SharedBuckleSystem.Buckle.cs b/Content.Shared/Buckle/SharedBuckleSystem.Buckle.cs index 020b47f708..6add066133 100644 --- a/Content.Shared/Buckle/SharedBuckleSystem.Buckle.cs +++ b/Content.Shared/Buckle/SharedBuckleSystem.Buckle.cs @@ -457,7 +457,7 @@ public abstract partial class SharedBuckleSystem if (buckleXform.ParentUid == strapUid && !Terminating(buckleXform.ParentUid)) { - _container.AttachParentToContainerOrGrid(buckleXform); + _container.AttachParentToContainerOrGrid((buckleUid, buckleXform)); var oldBuckledToWorldRot = _transform.GetWorldRotation(strapUid); _transform.SetWorldRotation(buckleXform, oldBuckledToWorldRot); diff --git a/Content.Shared/Chemistry/MetabolismMovespeedModifierSystem.cs b/Content.Shared/Chemistry/MetabolismMovespeedModifierSystem.cs index 6b7c75514f..e9d3b7de53 100644 --- a/Content.Shared/Chemistry/MetabolismMovespeedModifierSystem.cs +++ b/Content.Shared/Chemistry/MetabolismMovespeedModifierSystem.cs @@ -10,7 +10,7 @@ namespace Content.Shared.Chemistry [Dependency] private readonly IGameTiming _gameTiming = default!; [Dependency] private readonly MovementSpeedModifierSystem _movespeed = default!; - private readonly List _components = new(); + private readonly List> _components = new(); public override void Initialize() { @@ -27,9 +27,9 @@ namespace Content.Shared.Chemistry args.ModifySpeed(component.WalkSpeedModifier, component.SprintSpeedModifier); } - private void AddComponent(EntityUid uid, MovespeedModifierMetabolismComponent component, ComponentStartup args) + private void AddComponent(Entity metabolism, ref ComponentStartup args) { - _components.Add(component); + _components.Add(metabolism); } public override void Update(float frameTime) @@ -40,20 +40,21 @@ namespace Content.Shared.Chemistry for (var i = _components.Count - 1; i >= 0; i--) { - var component = _components[i]; + var metabolism = _components[i]; - if (component.Deleted) + if (metabolism.Comp.Deleted) { _components.RemoveAt(i); continue; } - if (component.ModifierTimer > currentTime) continue; + if (metabolism.Comp.ModifierTimer > currentTime) + continue; _components.RemoveAt(i); - EntityManager.RemoveComponent(component.Owner); + EntityManager.RemoveComponent(metabolism); - _movespeed.RefreshMovementSpeedModifiers(component.Owner); + _movespeed.RefreshMovementSpeedModifiers(metabolism); } } } diff --git a/Content.Shared/Containers/ItemSlot/ItemSlotsSystem.cs b/Content.Shared/Containers/ItemSlot/ItemSlotsSystem.cs index cb92892305..902b56427a 100644 --- a/Content.Shared/Containers/ItemSlot/ItemSlotsSystem.cs +++ b/Content.Shared/Containers/ItemSlot/ItemSlotsSystem.cs @@ -88,7 +88,7 @@ namespace Content.Shared.Containers.ItemSlots public void AddItemSlot(EntityUid uid, string id, ItemSlot slot, ItemSlotsComponent? itemSlots = null) { itemSlots ??= EntityManager.EnsureComponent(uid); - DebugTools.Assert(itemSlots.Owner == uid); + DebugTools.AssertOwner(uid, itemSlots); if (itemSlots.Slots.TryGetValue(id, out var existing)) { diff --git a/Content.Shared/Coordinates/EntityCoordinatesExtensions.cs b/Content.Shared/Coordinates/EntityCoordinatesExtensions.cs index f660ee5eb0..2aadbf8a81 100644 --- a/Content.Shared/Coordinates/EntityCoordinatesExtensions.cs +++ b/Content.Shared/Coordinates/EntityCoordinatesExtensions.cs @@ -21,11 +21,6 @@ namespace Content.Shared.Coordinates return new EntityCoordinates(id, x, y); } - public static EntityCoordinates ToCoordinates(this MapGridComponent grid, Vector2 offset) - { - return ToCoordinates(grid.Owner, offset); - } - public static EntityCoordinates ToCoordinates(this MapGridComponent grid, float x, float y) { return ToCoordinates(grid.Owner, x, y); diff --git a/Content.Shared/Doors/Systems/SharedDoorSystem.cs b/Content.Shared/Doors/Systems/SharedDoorSystem.cs index 4a241ba376..084c3b4ea2 100644 --- a/Content.Shared/Doors/Systems/SharedDoorSystem.cs +++ b/Content.Shared/Doors/Systems/SharedDoorSystem.cs @@ -2,24 +2,22 @@ using System.Linq; using Content.Shared.Access.Components; using Content.Shared.Access.Systems; using Content.Shared.Damage; -using Content.Shared.DoAfter; using Content.Shared.Doors.Components; using Content.Shared.Hands.Components; using Content.Shared.Interaction; using Content.Shared.Physics; +using Content.Shared.Prying.Components; using Content.Shared.Stunnable; using Content.Shared.Tag; using Robust.Shared.Audio; using Robust.Shared.Physics.Components; using Robust.Shared.Physics.Events; using Robust.Shared.Physics.Systems; -using Robust.Shared.Serialization; using Robust.Shared.Timing; -using Content.Shared.Prying.Components; namespace Content.Shared.Doors.Systems; -public abstract partial class SharedDoorSystem : EntitySystem +public abstract class SharedDoorSystem : EntitySystem { [Dependency] protected readonly IGameTiming GameTiming = default!; [Dependency] protected readonly SharedPhysicsSystem PhysicsSystem = default!; @@ -45,7 +43,7 @@ public abstract partial class SharedDoorSystem : EntitySystem /// /// A set of doors that are currently opening, closing, or just queued to open/close after some delay. /// - private readonly HashSet _activeDoors = new(); + private readonly HashSet> _activeDoors = new(); public override void Initialize() { @@ -64,10 +62,11 @@ public abstract partial class SharedDoorSystem : EntitySystem } - protected virtual void OnComponentInit(EntityUid uid, DoorComponent door, ComponentInit args) + protected virtual void OnComponentInit(Entity ent, ref ComponentInit args) { + var door = ent.Comp; if (door.NextStateChange != null) - _activeDoors.Add(door); + _activeDoors.Add(ent); else { // Make sure doors are not perpetually stuck opening or closing. @@ -90,25 +89,26 @@ public abstract partial class SharedDoorSystem : EntitySystem || door.State == DoorState.Closing && door.Partial || door.State == DoorState.Opening && !door.Partial; - SetCollidable(uid, collidable, door); - AppearanceSystem.SetData(uid, DoorVisuals.State, door.State); + SetCollidable(ent, collidable, door); + AppearanceSystem.SetData(ent, DoorVisuals.State, door.State); } - private void OnRemove(EntityUid uid, DoorComponent door, ComponentRemove args) + private void OnRemove(Entity door, ref ComponentRemove args) { _activeDoors.Remove(door); } #region StateManagement - private void OnHandleState(EntityUid uid, DoorComponent door, ref AfterAutoHandleStateEvent args) + private void OnHandleState(Entity ent, ref AfterAutoHandleStateEvent args) { + var door = ent.Comp; if (door.NextStateChange == null) - _activeDoors.Remove(door); + _activeDoors.Remove(ent); else - _activeDoors.Add(door); + _activeDoors.Add(ent); - RaiseLocalEvent(uid, new DoorStateChangedEvent(door.State)); - AppearanceSystem.SetData(uid, DoorVisuals.State, door.State); + RaiseLocalEvent(ent, new DoorStateChangedEvent(door.State)); + AppearanceSystem.SetData(ent, DoorVisuals.State, door.State); } protected void SetState(EntityUid uid, DoorState state, DoorComponent? door = null) @@ -123,29 +123,29 @@ public abstract partial class SharedDoorSystem : EntitySystem switch (state) { case DoorState.Opening: - _activeDoors.Add(door); + _activeDoors.Add((uid, door)); door.NextStateChange = GameTiming.CurTime + door.OpenTimeOne; break; case DoorState.Closing: - _activeDoors.Add(door); + _activeDoors.Add((uid, door)); door.NextStateChange = GameTiming.CurTime + door.CloseTimeOne; break; case DoorState.Denying: - _activeDoors.Add(door); + _activeDoors.Add((uid, door)); door.NextStateChange = GameTiming.CurTime + door.DenyDuration; break; case DoorState.Emagging: - _activeDoors.Add(door); + _activeDoors.Add((uid, door)); door.NextStateChange = GameTiming.CurTime + door.EmagDuration; break; case DoorState.Open: door.Partial = false; if (door.NextStateChange == null) - _activeDoors.Remove(door); + _activeDoors.Remove((uid, door)); break; case DoorState.Closed: // May want to keep the door around to re-check for opening if we got a contact during closing. @@ -154,8 +154,8 @@ public abstract partial class SharedDoorSystem : EntitySystem } door.State = state; - Dirty(door); - RaiseLocalEvent(uid, new DoorStateChangedEvent(state), false); + Dirty(uid, door); + RaiseLocalEvent(uid, new DoorStateChangedEvent(state)); AppearanceSystem.SetData(uid, DoorVisuals.State, door.State); } @@ -187,7 +187,7 @@ public abstract partial class SharedDoorSystem : EntitySystem // might not be able to deny without power or some other blocker. var ev = new BeforeDoorDeniedEvent(); - RaiseLocalEvent(uid, ev, false); + RaiseLocalEvent(uid, ev); if (ev.Cancelled) return; @@ -239,7 +239,7 @@ public abstract partial class SharedDoorSystem : EntitySystem return false; var ev = new BeforeDoorOpenedEvent() { User = user }; - RaiseLocalEvent(uid, ev, false); + RaiseLocalEvent(uid, ev); if (ev.Cancelled) return false; @@ -290,8 +290,8 @@ public abstract partial class SharedDoorSystem : EntitySystem SetCollidable(uid, false, door); door.Partial = true; door.NextStateChange = GameTiming.CurTime + door.CloseTimeTwo; - _activeDoors.Add(door); - Dirty(door); + _activeDoors.Add((uid, door)); + Dirty(uid, door); } #endregion @@ -359,7 +359,7 @@ public abstract partial class SharedDoorSystem : EntitySystem return false; door.Partial = true; - Dirty(door); + Dirty(uid, door); // Make sure no entity waled into the airlock when it started closing. if (!CanClose(uid, door)) @@ -372,7 +372,7 @@ public abstract partial class SharedDoorSystem : EntitySystem SetCollidable(uid, true, door, physics); door.NextStateChange = GameTiming.CurTime + door.CloseTimeTwo; - _activeDoors.Add(door); + _activeDoors.Add((uid, door)); // Crush any entities. Note that we don't check airlock safety here. This should have been checked before // the door closed. @@ -567,12 +567,12 @@ public abstract partial class SharedDoorSystem : EntitySystem if (delay == null || delay.Value <= TimeSpan.Zero) { door.NextStateChange = null; - _activeDoors.Remove(door); + _activeDoors.Remove((uid, door)); return; } door.NextStateChange = GameTiming.CurTime + delay.Value; - _activeDoors.Add(door); + _activeDoors.Add((uid, door)); } /// @@ -582,76 +582,78 @@ public abstract partial class SharedDoorSystem : EntitySystem { var time = GameTiming.CurTime; - foreach (var door in _activeDoors.ToList()) + foreach (var ent in _activeDoors.ToList()) { + var door = ent.Comp; if (door.Deleted || door.NextStateChange == null) { - _activeDoors.Remove(door); + _activeDoors.Remove(ent); continue; } - if (Paused(door.Owner)) + if (Paused(ent)) continue; if (door.NextStateChange.Value < time) - NextState(door, time); + NextState(ent, time); if (door.State == DoorState.Closed && - TryComp(door.Owner, out var doorBody)) + TryComp(ent, out var doorBody)) { // If something bumped into us during closing then start to re-open, otherwise, remove it from active. - _activeDoors.Remove(door); - CheckDoorBump(door, doorBody); + _activeDoors.Remove(ent); + CheckDoorBump((ent, door, doorBody)); } } } - protected virtual void CheckDoorBump(DoorComponent component, PhysicsComponent body) { } + protected virtual void CheckDoorBump(Entity ent) { } /// /// Makes a door proceed to the next state (if applicable). /// - private void NextState(DoorComponent door, TimeSpan time) + private void NextState(Entity ent, TimeSpan time) { + var door = ent.Comp; door.NextStateChange = null; if (door.CurrentlyCrushing.Count > 0) // This is a closed door that is crushing people and needs to auto-open. Note that we don't check "can open" // here. The door never actually finished closing and we don't want people to get stuck inside of doors. - StartOpening(door.Owner, door, predicted: true); + StartOpening(ent, door, predicted: true); switch (door.State) { case DoorState.Opening: // Either fully or partially open this door. if (door.Partial) - SetState(door.Owner, DoorState.Open, door); + SetState(ent, DoorState.Open, door); else - OnPartialOpen(door.Owner, door); + OnPartialOpen(ent, door); break; case DoorState.Closing: // Either fully or partially close this door. if (door.Partial) - SetState(door.Owner, DoorState.Closed, door); + SetState(ent, DoorState.Closed, door); else - OnPartialClose(door.Owner, door); + OnPartialClose(ent, door); break; case DoorState.Denying: // Finish denying entry and return to the closed state. - SetState(door.Owner, DoorState.Closed, door); + SetState(ent, DoorState.Closed, door); break; case DoorState.Emagging: - StartOpening(door.Owner, door); + StartOpening(ent, door); break; case DoorState.Open: // This door is open, and queued for an auto-close. - if (!TryClose(door.Owner, door, predicted: true)) + if (!TryClose(ent, door, predicted: true)) { // The door failed to close (blocked?). Try again in one second. door.NextStateChange = time + TimeSpan.FromSeconds(1); @@ -660,7 +662,7 @@ public abstract partial class SharedDoorSystem : EntitySystem case DoorState.Welded: // A welded door? This should never have been active in the first place. - Log.Error($"Welded door was in the list of active doors. Door: {ToPrettyString(door.Owner)}"); + Log.Error($"Welded door was in the list of active doors. Door: {ToPrettyString(ent)}"); break; } } diff --git a/Content.Shared/Examine/ExamineSystemShared.cs b/Content.Shared/Examine/ExamineSystemShared.cs index 2e0cffd7d2..1e6f121aae 100644 --- a/Content.Shared/Examine/ExamineSystemShared.cs +++ b/Content.Shared/Examine/ExamineSystemShared.cs @@ -1,14 +1,11 @@ using System.Linq; -using Content.Shared.DragDrop; -using Content.Shared.Interaction; -using Content.Shared.Eye.Blinding; using Content.Shared.Eye.Blinding.Components; +using Content.Shared.Interaction; using Content.Shared.Mobs.Components; using Content.Shared.Mobs.Systems; using JetBrains.Annotations; using Robust.Shared.Containers; using Robust.Shared.Map; -using Robust.Shared.Network; using Robust.Shared.Physics; using Robust.Shared.Utility; using static Content.Shared.Interaction.SharedInteractionSystem; @@ -191,7 +188,7 @@ namespace Content.Shared.Examine } var bBox = o.BoundingBox; - bBox = bBox.Translated(entMan.GetComponent(o.Owner).WorldPosition); + bBox = bBox.Translated(entMan.GetComponent(result.HitEntity).WorldPosition); if (bBox.Contains(origin.Position) || bBox.Contains(other.Position)) { @@ -213,15 +210,6 @@ namespace Content.Shared.Examine return InRangeUnOccluded(originPos, otherPos, range, predicate, ignoreInsideBlocker); } - public static bool InRangeUnOccluded(EntityUid origin, IComponent other, float range = ExamineRange, Ignored? predicate = null, bool ignoreInsideBlocker = true) - { - var entMan = IoCManager.Resolve(); - var originPos = entMan.GetComponent(origin).MapPosition; - var otherPos = entMan.GetComponent(other.Owner).MapPosition; - - return InRangeUnOccluded(originPos, otherPos, range, predicate, ignoreInsideBlocker); - } - public static bool InRangeUnOccluded(EntityUid origin, EntityCoordinates other, float range = ExamineRange, Ignored? predicate = null, bool ignoreInsideBlocker = true) { var entMan = IoCManager.Resolve(); diff --git a/Content.Shared/Follower/FollowerSystem.cs b/Content.Shared/Follower/FollowerSystem.cs index e4a0488dfb..58a94d1723 100644 --- a/Content.Shared/Follower/FollowerSystem.cs +++ b/Content.Shared/Follower/FollowerSystem.cs @@ -151,7 +151,7 @@ public sealed class FollowerSystem : EntitySystem { followerComp = AddComp(follower); } - + followerComp.Following = entity; var followedComp = EnsureComp(entity); @@ -165,7 +165,7 @@ public sealed class FollowerSystem : EntitySystem _physicsSystem.SetLinearVelocity(follower, Vector2.Zero); var xform = Transform(follower); - _containerSystem.AttachParentToContainerOrGrid(xform); + _containerSystem.AttachParentToContainerOrGrid((follower, xform)); // If we didn't get to parent's container. if (xform.ParentUid != Transform(xform.ParentUid).ParentUid) diff --git a/Content.Shared/Friction/TileFrictionController.cs b/Content.Shared/Friction/TileFrictionController.cs index c0af2f4ed4..472f5b574b 100644 --- a/Content.Shared/Friction/TileFrictionController.cs +++ b/Content.Shared/Friction/TileFrictionController.cs @@ -6,16 +6,12 @@ using Content.Shared.Movement.Systems; using Content.Shared.Pulling.Components; using JetBrains.Annotations; using Robust.Shared.Configuration; -using Robust.Shared.GameStates; using Robust.Shared.Map; using Robust.Shared.Map.Components; using Robust.Shared.Physics.Components; using Robust.Shared.Physics.Controllers; using Robust.Shared.Physics.Dynamics; using Robust.Shared.Physics.Systems; -using Robust.Shared.Serialization; -using Robust.Shared.Utility; - namespace Content.Shared.Friction { @@ -68,7 +64,7 @@ namespace Content.Shared.Friction // Only apply friction when it's not a mob (or the mob doesn't have control) if (prediction && !body.Predict || body.BodyStatus == BodyStatus.InAir || - _mover.UseMobMovement(body.Owner)) + _mover.UseMobMovement(uid)) { continue; } @@ -78,7 +74,7 @@ namespace Content.Shared.Friction if (!xformQuery.TryGetComponent(uid, out var xform)) { - Log.Error($"Unable to get transform for {ToPrettyString(body.Owner)} in tilefrictioncontroller"); + Log.Error($"Unable to get transform for {ToPrettyString(uid)} in tilefrictioncontroller"); continue; } diff --git a/Content.Shared/Gravity/SharedFloatingVisualizerSystem.cs b/Content.Shared/Gravity/SharedFloatingVisualizerSystem.cs index 0f06d72192..57136116ca 100644 --- a/Content.Shared/Gravity/SharedFloatingVisualizerSystem.cs +++ b/Content.Shared/Gravity/SharedFloatingVisualizerSystem.cs @@ -45,7 +45,8 @@ public abstract class SharedFloatingVisualizerSystem : EntitySystem private void OnGravityChanged(ref GravityChangedEvent args) { - foreach (var (floating, transform) in EntityQuery(true)) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var floating, out var transform)) { if (transform.MapID == MapId.Nullspace) continue; @@ -54,9 +55,8 @@ public abstract class SharedFloatingVisualizerSystem : EntitySystem continue; floating.CanFloat = !args.HasGravity; - Dirty(floating); + Dirty(uid, floating); - var uid = floating.Owner; if (!args.HasGravity) FloatAnimation(uid, floating.Offset, floating.AnimationKey, floating.AnimationTime); } diff --git a/Content.Shared/Hands/EntitySystems/SharedHandsSystem.Pickup.cs b/Content.Shared/Hands/EntitySystems/SharedHandsSystem.Pickup.cs index 0171b9f70c..edba1f98c4 100644 --- a/Content.Shared/Hands/EntitySystems/SharedHandsSystem.Pickup.cs +++ b/Content.Shared/Hands/EntitySystems/SharedHandsSystem.Pickup.cs @@ -1,4 +1,3 @@ -using System.Numerics; using Content.Shared.Database; using Content.Shared.Hands.Components; using Content.Shared.Item; @@ -202,7 +201,7 @@ public abstract partial class SharedHandsSystem : EntitySystem { // TODO make this check upwards for any container, and parent to that. // Currently this just checks the direct parent, so items can still teleport through containers. - ContainerSystem.AttachParentToContainerOrGrid(Transform(entity)); + ContainerSystem.AttachParentToContainerOrGrid((entity, Transform(entity))); } } diff --git a/Content.Shared/Hands/EntitySystems/SharedHandsSystem.cs b/Content.Shared/Hands/EntitySystems/SharedHandsSystem.cs index 9f7623329e..e1de636969 100644 --- a/Content.Shared/Hands/EntitySystems/SharedHandsSystem.cs +++ b/Content.Shared/Hands/EntitySystems/SharedHandsSystem.cs @@ -21,7 +21,7 @@ public abstract partial class SharedHandsSystem [Dependency] private readonly SharedStorageSystem _storage = default!; [Dependency] protected readonly SharedTransformSystem TransformSystem = default!; - protected event Action? OnHandSetActive; + protected event Action?>? OnHandSetActive; public override void Initialize() { @@ -216,7 +216,7 @@ public abstract partial class SharedHandsSystem } handComp.ActiveHand = hand; - OnHandSetActive?.Invoke(handComp); + OnHandSetActive?.Invoke((uid, handComp)); if (hand.HeldEntity != null) RaiseLocalEvent(hand.HeldEntity.Value, new HandSelectedEvent(uid)); diff --git a/Content.Shared/Hands/SharedHandVirtualItemSystem.cs b/Content.Shared/Hands/SharedHandVirtualItemSystem.cs index 7fb4a4c127..2e426020ca 100644 --- a/Content.Shared/Hands/SharedHandVirtualItemSystem.cs +++ b/Content.Shared/Hands/SharedHandVirtualItemSystem.cs @@ -58,7 +58,7 @@ public abstract class SharedHandVirtualItemSystem : EntitySystem { if (TryComp(hand.HeldEntity, out HandVirtualItemComponent? virt) && virt.BlockingEntity == matching) { - Delete(virt, user); + Delete((hand.HeldEntity.Value, virt), user); } } } @@ -80,16 +80,16 @@ public abstract class SharedHandVirtualItemSystem : EntitySystem /// /// Queues a deletion for a virtual item and notifies the blocking entity and user. /// - public void Delete(HandVirtualItemComponent comp, EntityUid user) + public void Delete(Entity item, EntityUid user) { if (_net.IsClient) return; - var userEv = new VirtualItemDeletedEvent(comp.BlockingEntity, user); + var userEv = new VirtualItemDeletedEvent(item.Comp.BlockingEntity, user); RaiseLocalEvent(user, userEv); - var targEv = new VirtualItemDeletedEvent(comp.BlockingEntity, user); - RaiseLocalEvent(comp.BlockingEntity, targEv); + var targEv = new VirtualItemDeletedEvent(item.Comp.BlockingEntity, user); + RaiseLocalEvent(item.Comp.BlockingEntity, targEv); - QueueDel(comp.Owner); + QueueDel(item); } } diff --git a/Content.Shared/Lathe/SharedLatheSystem.cs b/Content.Shared/Lathe/SharedLatheSystem.cs index e9482d24d1..9debaa7719 100644 --- a/Content.Shared/Lathe/SharedLatheSystem.cs +++ b/Content.Shared/Lathe/SharedLatheSystem.cs @@ -38,7 +38,7 @@ public abstract class SharedLatheSystem : EntitySystem { var adjustedAmount = AdjustMaterial(needed, recipe.ApplyMaterialDiscount, component.MaterialUseMultiplier); - if (_materialStorage.GetMaterialAmount(component.Owner, material) < adjustedAmount * amount) + if (_materialStorage.GetMaterialAmount(uid, material) < adjustedAmount * amount) return false; } return true; diff --git a/Content.Shared/Light/SharedHandheldLightSystem.cs b/Content.Shared/Light/SharedHandheldLightSystem.cs index ad209c95f8..d530b07b18 100644 --- a/Content.Shared/Light/SharedHandheldLightSystem.cs +++ b/Content.Shared/Light/SharedHandheldLightSystem.cs @@ -52,10 +52,10 @@ public abstract class SharedHandheldLightSystem : EntitySystem if (makeNoise) { var sound = component.Activated ? component.TurnOnSound : component.TurnOffSound; - _audio.PlayPvs(sound, component.Owner); + _audio.PlayPvs(sound, uid); } - Dirty(component); + Dirty(uid, component); UpdateVisuals(uid, component); } diff --git a/Content.Shared/Maps/TurfHelpers.cs b/Content.Shared/Maps/TurfHelpers.cs index 6b9d7dbbf9..857244d658 100644 --- a/Content.Shared/Maps/TurfHelpers.cs +++ b/Content.Shared/Maps/TurfHelpers.cs @@ -1,11 +1,8 @@ +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; -using System.Diagnostics.CodeAnalysis; -using Content.Shared.Decals; using Content.Shared.Physics; using Robust.Shared.Map; -using Robust.Shared.Physics; -using Robust.Shared.Physics.Components; using Robust.Shared.Random; namespace Content.Shared.Maps @@ -175,7 +172,7 @@ namespace Content.Shared.Maps if (map.TryGetGrid(turf.GridUid, out var tileGrid)) { - var gridRot = entManager.GetComponent(tileGrid.Owner).WorldRotation; + var gridRot = entManager.GetComponent(turf.GridUid).WorldRotation; // This is scaled to 90 % so it doesn't encompass walls on other tiles. var tileBox = Box2.UnitCentered.Scale(0.9f); diff --git a/Content.Shared/Mobs/Systems/MobStateSystem.StateMachine.cs b/Content.Shared/Mobs/Systems/MobStateSystem.StateMachine.cs index b07087cafa..25b63d5b80 100644 --- a/Content.Shared/Mobs/Systems/MobStateSystem.StateMachine.cs +++ b/Content.Shared/Mobs/Systems/MobStateSystem.StateMachine.cs @@ -111,8 +111,8 @@ public partial class MobStateSystem OnStateChanged(target, component, oldState, newState); RaiseLocalEvent(target, ev, true); _adminLogger.Add(LogType.Damaged, oldState == MobState.Alive ? LogImpact.Low : LogImpact.Medium, - $"{ToPrettyString(component.Owner):user} state changed from {oldState} to {newState}"); - Dirty(component); + $"{ToPrettyString(target):user} state changed from {oldState} to {newState}"); + Dirty(target, component); } #endregion diff --git a/Content.Shared/Physics/Controllers/SharedConveyorController.cs b/Content.Shared/Physics/Controllers/SharedConveyorController.cs index 8ec6ddbefe..ec17df7a24 100644 --- a/Content.Shared/Physics/Controllers/SharedConveyorController.cs +++ b/Content.Shared/Physics/Controllers/SharedConveyorController.cs @@ -152,7 +152,7 @@ public abstract class SharedConveyorController : VirtualController foreach (var entity in comp.Intersecting) { - if (!xformQuery.TryGetComponent(entity, out var entityXform) || entityXform.ParentUid != grid.Owner) + if (!xformQuery.TryGetComponent(entity, out var entityXform) || entityXform.ParentUid != xform.GridUid!.Value) continue; if (!bodyQuery.TryGetComponent(entity, out var physics) || physics.BodyType == BodyType.Static || physics.BodyStatus == BodyStatus.InAir || _gravity.IsWeightless(entity, physics, entityXform)) diff --git a/Content.Shared/Random/RulesSystem.cs b/Content.Shared/Random/RulesSystem.cs index 8e9ccadc71..f8711fb63e 100644 --- a/Content.Shared/Random/RulesSystem.cs +++ b/Content.Shared/Random/RulesSystem.cs @@ -17,6 +17,7 @@ public sealed class RulesSystem : EntitySystem public bool IsTrue(EntityUid uid, RulesPrototype rules) { + var inRange = new HashSet>(); foreach (var rule in rules.Rules) { switch (rule) @@ -72,12 +73,13 @@ public sealed class RulesSystem : EntitySystem var count = 0; // TODO: Update this when we get the callback version - foreach (var comp in _lookup.GetComponentsInRange(xform.MapID, - worldPos, access.Range)) + var entities = new HashSet>(); + _lookup.GetEntitiesInRange(xform.MapID, worldPos, access.Range, entities); + foreach (var comp in entities) { if (!_reader.AreAccessTagsAllowed(access.Access, comp) || access.Anchored && - (!xformQuery.TryGetComponent(comp.Owner, out var compXform) || + (!xformQuery.TryGetComponent(comp, out var compXform) || !compXform.Anchored)) { continue; @@ -113,12 +115,12 @@ public sealed class RulesSystem : EntitySystem foreach (var compType in nearbyComps.Components.Values) { - // TODO: Update this when we get the callback version - foreach (var comp in _lookup.GetComponentsInRange(compType.Component.GetType(), xform.MapID, - worldPos, nearbyComps.Range)) + inRange.Clear(); + _lookup.GetEntitiesInRange(compType.Component.GetType(), xform.MapID, worldPos, nearbyComps.Range, inRange); + foreach (var comp in inRange) { if (nearbyComps.Anchored && - (!xformQuery.TryGetComponent(comp.Owner, out var compXform) || + (!xformQuery.TryGetComponent(comp, out var compXform) || !compXform.Anchored)) { continue; diff --git a/Content.Shared/Revenant/EntitySystems/SharedRevenantOverloadedLightsSystem.cs b/Content.Shared/Revenant/EntitySystems/SharedRevenantOverloadedLightsSystem.cs index 40e6a53a00..7fa2ef51e8 100644 --- a/Content.Shared/Revenant/EntitySystems/SharedRevenantOverloadedLightsSystem.cs +++ b/Content.Shared/Revenant/EntitySystems/SharedRevenantOverloadedLightsSystem.cs @@ -20,10 +20,10 @@ public abstract class SharedRevenantOverloadedLightsSystem : EntitySystem if (comp.Accumulator < comp.ZapDelay) continue; - OnZap(comp); + OnZap((uid, comp)); RemCompDeferred(uid, comp); } } - protected abstract void OnZap(RevenantOverloadedLightsComponent component); + protected abstract void OnZap(Entity component); } diff --git a/Content.Shared/Singularity/Components/ContainmentFieldGeneratorComponent.cs b/Content.Shared/Singularity/Components/ContainmentFieldGeneratorComponent.cs index d9fc044dce..c704c8bf77 100644 --- a/Content.Shared/Singularity/Components/ContainmentFieldGeneratorComponent.cs +++ b/Content.Shared/Singularity/Components/ContainmentFieldGeneratorComponent.cs @@ -92,7 +92,7 @@ public sealed partial class ContainmentFieldGeneratorComponent : Component /// Stores a list of fields connected between generators in this direction. /// [ViewVariables] - public Dictionary)> Connections = new(); + public Dictionary, List)> Connections = new(); /// /// What fields should this spawn? diff --git a/Content.Shared/Singularity/EntitySystems/SharedSingularitySystem.cs b/Content.Shared/Singularity/EntitySystems/SharedSingularitySystem.cs index 2ea40308b9..acac1dfd84 100644 --- a/Content.Shared/Singularity/EntitySystems/SharedSingularitySystem.cs +++ b/Content.Shared/Singularity/EntitySystems/SharedSingularitySystem.cs @@ -1,13 +1,12 @@ using System.Numerics; +using Content.Shared.Radiation.Components; +using Content.Shared.Singularity.Components; +using Content.Shared.Singularity.Events; using Robust.Shared.Containers; using Robust.Shared.Physics.Components; using Robust.Shared.Physics.Systems; using Robust.Shared.Serialization; -using Content.Shared.Radiation.Components; -using Content.Shared.Singularity.Components; -using Content.Shared.Singularity.Events; - namespace Content.Shared.Singularity.EntitySystems; /// @@ -89,8 +88,8 @@ public abstract class SharedSingularitySystem : EntitySystem singularity.Level = value; UpdateSingularityLevel(uid, oldValue, singularity); - if(!EntityManager.Deleted(singularity.Owner)) - EntityManager.Dirty(singularity); + if (!Deleted(uid)) + Dirty(uid, singularity); } /// diff --git a/Content.Shared/Stacks/SharedStackSystem.cs b/Content.Shared/Stacks/SharedStackSystem.cs index 99e3f7c6de..d70dfc52f9 100644 --- a/Content.Shared/Stacks/SharedStackSystem.cs +++ b/Content.Shared/Stacks/SharedStackSystem.cs @@ -1,6 +1,5 @@ using System.Numerics; using Content.Shared.Examine; -using Content.Shared.Hands; using Content.Shared.Hands.Components; using Content.Shared.Hands.EntitySystems; using Content.Shared.Interaction; @@ -217,8 +216,8 @@ namespace Content.Shared.Stacks var map = xform.MapID; var bounds = _physics.GetWorldAABB(uid); - var intersecting = _entityLookup.GetComponentsIntersecting(map, bounds, - LookupFlags.Dynamic | LookupFlags.Sundries); + var intersecting = new HashSet>(); + _entityLookup.GetEntitiesIntersecting(map, bounds, intersecting, LookupFlags.Dynamic | LookupFlags.Sundries); var merged = false; foreach (var otherStack in intersecting) diff --git a/Content.Shared/StatusEffect/StatusEffectsSystem.cs b/Content.Shared/StatusEffect/StatusEffectsSystem.cs index 17b8864493..6aec3a8b3b 100644 --- a/Content.Shared/StatusEffect/StatusEffectsSystem.cs +++ b/Content.Shared/StatusEffect/StatusEffectsSystem.cs @@ -33,14 +33,14 @@ namespace Content.Shared.StatusEffect var curTime = _gameTiming.CurTime; var enumerator = EntityQueryEnumerator(); - while (enumerator.MoveNext(out _, out var status)) + while (enumerator.MoveNext(out var uid, out _, out var status)) { foreach (var state in status.ActiveEffects.ToArray()) { // if we're past the end point of the effect if (curTime > state.Value.Cooldown.Item2) { - TryRemoveStatusEffect(status.Owner, state.Key, status); + TryRemoveStatusEffect(uid, state.Key, status); } } } @@ -134,10 +134,7 @@ namespace Content.Shared.StatusEffect // If they already have the comp, we just won't bother updating anything. if (!EntityManager.HasComponent(uid, _componentFactory.GetRegistration(component).Type)) { - // Fuck this shit I hate it var newComponent = (Component) _componentFactory.GetComponent(component); - newComponent.Owner = uid; - EntityManager.AddComponent(uid, newComponent); status.ActiveEffects[key].RelevantComponent = component; } diff --git a/Content.Shared/Storage/EntitySystems/DumpableSystem.cs b/Content.Shared/Storage/EntitySystems/DumpableSystem.cs index cb53ea8298..ad86a52665 100644 --- a/Content.Shared/Storage/EntitySystems/DumpableSystem.cs +++ b/Content.Shared/Storage/EntitySystems/DumpableSystem.cs @@ -133,7 +133,7 @@ public sealed class DumpableSystem : EntitySystem foreach (var entity in dumpQueue) { var transform = Transform(entity); - _container.AttachParentToContainerOrGrid(transform); + _container.AttachParentToContainerOrGrid((entity, transform)); _transformSystem.SetLocalPositionRotation(transform, transform.LocalPosition + _random.NextVector2Box() / 2, _random.NextAngle()); } diff --git a/Content.Shared/Strip/SharedStrippableSystem.cs b/Content.Shared/Strip/SharedStrippableSystem.cs index 47e1f02ad8..a698ae5035 100644 --- a/Content.Shared/Strip/SharedStrippableSystem.cs +++ b/Content.Shared/Strip/SharedStrippableSystem.cs @@ -29,11 +29,11 @@ public abstract class SharedStrippableSystem : EntitySystem if (args.Handled || args.Target != args.User) return; - StartOpeningStripper(args.User, component); + StartOpeningStripper(args.User, (uid, component)); args.Handled = true; } - public virtual void StartOpeningStripper(EntityUid user, StrippableComponent component, bool openInCombat = false) + public virtual void StartOpeningStripper(EntityUid user, Entity component, bool openInCombat = false) { } diff --git a/Content.Shared/Weather/SharedWeatherSystem.cs b/Content.Shared/Weather/SharedWeatherSystem.cs index 3aba97e92d..c7040515c8 100644 --- a/Content.Shared/Weather/SharedWeatherSystem.cs +++ b/Content.Shared/Weather/SharedWeatherSystem.cs @@ -101,13 +101,12 @@ public abstract class SharedWeatherSystem : EntitySystem var curTime = Timing.CurTime; - foreach (var comp in EntityQuery()) + var query = EntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var comp)) { if (comp.Weather.Count == 0) continue; - var uid = comp.Owner; - foreach (var (proto, weather) in comp.Weather) { var endTime = weather.EndTime; diff --git a/SpaceStation14.sln.DotSettings b/SpaceStation14.sln.DotSettings index 72e550ac6e..7d681e02b1 100644 --- a/SpaceStation14.sln.DotSettings +++ b/SpaceStation14.sln.DotSettings @@ -51,6 +51,7 @@ NEXT_LINE NEXT_LINE NEXT_LINE + AABB AL BB CC @@ -96,7 +97,7 @@ True Entity Component 1 - + 9 @@ -106,7 +107,7 @@ 6 True XAML Control - + True Client/Server Net Entity System 8 @@ -608,7 +609,7 @@ public sealed partial class $CLASS$ : Shared$CLASS$ { True True True - + True True True -- 2.51.2